コード例 #1
0
        public async Task <ActionResult <TicketPurchase> > PostTicketPurchase(TicketPurchase ticketPurchase)
        {
            _context.TicketPurchases.Add(ticketPurchase);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetTicketPurchase", new { id = ticketPurchase.Id }, ticketPurchase));
        }
コード例 #2
0
        public async Task <IActionResult> PutTicketPurchase(int id, TicketPurchase ticketPurchase)
        {
            if (id != ticketPurchase.PurchaseId)
            {
                return(BadRequest());
            }

            _context.Entry(ticketPurchase).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TicketPurchaseExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
コード例 #3
0
        public static TicketPurchase CreateTicket(Event Event, int tktQty)
        {
            TicketPurchase ticket = new TicketPurchase();

            ticket.Id             = Guid.NewGuid();
            ticket.Event          = Event;
            ticket.TicketQuantity = tktQty;
            return(ticket);
        }
コード例 #4
0
        public static PurchaseTicketResponse ConvertToPurchaseTicketResponse(this TicketPurchase ticketPurchase)
        {
            PurchaseTicketResponse response = new PurchaseTicketResponse();

            response.TicketId    = ticketPurchase.Id.ToString();
            response.EventName   = ticketPurchase.Event.Name;
            response.EventId     = ticketPurchase.Event.Id.ToString();
            response.NoOfTickets = ticketPurchase.TicketQuantity;
            return(response);
        }
コード例 #5
0
ファイル: PurchaseRepo.cs プロジェクト: Strikerred/TicketAPI
        // returns a tuple where Item1 corresponds to the success of the attempt, and Item2 is the associated status message
        public async Task <Tuple <bool, object> > TryAddPurchase(IEnumerable <int> eventSeatIds, string paymentMethod)
        {
            // check that event seats with the given ids exist and are available for purchase
            var purchaseSeats = new List <EventSeat>();

            foreach (int id in eventSeatIds)
            {
                var target = _context.EventSeat.SingleOrDefault(es => es.EventSeatId == id);
                if (target == null)
                {
                    return(new Tuple <bool, object>(false, $"An event seat with event_seat_id {id} does not exist"));
                }

                bool isPurchased = _context.TicketPurchaseSeat.ToList().Any(tps => tps.EventSeatId == id);
                if (isPurchased)
                {
                    return(new Tuple <bool, object>(false, $"The event seat with event_seat_id {id} has already been purchased"));
                }

                purchaseSeats.Add(target);
            }

            // make the purchase
            var purchase = new TicketPurchase {
                PaymentMethod    = paymentMethod,
                ConfirmationCode = _rand.Next(100000, 999999).ToString()
            };
            var     ticketPurchases   = new List <TicketPurchaseSeat>();
            decimal totalPurchaseCost = 0;

            foreach (EventSeat es in purchaseSeats)
            {
                decimal seatPrice    = (decimal)_context.Seat.SingleOrDefault(s => s.SeatId == es.SeatId).Price;
                var     seatPurchase = new TicketPurchaseSeat
                {
                    EventSeat    = es,
                    Purchase     = purchase,
                    SeatSubtotal = es.EventSeatPrice + seatPrice
                };
                ticketPurchases.Add(seatPurchase);
                totalPurchaseCost += (decimal)seatPurchase.SeatSubtotal;
            }

            purchase.PaymentAmount = totalPurchaseCost;
            _context.TicketPurchase.Add(purchase);
            await _context.SaveChangesAsync();

            foreach (TicketPurchaseSeat ticket in ticketPurchases)
            {
                _context.TicketPurchaseSeat.Add(ticket);
            }
            await _context.SaveChangesAsync();

            return(new Tuple <bool, object>(true, purchase));
        }
コード例 #6
0
        public async Task <IActionResult> Create([Bind("TransactionId,CustomerId,TicketId,Price,ExpirationDate,PurchaseDate,IsValid")] TicketPurchase ticketPurchase)
        {
            if (ModelState.IsValid)
            {
                _context.Add(ticketPurchase);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CustomerId"] = new SelectList(_context.Customer, "CustomerId", "CustomerId", ticketPurchase.CustomerId);
            return(View(ticketPurchase));
        }
コード例 #7
0
        public IActionResult Delete(int ticketPurchaseId, String ConfirmationCode)
        {
            TicketPurchaseRepository ticketPurchaseRepo = new TicketPurchaseRepository(_context);

            TicketPurchase purchase = _context.TicketPurchase.FirstOrDefault(tp => (tp.TicketPurchaseId == ticketPurchaseId) &&
                                                                             (tp.ConfirmationCode == ConfirmationCode));

            if (purchase == null)
            {
                return(BadRequest("Purchase Details Provided To Not Match Any Transactions On File (Purchase ID + Confirmation Code)"));
            }


            return(Ok(ticketPurchaseRepo.CancelTicketPurchase(purchase)));
        }
コード例 #8
0
        public string CancelTicketPurchase(TicketPurchase purchase)
        {
            var purchasedSeats = _context.EventSeat
                                 .Where(s => s.TicketPurchase.TicketPurchaseId == purchase.TicketPurchaseId)
                                 .ToList();

            foreach (EventSeat seat in purchasedSeats)
            {
                seat.TicketPurchase = null;
            }

            _context.TicketPurchase.Remove(purchase);
            _context.SaveChanges();

            return($"Cancelled Purchase: {purchase.TicketPurchaseId}");
        }
コード例 #9
0
        public virtual IActionResult AddTicketValidation([FromBody] TicketValidation ticketValidation)
        {
            // TODO ftn: Add validation to the ticketValidation parameter!!!
            // Return 400 - BadRequest if not valid!

            if (_context.Validations.FirstOrDefault(t => t.Id == ticketValidation.Id) != null)
            {
                return(StatusCode(StatusCodes.Status409Conflict)); // 409 already exists!
            }

            TicketPurchase ticket = _context.Purchases.FirstOrDefault(p => p.Code == ticketValidation.Ticket.Code);

            if (ticket == null)
            {
                return(StatusCode(StatusCodes.Status404NotFound));
            }

            if (ticket.EndDateTime < DateTime.Now)
            {
                return(StatusCode(StatusCodes.Status406NotAcceptable, ticket));
            }

            try
            {
                ticketValidation.Ticket             = ticket;
                ticketValidation.IsValid            = true;
                ticketValidation.ValidationDateTime = DateTime.Now.ToUniversalTime();

                Random r    = new Random();
                int    rInt = r.Next(1, 1000000000);
                ticketValidation.Id = rInt;

                _context.Validations.Add(ticketValidation);
                _context.Entry(ticketValidation.Controller).State = Microsoft.EntityFrameworkCore.EntityState.Unchanged;
                _context.SaveChanges();
                return(new ObjectResult(ticket));
                //return Created(Request.Host.ToString(), ticketValidation); // 201 Created successfuly.
            }
            catch (Exception)
            {
                _logger.LogError(LoggingEvents.INSERT_ITEM, "AddTicketType({ticketValidation}) NOT ADDED", ticketValidation);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
コード例 #10
0
        public async Task <ActionResult <TicketPurchase> > PostTicketPurchase(TicketPurchase ticketPurchase)
        {
            _context.TicketPurchase.Add(ticketPurchase);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (TicketPurchaseExists(ticketPurchase.PurchaseId))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetTicketPurchase", new { id = ticketPurchase.PurchaseId }, ticketPurchase));
        }
コード例 #11
0
        public async Task <ActionResult <PurchaseResponse> > Post([FromBody] PurchaseRequest purchase)
        {
            var result = await _purchaseRepo.TryAddPurchase(purchase.Seats, purchase.PaymentMethod);

            if (!result.Item1)
            {
                // error encountered when attempting to make purchase
                return(BadRequest(result.Item2));
            }

            TicketPurchase tp       = (TicketPurchase)result.Item2;
            var            response = new PurchaseResponse
            {
                PaymentAmount    = tp.PaymentAmount,
                ConfirmationCode = tp.ConfirmationCode,
                PaymentMethod    = tp.PaymentMethod,
                PurchaseId       = tp.PurchaseId
            };

            return(CreatedAtAction(nameof(Get), new { id = tp.PurchaseId }, response));
        }
コード例 #12
0
        public bool CreateTicketPurchase(TicketPurchaseJSON ticketPurchase)
        {
            bool isSuccessful = false;

            try {
                TicketPurchase purchase = new TicketPurchase {
                    PaymentMethod    = ticketPurchase.PaymentMethod,
                    PaymentAmount    = ticketPurchase.PaymentAmount,
                    ConfirmationCode = ticketPurchase.ConfirmationCode
                };

                _context.TicketPurchase.Add(purchase);

                foreach (int eventSeatId in ticketPurchase.EventSeatsPurchased)
                {
                    EventSeat seat = _context.EventSeat
                                     .Where(es => es.EventSeatId == eventSeatId)
                                     .FirstOrDefault();

                    if (seat != null && seat.TicketPurchase == null)
                    {
                        seat.TicketPurchase = purchase;
                    }
                    else
                    {
                        _context.TicketPurchase.Remove(purchase);
                        _context.SaveChanges();
                        throw new System.ArgumentException("Seat ID Invalid");
                    }
                }

                _context.SaveChanges();
                isSuccessful = true;
            } catch (Exception e) {
            }


            return(isSuccessful);
        }
コード例 #13
0
        public async Task <IActionResult> Edit(int id, [Bind("TransactionId,CustomerId,TicketId,Price,ExpirationDate,PurchaseDate,IsValid")] TicketPurchase ticketPurchase)
        {
            if (id != ticketPurchase.TicketId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    TicketPurchase _ticketPurchase = _context.TicketPurchase.Where(s => s.TransactionId == ticketPurchase.TransactionId).First();
                    _ticketPurchase.TransactionId  = ticketPurchase.TransactionId;
                    _ticketPurchase.CustomerId     = ticketPurchase.CustomerId;
                    _ticketPurchase.TicketId       = ticketPurchase.TicketId;
                    _ticketPurchase.Price          = ticketPurchase.Price;
                    _ticketPurchase.ExpirationDate = ticketPurchase.ExpirationDate;
                    _ticketPurchase.PurchaseDate   = ticketPurchase.PurchaseDate;
                    _ticketPurchase.IsValid        = ticketPurchase.IsValid;

                    _context.Update(_ticketPurchase);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TicketPurchaseExists(ticketPurchase.TicketId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CustomerId"] = new SelectList(_context.Customer, "CustomerId", "CustomerId", ticketPurchase.CustomerId);
            return(View(ticketPurchase));
        }
コード例 #14
0
        public TicketPurchaseViewModel GetTicketPurchase(TicketPurchase ticketPurchase)
        {
            var purchase = _context.TicketPurchase.Where(t => t.TicketPurchaseId == ticketPurchase.TicketPurchaseId)
                           .Select(t => new TicketPurchaseViewModel {
                TicketPurchaseId = t.TicketPurchaseId,
                PaymentMethod    = t.PaymentMethod,
                PaymentAmount    = t.PaymentAmount,
                ConfirmationCode = t.ConfirmationCode,
                Seats            = _context.EventSeat.Where(es => es.TicketPurchase.TicketPurchaseId == t.TicketPurchaseId)
                                   .Select(es => new TicketSeatDetailViewModel {
                    EventSeatId    = es.EventSeatId,
                    EventId        = es.Event.EventId,
                    EventName      = es.Event.EventName,
                    VenueName      = es.Event.Venue.VenueName,
                    SeatName       = es.Seat.SeatName,
                    RowName        = es.Seat.Row.RowName,
                    SectionName    = es.Seat.Row.Section.SectionName,
                    EventSeatPrice = (es.EventSeatPrice + es.Seat.Price)
                }).ToList()
            }).FirstOrDefault();

            return(purchase);
        }
コード例 #15
0
        public Event FindBy(Guid id)
        {
            Event Event = default(Event);

            string queryString = "SELECT * FROM dbo.Events WHERE Id = @EventId " +
                                 "SELECT * FROM dbo.PurchasedTickets WHERE EventId = @EventId " +
                                 "SELECT * FROM dbo.ReservedTickets WHERE EventId = @EventId;";

            using (SqlConnection connection =
                       new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = queryString;

                SqlParameter Idparam = new SqlParameter("@EventId", id.ToString());
                command.Parameters.Add(Idparam);

                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        reader.Read();
                        Event = new Event();
                        Event.PurchasedTickets = new List <TicketPurchase>();
                        Event.ReservedTickets  = new List <TicketReservation>();
                        Event.Allocation       = int.Parse(reader["Allocation"].ToString());
                        Event.Id   = new Guid(reader["Id"].ToString());
                        Event.Name = reader["Name"].ToString();

                        if (reader.NextResult())
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    TicketPurchase ticketPurchase = new TicketPurchase();
                                    ticketPurchase.Id             = new Guid(reader["Id"].ToString());
                                    ticketPurchase.Event          = Event;
                                    ticketPurchase.TicketQuantity = int.Parse(reader["TicketQuantity"].ToString());
                                    Event.PurchasedTickets.Add(ticketPurchase);
                                }
                            }
                        }

                        if (reader.NextResult())
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    TicketReservation ticketReservation = new TicketReservation();
                                    ticketReservation.Id              = new Guid(reader["Id"].ToString());
                                    ticketReservation.Event           = Event;
                                    ticketReservation.ExpiryTime      = DateTime.Parse(reader["ExpiryTime"].ToString());
                                    ticketReservation.TicketQuantity  = int.Parse(reader["TicketQuantity"].ToString());
                                    ticketReservation.HasBeenRedeemed = bool.Parse(reader["HasBeenRedeemed"].ToString());
                                    Event.ReservedTickets.Add(ticketReservation);
                                }
                            }
                        }
                    }
                }
            }

            return(Event);
        }
