コード例 #1
0
        public async Task <IActionResult> Lab(int id)
        {
            if (HttpContext.Session.GetInt32("Id") == null && HttpContext.Session.GetInt32("AdminId") == null)
            {
                return(RedirectToAction("Login", "User"));
            }

            DateTime   startDate      = BangkokDateTime.now().Date;
            DinoLab    dinoLabDetails = null;
            HttpClient client         = new HttpClient();

            client.BaseAddress = new Uri(_config.GetValue <string>("DinoLabApi:ApiUri"));

            HttpResponseMessage response = await client.GetAsync(_config.GetValue <string>("DinoLabApi:GetLabPath") + $"/{id}");

            if (response.IsSuccessStatusCode)
            {
                dinoLabDetails = await JsonSerializer.DeserializeAsync <DinoLab>(await response.Content.ReadAsStreamAsync());
            }

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

            ViewBag.startDate = startDate;
            return(View(dinoLabDetails));
        }
コード例 #2
0
        public async Task <IActionResult> EditProfile(User user)
        {
            if (HttpContext.Session.GetInt32("Id") == null)
            {
                return(RedirectToAction("Login"));
            }

            Match mf = Regex.Match(user.FirstName ?? "", "^[A-Za-z]+$");
            Match ml = Regex.Match(user.LastName ?? "", "^[A-Za-z]+$");
            Match mp = Regex.Match(user.Phone ?? "", @"^\d{3}-?\d{3}-?\d{3,4}$");

            if (!mf.Success || !ml.Success || !mp.Success)
            {
                // _logger.LogInformation("{user}",user);
                return(View(user));
            }

            User loggedInUser = await _db.User.FindAsync(HttpContext.Session.GetInt32("Id"));

            if (loggedInUser == null)
            {
                throw new Exception("User not found");
            }
            loggedInUser.FirstName = user.FirstName;
            loggedInUser.LastName  = user.LastName;
            loggedInUser.Phone     = String.Join("", user.Phone.Split("-"));

            if (user.ImageFile != null)
            {
                string wwwRootPath = _hostEnvironment.WebRootPath;
                string fileName    = $"{BangkokDateTime.now().ToString("yyyyMMddhhmmssffff")}_{user.ImageFile.FileName}";
                string path        = $"{wwwRootPath}/images/users/{fileName}";
                // _logger.LogInformation(path);
                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    await user.ImageFile.CopyToAsync(fs);
                }
                loggedInUser.ImageUrl = $"~/images/users/{fileName}";
            }

            _db.User.Update(loggedInUser);
            await _db.SaveChangesAsync();

            return(RedirectToAction("Profile"));
        }
コード例 #3
0
        public async Task <IActionResult> EditItem(Lab lab)
        {
            if (HttpContext.Session.GetInt32("AdminId") == null)
            {
                return(RedirectToAction("Login", "Admin"));
            }

            Lab latestlab = await _db.Lab.FindAsync(lab.Id);

            if (latestlab == null)
            {
                return(BadRequest("The id not found."));
            }

            if (!ModelState.IsValid)
            {
                return(View(latestlab));
            }

            latestlab.Amount = lab.Amount;

            if (lab.ImageFile != null)
            {
                string wwwRootPath = _hostEnvironment.WebRootPath;
                string fileName    = $"{BangkokDateTime.now().ToString("yyyyMMddhhmmssffff")}_{lab.ImageFile.FileName}";
                string path        = $"{wwwRootPath}/images/labs/{fileName}";
                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    await lab.ImageFile.CopyToAsync(fs);
                }
                latestlab.ImageUrl = $"~/images/labs/{fileName}";
            }

            _db.Lab.Update(latestlab);
            await _db.SaveChangesAsync();

            return(RedirectToAction("EditItem", "LabAdmin", lab.Id));
        }
コード例 #4
0
        public async Task <IActionResult> Register(User user)
        {
            if (!ModelState.IsValid)
            {
                return(View(user));
            }
            // _logger.LogInformation("User {user}", user);
            user.Password = Md5.GetMd5Hash(user.Password);
            user.CreateAt = BangkokDateTime.now();
            user.Phone    = String.Join("", user.Phone.Split("-"));

            User registeredUser = await _db.User.Where(u => u.Email == user.Email).FirstOrDefaultAsync();

            if (registeredUser != null)
            {
                ViewBag.MessageError = "The Email already exists.";
                return(View(user));
            }
            _db.User.Add(user);
            await _db.SaveChangesAsync();

            return(RedirectToAction("Login"));
        }
