示例#1
0
        public async Task <List <object> > PostXmlExtractorAsync([FromBody] string value)
        {
            var           extractionHelper = new ExtractionHelper.ExtractionHelper(value);
            List <IItem>  items            = extractionHelper.extractAsync();
            List <object> created_objects  = new List <object>();

            foreach (IItem item in items)
            {
                if (item.ItemType == ItemType.Expense)
                {
                    ExpenseContext.ExpenseItems.Add((ExpenseItem)item);
                    await ExpenseContext.SaveChangesAsync();

                    CreatedAtActionResult expense_create = CreatedAtAction(nameof(ExpenseController.GetExpenseItem), new { id = item.Id }, item);
                    created_objects.Add(expense_create.Value);
                }
                if (item.ItemType == ItemType.Reservation)
                {
                    ReservationContext.ReservationItems.Add((ReservationItem)item);
                    await ReservationContext.SaveChangesAsync();

                    CreatedAtActionResult reserv_create = CreatedAtAction(nameof(ReservationController.GetReservationItem), new { id = item.Id }, item);
                    created_objects.Add(reserv_create.Value);
                }
            }
            return(created_objects);
        }
示例#2
0
        private async void OpenLand(object obj)   //Aktiv wenn Button gedrückt wird
        {
            IUser _user = new UserController();

            gUser.username = _username;
            var passwordBox = obj as PasswordBox;

            using var context = new ReservationContext();
            if (context.Database.CanConnect())
            {
                var verified = await _user.Login(_username, passwordBox.Password);

                if (verified == 2)
                {
                    User _newUser = new User();
                    _newUser.Username = _username;
                    _navigationViewModel.SelectedViewModel = new LandingPageViewModel(_navigationViewModel, _newUser);

                    // start logout check thread + logout time in min
                    AutoLogOff.CreateLogoutThread(_navigationViewModel, _newUser, 10);
                }
                else if (verified == 1)
                {
                    Info = "Sie sind bereits eingeloggt!";
                }
                else
                {
                    Info = "Passwort oder Benutzername ist falsch!";
                }
            }
            else
            {
                MessageBox.Show("Keine Verbindung zur Datenbank möglich.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
示例#3
0
        public async Task <LocationResult> GetLocation(int locationId)
        {
            using (var context = new ReservationContext())
            {
                Location location = await context.Location.FirstOrDefaultAsync(x => x.Id == locationId);

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

                var googleLocation = await _placesDetail.GetFor(location.PlacesId);

                Ok();
                return(new LocationResult()
                {
                    Id = location.Id,
                    Name = location.Name,
                    FillStatus = location.FillStatus,
                    Capacity = location.Capacity,
                    SlotDuration = location.SlotDuration,
                    SlotSize = location.SlotSize,
                    Openings = location.LocationOpenings.Select(x => new OpeningResult(x)).ToList(),
                    Latitude = googleLocation.Latitude,
                    Longitude = googleLocation.Longitude,
                    Address = googleLocation.Address
                });
            }
        }
示例#4
0
 //Makes a list with all of the Reservations in the Database
 public List <Reservation> GetAll()
 {
     using (context = new ReservationContext())
     {
         return(context.Reservations.ToList());
     }
 }
示例#5
0
        private async Task <bool> IsReservationAllowedAsync(ReservationContext context, int locationId, DateTime dateTime)
        {
            var openingHours = await context.LocationOpening
                               .Where(x => x.LocationId == locationId &&
                                      x.OpeningDays == dateTime.DayOfWeek.ToString() &&
                                      x.OpeningTime.TimeOfDay <= dateTime.TimeOfDay &&
                                      x.ClosingTime.TimeOfDay >= dateTime.TimeOfDay)
                               .SingleOrDefaultAsync();

            if (openingHours == null)
            {
                return(false);
            }

            var location = await context.Location.SingleAsync(x => x.Id == locationId);

            var rangeStart = dateTime.AddMinutes(-location.SlotDuration);
            var rangeEnd   = dateTime.AddMinutes(location.SlotDuration);

            var numberOfReservations = await context.Reservation.Where(x => x.LocationId == locationId &&
                                                                       ((x.StartTime >= rangeStart &&
                                                                         x.StartTime <= rangeEnd) ||
                                                                        (x.StartTime.AddMinutes(location.SlotDuration) >=
                                                                         rangeStart &&
                                                                         x.StartTime.AddMinutes(location.SlotDuration) <=
                                                                         rangeEnd))).CountAsync();

            return(numberOfReservations < location.SlotSize);
        }
示例#6
0
        public async Task <IActionResult> Task(string ticketId, int locationId)
        {
            using (var context = new ReservationContext())
            {
                var reservation = await context.Reservation
                                  .Include(x => x.Location)
                                  .FirstOrDefaultAsync(x => x.ReservationToken == ticketId && x.LocationId == locationId);

                if (reservation == null)
                {
                    return(Ok(new TicketValidationResult()
                    {
                        ValidationResult = false
                    }));
                }

                var currentTime = DateTime.Now.ToUniversalTime();
                if (reservation.StartTime <= currentTime &&
                    currentTime <= reservation.StartTime.AddMinutes(reservation.Location.SlotDuration))
                {
                    return(Ok(new TicketValidationResult()
                    {
                        ValidationResult = true
                    }));
                }

                return(Ok(new TicketValidationResult()
                {
                    ValidationResult = false
                }));
            }
        }
示例#7
0
        public async Task <GetValidKeysResult> ValidKeys(int locationId, int amountTimeSlots)
        {
            using (var context = new ReservationContext()) {
                var location = await context.Location
                               .Include(x => x.Reservations)
                               .FirstOrDefaultAsync(x => x.Id == locationId);

                if (location == null)
                {
                    NotFound(nameof(locationId));
                    return(null);
                }

                List <string> validKeys = context.Reservation
                                          .Where(x => x.LocationId == locationId &&
                                                 x.StartTime.AddMinutes(location.SlotDuration) > DateTime.Now &&
                                                 x.StartTime < DateTime.Now.AddMinutes(location.SlotDuration * amountTimeSlots))
                                          .Select(res => res.HumanReadableToken)
                                          .ToList();

                Ok();
                return(new GetValidKeysResult {
                    ValidKeys = validKeys
                });
            }
        }
示例#8
0
        public async Task <IActionResult> Reserve(int locationId, DateTime dateTime, string deviceId)
        {
            using (var context = new ReservationContext()) {
                var location = await context.Location.FirstOrDefaultAsync(x => x.Id == locationId);

                if (location == null)
                {
                    return(NotFound(nameof(deviceId)));
                }

                if (await IsReservationAllowedAsync(context, locationId, dateTime) == false)
                {
                    return(BadRequest("Error: Reservation not allowed."));
                }


                var humanReadableToken = _humanReadableKeyGeneratorService.GetHumanReadableText();
                var reservationToken   = Guid.NewGuid().ToString();

                (location.Reservations ??= new List <Reservation>()).Add(new Reservation {
                    DeviceId           = deviceId,
                    StartTime          = dateTime,
                    HumanReadableToken = humanReadableToken,
                    ReservationToken   = reservationToken
                });

                await context.SaveChangesAsync();

                return(Ok(new CreateReservationResult()
                {
                    HumanReadableToken = humanReadableToken,
                    ReservationToken = reservationToken
                }));
            }
        }
示例#9
0
 static void Seed()
 {
     Console.WriteLine("Hello World!");
     using var context = new ReservationContext();
     var seeder = new DBSeed();
     //seeder.SeedDataToDB();
 }
示例#10
0
        public async Task <IActionResult> Create([FromBody] UserModel model)
        {
            using (var context = new ReservationContext()) {
                if (await context.User.AnyAsync(x => x.Email == model.Email))
                {
                    return(Conflict());
                }

                var dbModel = new User()
                {
                    Email    = model.Email,
                    Name     = model.Name,
                    Password = model.Password.HashAsSha256(),
                    Type     = model.Type
                };
                await context.User.AddAsync(dbModel);

                await context.SaveChangesAsync();

                return(Ok(new UserModelWithId()
                {
                    Id = dbModel.Id,
                    Name = dbModel.Name,
                    Email = dbModel.Email,
                    Password = String.Empty,
                    Type = dbModel.Type
                }));
            }
        }
示例#11
0
        /// <summary>
        /// If a reservation for the given room and the given timestamp exist, return the reservation
        /// </summary>
        /// <param name="room"></param>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public async Task <(string, string)> GetReservationForRoom(Room room, DateTime timestamp)
        {
            await using var context = new ReservationContext();

            var innerjoin = from r in context.Reservations
                            join u in context.Users on r.User.Username equals u.Username
                            join ri in context.Rights on u.Rights.RightsName equals ri.RightsName
                            where r.Room == room && r.StartTime <= timestamp && r.EndTime >= timestamp
                            select new
            {
                User       = r.User,
                Room       = r.Room,
                RightsName = ri.RightsName
            };

            var returnTuple = ("", "");

            if (innerjoin.Count() > 0)
            {
                returnTuple = (innerjoin.First().User.Username, innerjoin.First().RightsName);
            }

            // var reservation = await context.Reservations.Where(x => x.Room.Equals(room) && x.StartTime <= timestamp && x.EndTime >= timestamp).FirstOrDefaultAsync();

            return(returnTuple);
        }
示例#12
0
        public async Task <IActionResult> Update([FromBody] UserModelWithId model)
        {
            using (var context = new ReservationContext()) {
                var user = await context.User.SingleOrDefaultAsync(x => x.Id == model.Id);

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

                if (await context.User.AnyAsync(x => x.Email == user.Email))
                {
                    return(BadRequest("Email already used."));
                }

                user.Name  = model.Name;
                user.Email = model.Email;
                user.Type  = model.Type;

                if (string.IsNullOrWhiteSpace(model.Password) == false)
                {
                    user.Password = model.Password.HashAsSha256();
                }

                model.Password = string.Empty;
                await context.SaveChangesAsync();
            }

            return(Ok(model));
        }
示例#13
0
        public Responses.ReservationResponse ReserveBestSeats(int customerID, int eventID, int numberOfSeats, int maxRows)
        {
            Responses.ReservationResponse response = new Responses.ReservationResponse();

            // Check if valid event and customer
            bool invalidEvent    = false;
            bool invalidCustomer = false;

            using (var db = new ReservationContext())
            {
                int eventCount = db.Events.Where(w => w.ID.Equals(eventID)).Count();
                invalidEvent = (eventCount != 1); // Should be exactly 1 event per EventID

                int customerCount = db.Customers.Where(w => w.ID.Equals(customerID)).Count();
                invalidCustomer = (customerCount != 1); // Should be exactly 1 cutomer per CustomerID
            }

            if (invalidEvent)
            {
                return(Responses.ReservationResponse.InvalidEventResponse);
            }
            else if (invalidCustomer)
            {
                return(Responses.ReservationResponse.InvalidCustomerResponse);
            }


            // Create list of seats that are reserved
            List <Seat> seats = FindSeatsInVenue(numberOfSeats, eventID, maxRows);

            // Create Order object and save in db, will be null if order cannot be saved
            Order order = this.CreateOrder(customerID, eventID, seats);

            // If a valid order is created prepare success ReservationResponse with seat information
            if (order != null)
            {
                response.Success = true;
                response.Message = "Your seats were successfully reserved.";

                response.OrderID = order.ID;
                response.Seats   = new List <Responses.ReservationSeat>();

                foreach (OrderSeat seat in order.OrderSeats)
                {
                    Responses.ReservationSeat newSeat = new Responses.ReservationSeat();
                    newSeat.RowNumber  = seat.Seat.Row.RowNumber;
                    newSeat.SeatNumber = seat.Seat.SeatNumber;

                    response.Seats.Add(newSeat);
                }
            }
            // If invalid order then return failure response
            else
            {
                response = Responses.ReservationResponse.ReservationCriteriaNotMetResponse;
            }

            return(response);
        }
示例#14
0
        public async Task <List <Reservation> > GetAllReservations()
        {
            await using var context = new ReservationContext();

            return(await context.Reservations.Include(x => x.User)
                   .Include(x => x.Room)
                   .ToListAsync());
        }
示例#15
0
 public ReservationManager(ReservationContext ticketContext,
                           RepertoryContext repertoryContext,
                           MovieContext movieContext)
 {
     _reservationContext = ticketContext;
     _repertoryContext   = repertoryContext;
     _movieContext       = movieContext;
 }
示例#16
0
        private List <Seat> FindSeatsInVenue(int seats, int eventID, int maxRows)
        {
            List <Seat> selectedSeats = new List <Seat>();

            using (var db = new ReservationContext())
            {
                // Get list of Rows available in the Event Venue
                List <Row> rows = db.Events
                                  .Where(w => w.ID.Equals(eventID))
                                  .FirstOrDefault()
                                  .Venue
                                  .Rows
                                  .ToList();

                // Get IDs of seats that have already been reserved for this event
                int[] takenSeats = db.OrderSeats
                                   .Where(w => w.Order.EventID.Equals(eventID))
                                   .Select(s => s.SeatID)
                                   .ToArray();

                int seatsNeeded   = seats;
                int rowsRemaining = maxRows;

                foreach (Row row in rows)
                {
                    // Get contiguous available seats in row
                    List <Seat> newSeats = this.FindSeatsInRow(seatsNeeded, row, takenSeats);

                    if (newSeats.Count > 0)
                    {
                        seatsNeeded -= newSeats.Count;
                        rowsRemaining--;
                        selectedSeats.AddRange(newSeats);
                    }

                    if (seatsNeeded == 0) // All requested seats have been reserved
                    {
                        break;
                    }
                    else if (rowsRemaining == 0) // Seats have been split between too many rows
                    {
                        seatsNeeded += this.RemoveNearestRow(ref selectedSeats);
                        rowsRemaining++;
                    }
                    else if (rowsRemaining < 0)
                    {
                        throw new InvalidOperationException("Seats spread across too many rows.");
                    }
                }

                if (seatsNeeded > 0)
                {
                    selectedSeats.Clear();
                }

                return(selectedSeats);
            }
        }
示例#17
0
        public ReservationController(ReservationContext context)
        {
            _context = context;

            if (_context.ReservationItems.Count() == 0)
            {
                _context.SaveChanges();
            }
        }
 public virtual void Edit(T entity)
 {
     using (context = new ReservationContext())
     {
         context.Entry(entity).State = EntityState.Modified;
         context.SaveChanges();
         //context.Entry(entity).Reload();
     }
 }
示例#19
0
        /// <summary>
        /// Return a specified Room
        /// </summary>
        /// <param name="roomnumber">Number identifying a room</param>
        /// <param name="building">String identifying a Building</param>
        /// <returns></returns>
        public async Task <Room> GetCurrentStatusForRoom(int roomnumber, string building)
        {
            await using var context = new ReservationContext();

            var concreteRoom = await context.Rooms.Where(y => y.Building.Equals(building))
                               .Where(x => x.RoomNr == roomnumber)
                               .FirstOrDefaultAsync();

            return(concreteRoom);
        }
示例#20
0
        public async Task <List <Reservation> > GetUserReservations(User user)
        {
            await using var context = new ReservationContext();

            var concreteUser = await context.Users.FindAsync(user.Username);

            return(await context.Reservations.Where(x => x.User == concreteUser)
                   .Include(x => x.Room)
                   .ToListAsync());
        }
示例#21
0
        /// <summary>
        /// Returns a specified Floor
        /// </summary>
        /// <param name="floor">Number identifying a floor</param>
        /// <param name="building">String identifying a Building</param>
        /// <returns></returns>
        public async Task <List <Room> > GetCurrentStatusForFloor(string building, int floor)
        {
            await using var context = new ReservationContext();

            var concreteFloor = await context.Rooms.Where(x => x.Building.Equals(building)).Where(y => y.Floor == floor)
                                .OrderBy(x => x.RoomNr)
                                .Include(x => x.Attribute)
                                .ToListAsync();

            return(concreteFloor);
        }
示例#22
0
        /// <summary>
        /// Gets all rooms of a floor in a given Building
        /// </summary>
        /// <param name="building">The building where the rooms should be</param>
        /// <param name="floor">The floor of the rooms</param>
        /// <returns></returns>
        public async Task <List <Room> > GetFloor(int floor, string building)
        {
            await using var context = new ReservationContext();

            return(await context.Rooms.Where(x => x.Floor == floor)
                   .Where(x => x.Building.Equals(building))
                   .OrderBy(x => x.RoomNr)
                   .ToListAsync());

            ;
        }
示例#23
0
        public void TearDown()
        {
            using var context = new ReservationContext();
            var dummyData = context.Reservations.Where(x => x.StartTime > new DateTime(2021, 12, 31));

            foreach (var reservation in dummyData)
            {
                context.Reservations.Remove(reservation);
            }

            context.SaveChanges();
        }
示例#24
0
        public IList <Reservation> GetReservationsByTimeinterval(DateTime searchStartDateUtc, DateTime searchEndDateUtc)
        {
            ReservationContext context = new ReservationContext();

            IList <Reservation> reservationsInSearchPeriod =
                (from r in context.Reservations
                 where r.ReservedDate >= searchStartDateUtc &&
                 r.ReservedDate <= searchEndDateUtc
                 select r).ToList();

            return(reservationsInSearchPeriod);
        }
 public int Add(T entity)
 {
     using (context = new ReservationContext())
     {
         context.Set <T>().Add(entity);
         context.SaveChanges();
         DbPropertyValues sa      = context.Entry(entity).GetDatabaseValues();
         string           keyName = sa.PropertyNames.First();
         int Id = sa.GetValue <int>(keyName);
         return(Id);
     }
 }
示例#26
0
        static void Main(string[] args)
        {
            var reservationContext = new ReservationContext();
            var state = (ReservationState)reservationContext.State;

            state.AuthorizationProcess = new AuthorizationProcess
            {
                Id = 10000,
                MasterLocatorId = 393875,
                AuthFlowType    = AuthFlowType.ByCorporate
            };

            reservationContext.StateSubject.Subscribe(rs =>
            {
                Console.WriteLine("OnNext: " + rs.Name);
            },
                                                      ex => Console.WriteLine("OnError: " + ex),
                                                      () => Console.WriteLine("OnComplete"));

            reservationContext.StateSubject
            .Where(rs => rs.StateInfo != null && rs.StateInfo.StateHook == StateHook.OnEntry)
            .Subscribe(rs =>
            {
                Console.WriteLine("OnNext: " + rs.Name);
                Console.WriteLine("OnNext Hook: " + rs.StateInfo.StateHook);
            },
                       ex => Console.WriteLine("OnError: " + ex),
                       () => Console.WriteLine("OnComplete"));

            reservationContext.StateSubject
            .Where(rs => rs.StateInfo != null && rs.StateInfo.StateHook == StateHook.OnExit)
            .Subscribe(rs =>
            {
                Console.WriteLine("OnNext: " + rs.Name);
                Console.WriteLine("OnNext Hook: " + rs.StateInfo.StateHook);
            },
                       ex => Console.WriteLine("OnError: " + ex),
                       () => Console.WriteLine("OnComplete"));

            reservationContext.TransitionSubject.Subscribe(st =>
            {
                Console.WriteLine("current: {0}, new: {1}", st.From, st.To);
            });

            reservationContext.RequestReview();
            reservationContext.Approve();
            reservationContext.Approve();
            reservationContext.Cancel();
            reservationContext.Pay();
            //reservationContext.EmitTicket();
            Console.ReadKey();
        }
示例#27
0
        public async Task SeedAsync(ReservationContext context, IHostEnvironment env)
        {
            using (context)
            {
                if (!context.Offices.Any())
                {
                    context.Offices.AddRange(
                        new Office("Amsterdam", new TimeSpan(08, 30, 00), new TimeSpan(17, 00, 00))
                    {
                        Id = 1
                    },
                        new Office("Berlin", new TimeSpan(08, 30, 00), new TimeSpan(20, 00, 00))
                    {
                        Id = 2
                    }
                        );
                    await context.SaveChangesAsync();
                }

                if (!context.MeetingRooms.Any())
                {
                    context.MeetingRooms.AddRange(
                        new MeetingRoom("101", 10, 1, 10)
                    {
                        Id = 1
                    },
                        new MeetingRoom("102", 20, 1, 20)
                    {
                        Id = 2
                    },
                        new MeetingRoom("103", 10, 1, 0)
                    {
                        Id = 3
                    },
                        new MeetingRoom("201", 10, 1, 10)
                    {
                        Id = 4
                    },
                        new MeetingRoom("202", 20, 1, 20)
                    {
                        Id = 5
                    },
                        new MeetingRoom("203", 10, 1, 0)
                    {
                        Id = 6
                    }
                        );
                    await context.SaveChangesAsync();
                }
                ;
            }
        }
示例#28
0
        public async Task <IActionResult> GetSlots(int locationId, DateTime startTime, int slotSizeInMinutes)
        {
            using (var context = new ReservationContext()) {
                if (await context.Location.AnyAsync(x => x.Id == locationId) == false)
                {
                    return(BadRequest("Location id not existing."));
                }

                if (slotSizeInMinutes < 1)
                {
                    return(BadRequest("Slot size must be a positive number."));
                }

                var result    = new SlotResult();
                var dayOfWeek = startTime.DayOfWeek.ToString();
                var opening   = await context.LocationOpening.FirstOrDefaultAsync(x => x.LocationId == locationId &&
                                                                                  x.OpeningDays == dayOfWeek);

                DateTime endTime;

                if (opening == null)
                {
                    endTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 23, 59, 59);
                }
                else
                {
                    endTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, opening.ClosingTime.Hour, opening.ClosingTime.Minute, opening.ClosingTime.Second);
                }


                var current = startTime;
                do
                {
                    var currentEnd = current.AddMinutes(slotSizeInMinutes);

                    var count = await context.Reservation.CountAsync(x => x.LocationId == locationId &&
                                                                     x.StartTime >= current &&
                                                                     x.StartTime < currentEnd);

                    result.Items.Add(new SlotItem()
                    {
                        Start             = current,
                        End               = currentEnd,
                        RegistrationCount = count
                    });

                    current = current.AddMinutes(slotSizeInMinutes);
                } while (current < endTime);

                return(Ok(result));
            }
        }
示例#29
0
        public Reservation GetReservationById(Guid reservationId)
        {
            ReservationContext context = new ReservationContext();

            Reservation reservation = (from r in context.Reservations where r.Id == reservationId select r).FirstOrDefault();

            if (reservation == null)
            {
                throw new ArgumentException(string.Format("There's no reservation by ID {0}", reservationId));
            }

            return(reservation);
        }
        public IQueryable <T> FindMany(Expression <Func <T, bool> > predicate, IEnumerable <string> IncludeEntities = null)
        {
            using (context = new ReservationContext())
            {
                IQueryable <T> query = context.Set <T>().Where(predicate);
                if (IncludeEntities != null)
                {
                    query = IncludeEntities.Aggregate(query, (current, includePath) => current.Include(includePath));
                }

                return(query.ToList().AsQueryable());
            }
        }