コード例 #16
0
ファイル: TicketsApi.cs プロジェクト: xia7410/TripApp
        public virtual async Task <IActionResult> AddTicketPurchase([FromBody] TicketPurchase ticketPurchase)
        {
            // TODO FTN: Add validation!
            var    loggedInUserId      = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
            var    buyerUsername       = User.FindFirst(ClaimTypes.Name).Value;
            var    buyerFirstName      = User.FindFirst(ClaimTypes.GivenName).Value;
            string deviceId            = null;
            bool   enableNotifications = true;

            var hasTypeAndUser = ticketPurchase != null &&
                                 ticketPurchase.TypeId != null &&
                                 ticketPurchase.TypeId > 0 &&
                                 ticketPurchase.UserId != null &&
                                 ticketPurchase.UserId > 0 &&
                                 ticketPurchase.NumberOfPassangers > 0;

            if (!hasTypeAndUser)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, ticketPurchase));
            }

            if (loggedInUserId != ticketPurchase.UserId)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, ticketPurchase));
            }

            try
            {
                if (_context.Purchases.FirstOrDefault(p => p.Id == ticketPurchase.Id) != null)
                {
                    return(StatusCode(StatusCodes.Status409Conflict, ticketPurchase)); // 409 already exists!
                }

                deviceId            = Request.Headers["DeviceID"];
                enableNotifications = Request.Headers["Notifications"].Any() ? Request.Headers["Notifications"] != "false" : true;

                var type = _context.Types.First(t => t.Id == ticketPurchase.TypeId);
                var user = _context.Users.First(u => u.Id == ticketPurchase.UserId);

                if (user.Balance - type.Price * ticketPurchase.NumberOfPassangers < 0.0d)
                {
                    return(StatusCode(StatusCodes.Status402PaymentRequired, ticketPurchase));
                }

                ticketPurchase.Code          = Guid.NewGuid();
                ticketPurchase.StartDateTime = DateTime.Now.ToUniversalTime().AddMinutes(_configuration.GetSection(Startup.AppSettingsConfigurationSectionKey).GetValue <int>(Startup.AppSettingsMinutesUntilTicketStartKey));
                ticketPurchase.EndDateTime   = DateTime.Now.ToUniversalTime().AddMinutes(type.Duration.Value * 60 + _configuration.GetSection(Startup.AppSettingsConfigurationSectionKey).GetValue <int>(Startup.AppSettingsMinutesUntilTicketStartKey));
                ticketPurchase.Price         = type.Price;
                user.Balance = user.Balance - type.Price * ticketPurchase.NumberOfPassangers;

                _context.Purchases.Add(ticketPurchase);
                _context.SaveChanges();

                ticketPurchase = _context.Purchases.Include(u => u.User).First(p => p.Id == ticketPurchase.Id);
            }
            catch (Exception)
            {
                _logger.LogError(LoggingEvents.INSERT_ITEM, "AddTicketPurchase({ticketPurchase}) NOT ADDED", ticketPurchase);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            string notificationSent = "[ALL: False1 ; Device ID: False2]";

            if (_newBuyerIsBIGNews)
            {
                var notification = new Notification()
                {
                    Title   = "We have a new ticket buyer!",
                    Message = $"User: {buyerUsername} have bought a ticket of type id: '{ticketPurchase.TypeId}'! YEEEAAAH!",
                    Topic   = "news"
                };

                var result = await _notificationService.Send(notification);

                notificationSent = notificationSent.Replace("False1", result.ToString());
            }

            if (!string.IsNullOrEmpty(deviceId) && enableNotifications)
            {
                var notification = new Notification()
                {
                    Title    = "Your have bought a ticket. Congrats!",
                    Message  = $"Hello {buyerFirstName}. Your ticket '{ticketPurchase.Code}' is ready!",
                    DeviceID = deviceId
                };

                var result = await _notificationService.Send(notification);

                notificationSent = notificationSent.Replace("False2", result.ToString());
            }

            Response.Headers.Add("DeviceID", deviceId);
            Response.Headers.Add("Notifications", enableNotifications.ToString());
            Response.Headers.Add("NotificationSent", notificationSent.ToString());
            return(StatusCode(StatusCodes.Status201Created, ticketPurchase));
        }
