예제 #1
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                if (_dbContext == null)
                {
                    var scope = _scopeFactory.CreateScope();
                    _dbContext = scope.ServiceProvider.GetRequiredService <HotelApiDbContext>();
                }
                var migratingRecords = await _dbContext.Rooms.Where(room => !room.IsMigrate).ToListAsync();

                foreach (var record in migratingRecords)
                {
                    // do work

                    record.IsMigrate = true;
                }

                if (_dbContext.ChangeTracker.HasChanges())
                {
                    await _dbContext.SaveChangesAsync();
                }

                await _dbContext.SaveChangesAsync();

                _logger.LogInformation("Worker Running");


                await Task.Delay(3000, stoppingToken);
            }
        }
        public async Task <Guid> CreateBookingAsync(
            Guid userId,
            Guid roomId,
            DateTimeOffset startAt,
            DateTimeOffset endAt)
        {
            var user = await _userManager.Users.SingleOrDefaultAsync(u => u.Id == userId);

            if (user == null)
            {
                throw new InvalidOperationException("You must be logged in.");
            }

            var room = await _context.Rooms
                       .SingleOrDefaultAsync(r => r.Id == roomId);

            if (room == null)
            {
                throw new ArgumentException("Invalid room ID.");
            }

            var minimumStay = _dateLogicService.GetMinimumStay();
            var total       = (int)((endAt - startAt).TotalHours / minimumStay.TotalHours)
                              * room.Rate;

            var id = Guid.NewGuid();

            var newBooking = _context.Bookings.Add(new BookingEntity
            {
                Id         = id,
                CreatedAt  = DateTimeOffset.UtcNow,
                ModifiedAt = DateTimeOffset.UtcNow,
                StartAt    = startAt.ToUniversalTime(),
                EndAt      = endAt.ToUniversalTime(),
                Total      = total,
                User       = user,
                Room       = room
            });

            var created = await _context.SaveChangesAsync();

            if (created < 1)
            {
                throw new InvalidOperationException("Could not create booking.");
            }

            return(id);
        }
예제 #3
0
        public async Task <UserInfo> Authenticate(TokenRequest req)
        {
            if (string.IsNullOrWhiteSpace(req.LoginUser) ||
                string.IsNullOrWhiteSpace(req.LoginPassword))
            {
                return(null);
            }

            var user = await _dbContext
                       .Users
                       .SingleOrDefaultAsync(user => user.LoginName == req.LoginUser &&
                                             user.Password == req.LoginPassword);

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

            var secretKey  = _configuration.GetValue <string>("JwtTokenKey");
            var singingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
            var tokenDesc  = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                NotBefore          = DateTime.Now,
                Expires            = DateTime.Now.AddMinutes(2),
                SigningCredentials = new SigningCredentials(singingKey, SecurityAlgorithms.HmacSha256Signature)
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var newToken     = tokenHandler.CreateToken(tokenDesc);

            var userInfo = _mapper.Map <UserInfo>(user);

            userInfo.ExpireTime          = tokenDesc.Expires ?? DateTime.Now.AddHours(1);
            userInfo.Token               = tokenHandler.WriteToken(newToken);
            userInfo.RefreshToken        = CreateRefreshToken();
            userInfo.RefreshTokenEndTime = DateTime.Now.AddHours(1.5);
            _dbContext.UserInfos.Add(userInfo);
            await _dbContext.SaveChangesAsync();

            return(userInfo);
        }
예제 #4
0
        public async Task <Guid> CreateBookingAsync(
            Guid userId,
            Guid roomId,
            DateTimeOffset startAt,
            DateTimeOffset endAt)
        {
            // Lookup the room reference to do it.
            var room = await _context.Rooms.SingleOrDefaultAsync(r => r.Id == roomId);

            // Error out if required.
            if (room == null)
            {
                throw new ArgumentException("Invalid room ID");
            }

            // Calculate how much
            var minimumStay = _dateLogicService.GetMinimumStay();
            var total       = (int)((endAt - startAt).TotalHours / minimumStay.TotalHours) * room.Rate;

            var bookingId = Guid.NewGuid();

            var newBooking = _context.Bookings.Add(new BookingEntity
            {
                Id         = bookingId,
                CreatedAt  = DateTimeOffset.UtcNow,
                ModifiedAt = DateTimeOffset.UtcNow,
                StartAt    = startAt.ToUniversalTime(),
                EndAt      = endAt.ToUniversalTime(),
                Total      = total,
                Room       = room
            });

            var created = await _context.SaveChangesAsync();

            if (created < 1)
            {
                throw new InvalidOperationException("Could not create the booking.");
            }

            return(bookingId);
        }
예제 #5
0
 public static async Task AddTestData(HotelApiDbContext context)
 {
     if (context.Rooms.Any())
     {
         //Already Has Data
         return;
     }
     context.Rooms.Add(new RoomEntity()
     {
         Id   = Guid.NewGuid(),
         Name = "Driscoll Suite",
         Rate = 1000
     });
     context.Rooms.Add(new RoomEntity()
     {
         Id   = Guid.Parse("f391e1b4-4e6e-4bd0-aa58-c05f0c580f17"),//Guid(61331889-41f6-4b96-8ff1-6dc090f709f1),
         Name = "ViewBer Mar",
         Rate = 2000
     });
     await context.SaveChangesAsync();
 }
예제 #6
0
        public static async Task AddTestData(HotelApiDbContext context,
                                             IDateLogicService dateLogicService)
        {
            if (context.Rooms.Any())//if it has data return
            {
                return;
            }


            var oxford = context.Rooms.Add(new RoomEntity
            {
                Id   = Guid.Parse("301df04d-8679-4b1b-ab92-0a586ae53d08"),
                Name = "Oxford Suite",
                Rate = 10119,
            }).Entity;

            context.Rooms.Add(new RoomEntity
            {
                Id   = Guid.Parse("ee2b83be-91db-4de5-8122-35a9e9195976"),
                Name = "Driscoll Suite",
                Rate = 23959
            });

            var today = DateTimeOffset.Now;
            var start = dateLogicService.AlignStartTime(today);
            var end   = start.Add(dateLogicService.GetMinimumStay());

            context.Bookings.Add(new BookingEntity
            {
                Id        = Guid.Parse("2eac8dea-2749-42b3-9d21-8eb2fc0fd6bd"),
                Room      = oxford,
                CreatedAt = DateTimeOffset.UtcNow,
                StartAt   = start,
                EndAt     = end,
                Total     = oxford.Rate,
            });

            await context.SaveChangesAsync();
        }