コード例 #5
0
        public async Task <IActionResult> GetBooking(int?id)
        {
            Lab lab = await _db.Lab.FindAsync(id);

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

            DateTime startDate = BangkokDateTime.now().Date;
            DateTime endDate   = startDate.AddDays(14).Date;
            DateTime cacheDate;

            Func <DateTime, object, bool> checkDateCurrent = (cacheDate, key) =>
            {
                if (cacheDate < startDate)
                {
                    _cache.Remove(key);
                    return(true);
                }
                return(false);
            };

            do
            {
                (lab.BookSlotTable, cacheDate) = await _cache.GetOrCreateAsync <(int[, ], DateTime)>($"BookSlotTable_{lab.Id}", entry =>
                {
                    IEnumerable <BookSlot> bookSlots = _db.BookSlot.Where(bookSlot => bookSlot.LabId == lab.Id &&
                                                                          startDate <= bookSlot.Date && bookSlot.Date < endDate);

                    //Console.WriteLine(bookSlots.Count());

                    int[,] bookSlotTable = new int[9, 14];

                    for (int r = 0; r < 9; r++)
                    {
                        for (int c = 0; c < 14; c++)
                        {
                            bookSlotTable[r, c] = bookSlots.Where(bookSlot => bookSlot.Date == startDate.AddDays(c).Date)
                                                  .Count(bookSlot => bookSlot.TimeSlot == r + 1);
                        }
                    }

                    entry.SlidingExpiration = TimeSpan.FromMinutes(5);
                    return(Task.FromResult((bookSlotTable, startDate)));
                });
            } while (checkDateCurrent(cacheDate, $"BookSlotTable_{lab.Id}"));

            int[][] result = new int[14][];

            for (int r = 0; r < 14; r++)
            {
                int[] arr = new int[9];
                for (int c = 0; c < 9; c++)
                {
                    arr[c] = lab.Amount > lab.BookSlotTable[c, r] ? lab.Amount - lab.BookSlotTable[c, r] : 0;
                }
                result[r] = arr;
            }

            return(Json(new
            {
                Id = lab.Id,
                ItemName = lab.ItemName,
                ImageUrl = Url.Content(lab.ImageUrl),
                StartDate = startDate.ToString("dd-MMM-yyyy"),
                EndDate = endDate.ToString("dd-MMM-yyyy"),
                From = 8,
                To = 17,
                BookSlotTable = result,
                TimeStamp = BangkokDateTime.now().ToString("dd-MMM-yyyy HH:mm:ss")
            }));
        }
コード例 #6
0
        public async Task <IActionResult> ViewItem(int?id)
        {
            if (HttpContext.Session.GetInt32("AdminId") == null)
            {
                return(RedirectToAction("Login", "Admin"));
            }

            if (id == null)
            {
                return(RedirectToAction("Index"));
            }

            Lab lab = await _db.Lab.FindAsync(id);

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

            DateTime startDate = BangkokDateTime.now().Date;
            DateTime endDate   = startDate.AddDays(14).Date;
            DateTime cacheDate;

            Func <DateTime, object, bool> checkDateCurrent = (cacheDate, key) =>
            {
                if (cacheDate < startDate)
                {
                    _cache.Remove(key);
                    return(true);
                }
                return(false);
            };

            do
            {
                (lab.BookSlotTable, cacheDate) = await _cache.GetOrCreateAsync <(int[, ], DateTime)>($"BookSlotTable_{lab.Id}", entry =>
                {
                    IEnumerable <BookSlot> bookSlots = _db.BookSlot.Where(bookSlot => bookSlot.LabId == lab.Id &&
                                                                          startDate <= bookSlot.Date && bookSlot.Date < endDate);

                    //Console.WriteLine(bookSlots.Count());

                    int[,] bookSlotTable = new int[9, 14];

                    for (int r = 0; r < 9; r++)
                    {
                        for (int c = 0; c < 14; c++)
                        {
                            bookSlotTable[r, c] = bookSlots.Where(bookSlot => bookSlot.Date == startDate.AddDays(c).Date)
                                                  .Count(bookSlot => bookSlot.TimeSlot == r + 1);
                        }
                    }

                    entry.SlidingExpiration = TimeSpan.FromMinutes(5);
                    return(Task.FromResult((bookSlotTable, startDate)));
                });
            } while (checkDateCurrent(cacheDate, $"BookSlotTable_{id}"));

            ViewBag.startDate = startDate;
            return(View(lab));
        }