コード例 #17
0
        public static void Initialize(ssdticketsContext context)
        {
            context.Database.EnsureCreated();

            if (context.Venue.Any())
            {
                // DB has already been seeded
                return;
            }

            // Initialization constants
            const string VENUE_NAME = "BCIT Stadium";

            const int NUM_SECTIONS     = 10;
            const int ROWS_PER_SECTION = 10;
            const int SEATS_PER_ROW    = 10;
            const int CAPACITY         = NUM_SECTIONS * ROWS_PER_SECTION * SEATS_PER_ROW;

            const decimal VENUE_SEAT_PRICE = 12.50m;

            // Venue
            Venue bcit = new Venue {
                Capacity = CAPACITY, VenueName = VENUE_NAME
            };

            context.Venue.Add(bcit);
            context.SaveChanges();

            // Sections
            List <Section> sections = new List <Section>();

            for (int i = 0; i < NUM_SECTIONS; i++)
            {
                var section = new Section
                {
                    VenueName   = bcit.VenueName,
                    SectionName = $"Section {i + 1}"
                };

                sections.Add(section);
                context.Section.Add(section);
            }
            context.SaveChanges();

            // Rows
            List <Row> rows = new List <Row>();

            foreach (Section s in sections)
            {
                for (int i = 0; i < ROWS_PER_SECTION; i++)
                {
                    var row = new Row {
                        Section = s, RowName = $"Row {i + 1}"
                    };
                    rows.Add(row);
                    context.Row.Add(row);
                }
                context.SaveChanges();
            }

            // Seats
            List <Seat> seats = new List <Seat>();

            foreach (Row r in rows)
            {
                for (int i = 0; i < SEATS_PER_ROW; i++)
                {
                    var seat = new Seat {
                        Row = r, Price = VENUE_SEAT_PRICE
                    };
                    seats.Add(seat);
                    context.Seat.Add(seat);
                }
                context.SaveChanges();
            }

            // Events
            var events = new Event[] {
                new Event {
                    EventName = "Conference", VenueName = VENUE_NAME
                },
                new Event {
                    EventName = "Barbecue", VenueName = VENUE_NAME
                },
                new Event {
                    EventName = "Hackathon", VenueName = VENUE_NAME
                },
                new Event {
                    EventName = "Convention", VenueName = VENUE_NAME
                },
                new Event {
                    EventName = "Soccer Championships", VenueName = VENUE_NAME
                }
            };

            foreach (Event e in events)
            {
                context.Event.Add(e);
            }
            context.SaveChanges();

            // Event Seats
            // Prices for events are 10.50, plus an extra $5 for each row closer to the front
            //   (eg. if there are 10 rows, the 10th row will have no extra cost, and the 1st row will be an extra $45)
            foreach (Event e in events)
            {
                decimal eventPrice = 10.50m;

                foreach (Seat venueSeat in seats)
                {
                    var eventSeat = new EventSeat {
                        Seat           = venueSeat,
                        Event          = e,
                        EventSeatPrice = eventPrice + (5 * (ROWS_PER_SECTION - getRowNumber(venueSeat.Row)))
                    };
                    context.EventSeat.Add(eventSeat);
                }
                context.SaveChanges();
            }

            // Ticket Purchases
            // Each event has the first row of section 1 sold out
            // Each event also has seats 1 and 2 sold in the second row of section 1
            foreach (Event e in events)
            {
                // Purchase first row in a single transaction
                IEnumerable <EventSeat> firstRow = e.EventSeat.Where(es => getRowNumber(es.Seat.Row) == 1 && es.Seat.Row.SectionId == 1);
                var firstRowPurchase             = new TicketPurchase {
                    PaymentMethod = "Credit Card", ConfirmationCode = "123456"
                };
                decimal totalPurchaseCost = 0;

                var tickets = new List <TicketPurchaseSeat>();
                foreach (EventSeat es in firstRow)
                {
                    var seatPurchase = new TicketPurchaseSeat {
                        EventSeat    = es,
                        Purchase     = firstRowPurchase,
                        SeatSubtotal = es.EventSeatPrice + es.Seat.Price
                    };
                    tickets.Add(seatPurchase);
                    totalPurchaseCost += (decimal)seatPurchase.SeatSubtotal;
                }

                firstRowPurchase.PaymentAmount = totalPurchaseCost;
                context.TicketPurchase.Add(firstRowPurchase);
                context.SaveChanges();

                foreach (TicketPurchaseSeat ticket in tickets)
                {
                    context.TicketPurchaseSeat.Add(ticket);
                }
                context.SaveChanges();

                // Purchase seats 1 and 2 of second row
                IEnumerable <EventSeat> secondRowSeats = e.EventSeat.Where(
                    es => getRowNumber(es.Seat.Row) == 2 && es.Seat.Row.SectionId == 1 && (es.SeatId % SEATS_PER_ROW == 1 || es.SeatId % SEATS_PER_ROW == 2));
                var secondRowPurchase = new TicketPurchase {
                    PaymentMethod = "Debit", ConfirmationCode = "789123"
                };
                totalPurchaseCost = 0;

                tickets = new List <TicketPurchaseSeat>();
                foreach (EventSeat es in secondRowSeats)
                {
                    var seatPurchase = new TicketPurchaseSeat
                    {
                        EventSeat    = es,
                        Purchase     = secondRowPurchase,
                        SeatSubtotal = es.EventSeatPrice + es.Seat.Price
                    };
                    tickets.Add(seatPurchase);
                    totalPurchaseCost += (decimal)seatPurchase.SeatSubtotal;
                }

                secondRowPurchase.PaymentAmount = totalPurchaseCost;
                context.TicketPurchase.Add(secondRowPurchase);
                context.SaveChanges();

                foreach (TicketPurchaseSeat ticket in tickets)
                {
                    context.TicketPurchaseSeat.Add(ticket);
                }
                context.SaveChanges();
            }
        }