コード例 #7
0
        // API
        public IActionResult UserBookList([FromQuery(Name = "labId")] int?labId, [FromQuery(Name = "date")] long?date, [FromQuery(Name = "timeslot")] int?timeslot)
        {
            if (HttpContext.Session.GetInt32("AdminId") == null)
            {
                return(Unauthorized());
            }

            if (labId == null || date == null || timeslot == null)
            {
                return(BadRequest());
            }

            DateTime dateValue = BangkokDateTime.millisecondToDateTime((long)date).Date;

            Func <BookList, User, BookList> joinUser = (bookList, user) =>
            {
                bookList.FullName     = $"{user.FirstName} {user.LastName}";
                bookList.UserImageUrl = user.ImageUrl;
                return(bookList);
            };

            IEnumerable <BookList> bookLists = _db.BookSlot.Where(bs => bs.LabId == labId && bs.Date == dateValue && bs.TimeSlot == timeslot)
                                               .Join(
                _db.BookList,
                bs => bs.BookListId,
                bl => bl.Id,
                (bs, bl) => bl)
                                               .Join(_db.User,
                                                     bookList => bookList.UserId,
                                                     user => user.Id,
                                                     joinUser);
            DateTime dateNow = BangkokDateTime.now();

            foreach (BookList bookList in bookLists)
            {
                if (bookList.Status == BookList.StatusType.COMING)
                {
                    if (bookList.Date.AddHours(bookList.From) <= dateNow && dateNow < bookList.Date.AddHours(bookList.To))
                    {
                        bookList.Status = BookList.StatusType.USING;
                        _db.BookList.Update(bookList);
                    }
                    else if (dateNow >= bookList.Date.AddHours(bookList.To))
                    {
                        bookList.Status = BookList.StatusType.FINISHED;
                        _db.BookList.Update(bookList);
                    }
                }
                if (bookList.Status == BookList.StatusType.USING)
                {
                    if (dateNow >= bookList.Date.AddHours(bookList.To))
                    {
                        bookList.Status = BookList.StatusType.FINISHED;
                        _db.BookList.Update(bookList);
                    }
                }
            }

            return(Json(bookLists.Select(bl => new BookListLabAdmin
            {
                BooklistId = bl.Id,
                UserId = bl.UserId,
                UserImageUrl = Url.Content(bl.UserImageUrl != "" ? bl.UserImageUrl : "~/assets/images/brand.jpg"),
                FullName = bl.FullName,
                From = bl.From,
                To = bl.To,
                Status = (int)bl.Status,
            })));
        }
コード例 #8
0
        public async Task <IActionResult> Booklist()
        {
            if (HttpContext.Session.GetInt32("Id") == null)
            {
                return(RedirectToAction("Login"));
            }
            DateTime dateNow = BangkokDateTime.now();
            int      userId  = (int)HttpContext.Session.GetInt32("Id");

            Func <BookList, Lab, BookList> joinItemName = (bookList, lab) =>
            {
                bookList.ItemName = lab.ItemName;
                return(bookList);
            };

            IEnumerable <BookList> bookLists = _db.BookList.Where(bookList => bookList.UserId == userId)
                                               .Join(_db.Lab,
                                                     bookList => bookList.LabId,
                                                     lab => lab.Id,
                                                     joinItemName);

            foreach (BookList bookList in bookLists)
            {
                if (bookList.Status == BookList.StatusType.COMING)
                {
                    if (bookList.Date.AddHours(bookList.From) <= dateNow && dateNow < bookList.Date.AddHours(bookList.To))
                    {
                        bookList.Status = BookList.StatusType.USING;
                        _db.BookList.Update(bookList);
                    }
                    else if (dateNow >= bookList.Date.AddHours(bookList.To))
                    {
                        bookList.Status = BookList.StatusType.FINISHED;
                        _db.BookList.Update(bookList);
                    }
                }
                if (bookList.Status == BookList.StatusType.USING)
                {
                    if (dateNow >= bookList.Date.AddHours(bookList.To))
                    {
                        bookList.Status = BookList.StatusType.FINISHED;
                        _db.BookList.Update(bookList);
                    }
                }
            }
            await _db.SaveChangesAsync();

            List <BookList> bl = _cache.Set <List <BookList> >($"UserBooklist_{userId}", bookLists.Where(bl => bl.Status <= BookList.StatusType.COMING)
                                                               .OrderBy(bl => bl.Date)
                                                               .ThenBy(bl => bl.From)
                                                               .ThenBy(bl => bl.To)
                                                               .ThenBy(bl => bl.LabId)
                                                               .Concat(
                                                                   bookLists.Where(bl => bl.Status > BookList.StatusType.COMING)
                                                                   .OrderByDescending(bl => bl.Date)
                                                                   .ThenBy(bl => bl.From)
                                                                   .ThenBy(bl => bl.To)
                                                                   .ThenBy(bl => bl.LabId))
                                                               .ToList(), new MemoryCacheEntryOptions()
            {
                SlidingExpiration = TimeSpan.FromMinutes(1)
            });

            return(View(bl.GetRange(0, Math.Min(bl.Count, 10))));
        }
コード例 #9
0
        public async Task <IActionResult> Booking(int?id)
        {
            if (HttpContext.Session.GetInt32("Id") == null)
            {
                return(RedirectToAction("Login", "User"));
            }

            if (id == null)
            {
                return(RedirectToAction("Index"));
            }

            Lab lab = await _db.Lab.FindAsync(id);

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

            int userId = (int)HttpContext.Session.GetInt32("Id");

            DateTime startDate = BangkokDateTime.now().Date;
            DateTime endDate   = startDate.AddDays(14).Date;
            DateTime cacheDate;

            Func <DateTime, object, bool> checkDateCurrent = (cacheDate, key) =>
            {
                if (cacheDate < startDate)
                {
                    _cache.Remove(key);
                    return(true);
                }
                return(false);
            };

            do
            {
                (lab.BookSlotTable, cacheDate) = await _cache.GetOrCreateAsync <(int[, ], DateTime)>($"BookSlotTable_{lab.Id}", entry =>
                {
                    IEnumerable <BookSlot> bookSlots = _db.BookSlot.Where(bookSlot => bookSlot.LabId == lab.Id &&
                                                                          startDate <= bookSlot.Date && bookSlot.Date < endDate);

                    //Console.WriteLine(bookSlots.Count());

                    int[,] bookSlotTable = new int[9, 14];

                    for (int r = 0; r < 9; r++)
                    {
                        for (int c = 0; c < 14; c++)
                        {
                            bookSlotTable[r, c] = bookSlots.Where(bookSlot => bookSlot.Date == startDate.AddDays(c).Date)
                                                  .Count(bookSlot => bookSlot.TimeSlot == r + 1);
                        }
                    }

                    entry.SlidingExpiration = TimeSpan.FromMinutes(5);
                    return(Task.FromResult((bookSlotTable, startDate)));
                });
            } while (checkDateCurrent(cacheDate, $"BookSlotTable_{lab.Id}"));

            int[,] userBooked;
            do
            {
                (userBooked, cacheDate) = await _cache.GetOrCreateAsync <(int[, ], DateTime)>($"UserBooked_{lab.Id}_{userId}", entry =>
                {
                    IEnumerable <BookList> bookLists = _db.BookList.Where(bl => bl.UserId == userId &&
                                                                          bl.LabId == lab.Id &&
                                                                          startDate <= bl.Date && bl.Date < endDate &&
                                                                          bl.Status != BookList.StatusType.CANCEL && bl.Status != BookList.StatusType.EJECT);

                    int[,] booked = new int[9, 14];
                    foreach (BookList bl in bookLists)
                    {
                        for (int ts = bl.From; ts < bl.To; ts++)
                        {
                            booked[ts - 8, (bl.Date.Date - startDate.Date).Days] = 1;
                        }
                    }

                    entry.SlidingExpiration = TimeSpan.FromMinutes(1);
                    return(Task.FromResult((booked, startDate)));
                });
            } while (checkDateCurrent(cacheDate, $"UserBooked_{lab.Id}_{userId}"));

            User user = await _db.User.FindAsync(userId);

            ViewBag.userBlacklist = user.BlackList;
            ViewBag.userBooked    = userBooked;
            ViewBag.startDate     = startDate;
            return(View(lab));
        }