コード例 #18
0
        /// <summary>
        /// Seed database with predefined data.
        /// </summary>
        /// <param name="serviceProvider">DI service provider instance.</param>
        public static void Seed(IServiceProvider serviceProvider)
        {
            var context = serviceProvider.GetService <TripAppContext>();
            var hasher  = serviceProvider.GetService <IPasswordHasher <User> >();

            string defaultPass = hasher.HashPassword(null, defaultPassword);
            string devPass     = hasher.HashPassword(null, devPassword);

            // Users:
            User admin = new User(1, "admin", "Pera", "Administratovic", "*****@*****.**", defaultPass, "333-123", "administrator", 20.0d);

            context.Users.Add(admin);

            User passenger = new User(2, "a", "Darinka", "Putnik", "*****@*****.**", defaultPass, "333-444", "passenger", 25.0d);

            context.Users.Add(passenger);

            User controller = new User(3, "ctrl", "Milos", "Nagib", "*****@*****.**", defaultPass, "333-555", "controller", 50.0d);

            context.Users.Add(controller);

            User devadmin = new User(4, "dev", "Bill", "Linux Idol", "*****@*****.**", devPass, "123-456", "administrator", 100.0d);

            context.Users.Add(devadmin);

            // Purchase codes:
            PurchaseCode code   = new PurchaseCode(1, Guid.Parse("bc495959-9aa7-447d-905d-0dfc74c16188"), 5.0d, DateTime.Now.ToUniversalTime(), null, false, null);
            PurchaseCode code2  = new PurchaseCode(2, Guid.Parse("e1f80425-7f55-4a2a-b777-f6833c1758ae"), 10.0d, DateTime.Now.ToUniversalTime(), null, false, null);
            PurchaseCode code3  = new PurchaseCode(3, Guid.Parse("33994bf3-0489-4897-9b87-853c76124ee1"), 25.0d, DateTime.Now.ToUniversalTime(), null, false, null);
            PurchaseCode code4  = new PurchaseCode(4, Guid.Parse("6d043fbc-5fdc-40a0-9cbb-58bf7aef1744"), 50.0d, DateTime.Now.ToUniversalTime(), null, false, null);
            PurchaseCode code5  = new PurchaseCode(5, Guid.Parse("6d043fac-5fdc-40a0-9cbb-58bf7aef1741"), 100.0d, DateTime.Now.ToUniversalTime(), null, false, null);
            PurchaseCode code6  = new PurchaseCode(6, Guid.Parse("d6b11c76-a0f5-4ebf-b840-6d1a7d1b73ba"), 5.0d, DateTime.Now.ToUniversalTime(), null, false, null);
            PurchaseCode code7  = new PurchaseCode(7, Guid.Parse("ec61f4c7-3f0d-4754-ab27-8756efae6542"), 10.0d, DateTime.Now.ToUniversalTime(), null, false, null);
            PurchaseCode code8  = new PurchaseCode(8, Guid.Parse("39d3e085-5243-4ef3-a619-7d9765329f29"), 10.0d, DateTime.Now.ToUniversalTime(), null, false, null);
            PurchaseCode code9  = new PurchaseCode(9, Guid.Parse("4806c7e3-2c2f-4581-b8c1-b82537098ad4"), 10.0d, DateTime.Now.ToUniversalTime(), null, false, null);
            PurchaseCode code10 = new PurchaseCode(10, Guid.Parse("9999c59f-5827-47f6-a837-d6c6c70ed7a9"), 10.0d, DateTime.Now.ToUniversalTime(), null, false, null);

            context.Codes.Add(code);
            context.Codes.Add(code2);
            context.Codes.Add(code3);
            context.Codes.Add(code4);
            context.Codes.Add(code5);
            context.Codes.Add(code6);
            context.Codes.Add(code7);
            context.Codes.Add(code8);
            context.Codes.Add(code9);
            context.Codes.Add(code10);


            // Ticket types:
            TicketType typeHour  = new TicketType(1, "Hourly ticket", 1, 1.2d);
            TicketType typeDay   = new TicketType(2, "Daily ticket", 24, 5d);
            TicketType typeMonth = new TicketType(4, "Monthly ticket", 24 * 30, 40d);
            TicketType typeWeek  = new TicketType(3, "Weekly ticket", 24 * 7, 16d);

            context.Types.Add(typeHour);
            context.Types.Add(typeDay);
            context.Types.Add(typeMonth);
            context.Types.Add(typeWeek);

            // Purchases:
            TicketPurchase purchase = new TicketPurchase(750, Guid.NewGuid(), 30.0d, DateTime.Now, DateTime.Now.AddMinutes(typeHour.Duration.Value * 60), 1, typeHour, passenger);

            purchase.UserId = passenger.Id;
            TicketPurchase purchase2 = new TicketPurchase(751, Guid.NewGuid(), 30.0d, DateTime.Now.AddHours(-3), DateTime.Now.AddHours(-2), 2, typeHour, passenger);

            purchase2.UserId = passenger.Id;
            TicketPurchase purchase3 = new TicketPurchase(752, Guid.NewGuid(), 30.0d, DateTime.Now.AddHours(-12), DateTime.Now.AddHours(12), 1, typeDay, passenger);

            purchase3.UserId = passenger.Id;
            TicketPurchase purchase4 = new TicketPurchase(753, Guid.NewGuid(), 30.0d, DateTime.Now, DateTime.Now.AddHours(24 * 30), 1, typeMonth, passenger);

            purchase4.UserId = passenger.Id;

            context.Purchases.Add(purchase);
            context.Purchases.Add(purchase2);
            context.Purchases.Add(purchase3);
            context.Purchases.Add(purchase4);

            // Validations:
            TicketValidation validation = new TicketValidation(1, DateTime.Now.AddMinutes(2).ToUniversalTime(), true, purchase, controller);

            context.Validations.Add(validation);

            context.SaveChanges();
        }