コード例 #10
0
        public IActionResult Booking(int id, [FromBody] IEnumerable <BookRange> bookRanges)
        {
            if (HttpContext.Session.GetInt32("Id") == null)
            {
                // "Your Session has Expired"
                return(Unauthorized());
            }

            if (bookRanges == null)
            {
                return(BadRequest());
            }

            int userId = (int)HttpContext.Session.GetInt32("Id");
            Lab lab    = _db.Lab.Find(id);

            if (lab == null)
            {
                return(BadRequest());
            }

            DateTime startDate = BangkokDateTime.now().Date;

            int[,] BookSlotTable = new int[14, 9];
            lock (_lock)
            {
                IEnumerable <BookList> bookLists = _db.BookList.Where(bl => bl.UserId == userId &&
                                                                      bl.LabId == id &&
                                                                      startDate.Date <= bl.Date && bl.Date < startDate.AddDays(14).Date&&
                                                                      bl.Status != BookList.StatusType.CANCEL && bl.Status != BookList.StatusType.EJECT);

                int[,] userBooked = new int[14, 9];
                foreach (BookList bl in bookLists)
                {
                    for (int ts = bl.From; ts < bl.To; ts++)
                    {
                        userBooked[(bl.Date.Date - startDate.Date).Days, ts - 8] = 1;
                    }
                }

                foreach (BookRange bookRange in bookRanges)
                {
                    if (bookRange.Date == 0 || bookRange.From == 0 || bookRange.To == 0)
                    {
                        // Please complete all field.
                        return(BadRequest());
                    }

                    DateTime dateValue = BangkokDateTime.millisecondToDateTime(bookRange.Date);
                    int      fromValue = bookRange.From;
                    int      toValue   = bookRange.To;

                    if (dateValue < startDate || dateValue >= startDate.AddDays(14))
                    {
                        // The date is out of the boundary that you can book.
                        return(BadRequest());
                    }

                    if (dateValue.DayOfWeek == DayOfWeek.Saturday || dateValue.DayOfWeek == DayOfWeek.Sunday)
                    {
                        // You cannot book an item on Weekend.
                        return(BadRequest());
                    }

                    if (fromValue >= toValue)
                    {
                        // You entered the wrong period.
                        return(BadRequest());
                    }

                    if (dateValue == startDate && BangkokDateTime.now().Hour > fromValue)
                    {
                        // The time is out of the boundary that you can book.
                        return(BadRequest());
                    }

                    for (int slot = fromValue; slot < toValue; slot++)
                    {
                        if (BookSlotTable[(dateValue - startDate).Days, slot - 8] == 1)
                        {
                            // You cannot enter the period that overlaps.
                            return(BadRequest());
                        }
                        if (userBooked[(dateValue - startDate).Days, slot - 8] == 1)
                        {
                            // You have already booked this period.
                            return(BadRequest());
                        }

                        if (_db.BookSlot.Where(bs => bs.LabId == lab.Id && bs.Date == dateValue).Count(bs => bs.TimeSlot == slot - 7) >= lab.Amount)
                        {
                            // You cannot enter the period that items full.
                            return(BadRequest());
                        }
                        BookSlotTable[(dateValue - startDate).Days, slot - 8] = 1;
                    }
                }

                for (int date = 0; date < 14; date++)
                {
                    int start = 0;
                    int end   = 0;
                    for (int timeslot = 0; timeslot < 9; timeslot++)
                    {
                        if (BookSlotTable[date, timeslot] == 1 && start == 0)
                        {
                            start = timeslot + 8;
                        }
                        if (BookSlotTable[date, timeslot] == 1 && start > 0)
                        {
                            end = timeslot + 9;
                        }
                        if (BookSlotTable[date, timeslot] == 0 && start > 0)
                        {
                            BookList bl = new BookList()
                            {
                                UserId = userId,
                                LabId  = lab.Id,
                                Date   = startDate.AddDays(date),
                                From   = start,
                                To     = end,
                                Status = BookList.StatusType.COMING
                            };
                            _db.BookList.Add(bl);
                            _db.SaveChanges();
                            for (int slot = start; slot < end; slot++)
                            {
                                _db.BookSlot.Add(new BookSlot()
                                {
                                    BookListId = bl.Id,
                                    LabId      = lab.Id,
                                    Date       = startDate.AddDays(date),
                                    TimeSlot   = slot - 7
                                });
                            }
                            _db.SaveChanges();
                            start = end = 0;
                        }
                    }
                    if (start > 0)
                    {
                        BookList bl = new BookList()
                        {
                            UserId = userId,
                            LabId  = lab.Id,
                            Date   = startDate.AddDays(date),
                            From   = start,
                            To     = end,
                            Status = BookList.StatusType.COMING
                        };
                        _db.BookList.Add(bl);
                        _db.SaveChanges();
                        for (int slot = start; slot < end; slot++)
                        {
                            _db.BookSlot.Add(new BookSlot()
                            {
                                BookListId = bl.Id,
                                LabId      = lab.Id,
                                Date       = startDate.AddDays(date),
                                TimeSlot   = slot - 7
                            });
                        }
                        _db.SaveChanges();
                    }
                }
            }
            _cache.Remove($"BookSlotTable_{lab.Id}");
            _cache.Remove($"UserBooked_{lab.Id}_{userId}");
            return(Ok("Ok"));
        }