Пример #1
0
        public IActionResult SubmitToolResult(PieceOfTest pot, WritingTestPaper.WritingPartTwoDTO wp2)
        {
            // Định nghĩa đích đến
            var dest = RedirectToAction(nameof(TestPaperController.ReviewHandler), NameUtils.ControllerName <TestPaperController>(), new { id = pot.Id });

            // Nếu không xác định được bài thi
            if (pot == null || pot.Id <= 0)
            {
                this.NotifyError("Cannot determine the test");
                return(dest);
            }

            // Nếu nội dung đánh giá rỗng
            if (string.IsNullOrEmpty(pot.InstructorComments))
            {
                this.NotifyError("Please leave your rating for this test.");
                return(dest);
            }

            // Nếu chưa cung cấp điểm cho bài nói của sinh viên
            if (pot.Scores < 0)
            {
                this.NotifyError("Please give the student a score.");
                return(dest);
            }

            // Nếu điểm quá lớn, thông báo
            if (pot.Scores > Config.SCORES_FULL_SPEAKING)
            {
                this.NotifyError("Cannot cheat student scores.");
                return(dest);
            }

            // Nếu tất cả đã hợp lệ, tiến hành lấy bản ghi
            var potRaw = _PieceOfTestManager.Get(pot.Id);

            // Cập nhật dữ liệu mới
            potRaw.InstructorComments = pot.InstructorComments;

            // Nếu là bài nói, Cập nhật điểm cho HV
            if (potRaw.TypeCode == TestCategory.SPEAKING)
            {
                potRaw.Scores = pot.Scores;
            }

            // Nếu là bài viết, cập nhập
            if (potRaw.TypeCode == TestCategory.WRITING)
            {
                SubmitToolResultForWriting(potRaw, wp2);
            }

            // Cập nhật vào CSDL
            _PieceOfTestManager.Update(potRaw);

            // Gửi thông báo thành công
            this.NotifySuccess("Update your evaluate success!");

            // Về điểm đích đã khai báo
            return(dest);
        }
Пример #2
0
        public IActionResult Index(string RequestPath)
        {
            if (User.Identity.IsAuthenticated)
            {
                TempData["ShowQuickTest"] = true;

                this.NotifySuccess("Welcome back");

                if (User.IsInRole(UserType.ROLE_INSTRUCTOR_USER))
                { // Nếu là giáo viên hướng dẫn thì chuyển về trang danh sách bài chấm của Học Viên
                    return(RedirectToAction(nameof(InstructorController.StudentTest), NameUtils.ControllerName <InstructorController>()));
                }

                if (string.IsNullOrEmpty(RequestPath))
                {
                    return(RedirectToAction(nameof(HomeController.Index), NameUtils.ControllerName <HomeController>()));
                }
                else
                {
                    return(Redirect(RequestPath));
                }
            }
            return(View(new UserLogin {
                RequestPath = RequestPath
            }));
        }
Пример #3
0
        public IActionResult Index(
            int grammarPage         = 1,
            string grammarSearchKey = "",
            string lookup           = "")
        {
            #region For grammar
            int topicStart = (grammarPage - 1) * Math.Min(10, Config.PAGE_PAGINATION_LIMIT);

            var grammars = _TestCategoryManager.GetByPagination(TestCategory.READING, 1, topicStart, Math.Min(10, Config.PAGE_PAGINATION_LIMIT), grammarSearchKey);
            ViewBag.Grammars         = grammars;
            ViewBag.GrammarSearchKey = grammarSearchKey;

            // Tạo đối tượng phân trang cho Grammars
            ViewBag.GrammarPagination = new Pagination(nameof(Index), NameUtils.ControllerName <DictionaryController>())
            {
                PageKey     = nameof(grammarPage),
                PageCurrent = grammarPage,
                NumberPage  = PaginationUtils.TotalPageCount(
                    _TestCategoryManager.CountFor(TestCategory.READING, 1, grammarSearchKey),
                    Math.Min(10, Config.PAGE_PAGINATION_LIMIT)),
                Offset = Math.Min(10, Config.PAGE_PAGINATION_LIMIT)
            };
            #endregion

            #region For search vocabulary
            ViewBag.Vocabularies = _VocabularyManager.LookUp(lookup ?? string.Empty);
            ViewBag.LookUp       = lookup;
            #endregion
            return(View());
        }
        private IEnumerable <object> QuestionRender(string actionName, string typeCode, int partId, int questionPage = 1, int category = 0, string questionSearchKey = "")
        {
            int questionStart = (questionPage - 1) * Config.PAGE_PAGINATION_LIMIT;

            int total;

            if (partId == 1)
            {
                total = _ReadingPartOneManager.GetAll(category).Count();
            }
            else
            {
                total = _ReadingPartTwoManager.GetAll(typeCode, partId, category).Count();
            }

            // Tạo đối tượng phân trang cho Câu hỏi
            ViewBag.QuestionPagination = new Pagination(actionName, NameUtils.ControllerName <ReadingManagerController>())
            {
                PageKey     = nameof(questionPage),
                PageCurrent = questionPage,
                TypeKey     = nameof(category),
                Type        = "0",
                NumberPage  = PaginationUtils.TotalPageCount(total, Config.PAGE_PAGINATION_LIMIT),
                Offset      = Config.PAGE_PAGINATION_LIMIT
            };

            if (category > 0)
            {
                var testCategory = _TestCategoryManager.Get(category);
                if (testCategory == null)
                {
                    return(new List <object>());
                }
                else
                {
                    ViewBag.QuestionType = testCategory.Name ?? "";
                    if (partId == 1)
                    {
                        return(_ReadingPartOneManager.GetByPagination(category, questionStart, Config.PAGE_PAGINATION_LIMIT));
                    }
                    else
                    {
                        return(_ReadingPartTwoManager.GetByPagination(category, typeCode, partId, questionStart, Config.PAGE_PAGINATION_LIMIT));
                    }
                }
            }
            else
            {
                ViewBag.QuestionType = "ALL";
                if (partId == 1)
                {
                    return(_ReadingPartOneManager.GetByPagination(questionStart, Config.PAGE_PAGINATION_LIMIT));
                }
                else
                {
                    return(_ReadingPartTwoManager.GetByPagination(typeCode, partId, questionStart, Config.PAGE_PAGINATION_LIMIT));
                }
            }
        }
Пример #5
0
        public IActionResult StudentTest(int studentId = -1, string type = "ALL", int page = 1, string searchKey = "", bool isUnRead = false)
        {
            // Truyền gửi tên bảng
            ViewBag.TableName = type.ToUpper();
            ViewBag.SearchKey = searchKey;
            // Lấy các đếm chuẩn
            ViewBag.UserTestCountOfAll       = _PieceOfTestManager.StudentTestCountOfType(User.Id(), "ALL", string.Empty, studentId, isUnRead);
            ViewBag.UserTestCountOfListening = _PieceOfTestManager.StudentTestCountOfType(User.Id(), TestCategory.LISTENING, string.Empty, studentId, isUnRead);
            ViewBag.UserTestCountOfReading   = _PieceOfTestManager.StudentTestCountOfType(User.Id(), TestCategory.READING, string.Empty, studentId, isUnRead);
            ViewBag.UserTestCountOfSpeaking  = _PieceOfTestManager.StudentTestCountOfType(User.Id(), TestCategory.SPEAKING, string.Empty, studentId, isUnRead);
            ViewBag.UserTestCountOfWriting   = _PieceOfTestManager.StudentTestCountOfType(User.Id(), TestCategory.WRITING, string.Empty, studentId, isUnRead);
            ViewBag.UserTestCountOfCrash     = _PieceOfTestManager.StudentTestCountOfType(User.Id(), "CRASH", string.Empty, studentId, isUnRead);

            // Tiến hành cấu hình phân trang

            int start = (page - 1) * Config.PAGE_PAGINATION_LIMIT;
            // Lấy danh sách
            List <PieceOfTest> PieceOfTests = _PieceOfTestManager.GetByPaginationSimpleForInstructor(User.Id(), type, start, Config.PAGE_PAGINATION_LIMIT, searchKey, studentId, isUnRead).ToList();

            // Lấy một số thông tin cần thiết của User
            for (int i = 0; i < PieceOfTests.Count(); i++)
            {
                var tempUser = _UserManager.Get(PieceOfTests[i].UserId);
                PieceOfTests[i].User = new User
                {
                    Avatar    = tempUser.Avatar,
                    FirstName = tempUser.FirstName,
                    LastName  = tempUser.LastName
                };
            }

            // Tạo đối tượng phân trang
            ViewBag.Pagination = new Pagination(nameof(Index), NameUtils.ControllerName <TestController>())
            {
                PageCurrent = page,
                Type        = type,
                NumberPage  = PaginationUtils.TotalPageCount(
                    _PieceOfTestManager.StudentTestCountOfType(
                        User.Id(),
                        type.ToUpper().Trim(),
                        searchKey,
                        studentId,
                        isUnRead
                        ).ToInt(),
                    Config.PAGE_PAGINATION_LIMIT
                    ),
                Offset = Config.PAGE_PAGINATION_LIMIT
            };

            // Lấy học viên nếu được chọn cụ thể
            if (studentId > 0)
            {
                ViewBag.Student = _UserManager.Get(studentId);
            }


            return(View(PieceOfTests));
        }
        public IActionResult ListeningReview(int id)
        {
            if (id <= 0)
            {
                return(NotFoundTest());
            }

            ViewBag.Title = "LISTENING TESTING";

            ViewBag.IsReviewMode = true;

            // Sau khi hoàn tất lọc các lỗi, tiến hành lấy
            PieceOfTest piece = _PieceOfTestManager.Get(id);

            if (piece == null)
            {
                return(NotFoundTest());
            }

            if (piece.InstructorId != User.Id() && piece.UserId != User.Id())
            {
                this.NotifyError("You are not authorized to view or manipulate this test");
                return(RedirectToAction(nameof(HomeController.Index), NameUtils.ControllerName <HomeController>()));
            }

            // Lấy chủ sở hữu của bài kiểm tra
            User owner = _UserManager.Get(piece.UserId);

            ViewData["Owner"] = new User
            {
                Avatar    = owner.Avatar,
                FirstName = owner.FirstName,
                LastName  = owner.LastName
            };

            // Thời gian làm bài
            ViewBag.Timer = piece.TimeToFinished;

            // Điểm của bài thi
            ViewBag.Scores = piece.Scores;

            // Bài thi của học viên
            ListeningTestPaper userPaper = JsonConvert.DeserializeObject <ListeningTestPaper>(piece.ResultOfUserJson ?? "");
            // Bài thi mẫu (Được tạo khi thi, của học viên)
            ListeningTestPaper resultPaper = JsonConvert.DeserializeObject <ListeningTestPaper>(piece.ResultOfTestJson ?? "");

            bool isReviewOfFailTest = piece.ResultOfUserJson == null || piece.ResultOfUserJson.Length <= 0 || piece.UpdatedTime == null;

            ViewBag.IsReviewOfFailTest = isReviewOfFailTest;
            ViewBag.ResultPaper        = resultPaper;

            if (isReviewOfFailTest)
            {
                userPaper = resultPaper;
            }

            return(View(nameof(Listening), userPaper));
        }
        public IActionResult General(int id)
        {
            ViewBag.Title = "GENERAL TESTING";
            if (id <= 0)
            {
                return(NotFoundTest());
            }

            // Sau khi hoàn tất lọc các lỗi, tiến hành xử lý, đếm số câu đúng
            PieceOfTest piece = _PieceOfTestManager.Get(id);

            // Nếu tìm không thấy bài Test
            if (piece == null)
            {
                return(NotFoundTest());
            }

            if (piece.InstructorId != User.Id() && piece.UserId != User.Id())
            {
                this.NotifyError("You are not authorized to view or manipulate this test");
                return(RedirectToAction(nameof(HomeController.Index), NameUtils.ControllerName <HomeController>()));
            }

            // Lấy chủ sở hữu của bài kiểm tra
            User owner = _UserManager.Get(piece.UserId);

            ViewData["Owner"] = new User
            {
                Avatar    = owner.Avatar,
                FirstName = owner.FirstName,
                LastName  = owner.LastName
            };

            // Nếu bài thi đã hoàn thành, thì chuyển sang màn hình review
            if (piece.ResultOfUserJson != null && piece.ResultOfUserJson.Length > 0 && piece.UpdatedTime != null)
            {
                return(RedirectToAction(nameof(GeneralReview), new { id }));
            }

            // Tránh timer bị reset
            if (piece.CreatedTime != null)
            {
                ViewBag.Timer = DateTime.UtcNow.Subtract((DateTime)piece.CreatedTime).TotalSeconds;
            }

            // Giải mã thành giữ liệu bài thi
            GeneralTestPaper paper = JsonConvert.DeserializeObject <GeneralTestPaper>(piece.ResultOfTestJson);

            // Gắn mã dữ liệu
            paper.PieceOfTestId = piece.Id;

            // Xóa đáp án của bài thi
            paper.ClearTrueAnswers();

            this.NotifySuccess("Try your best, Good Luck!");

            return(View(paper));
        }
Пример #8
0
        public IActionResult Speaking(int id)
        {
            ViewBag.Title = "SPEAKING TESTING";
            if (id <= 0)
            {
                return(NotFoundTest());
            }


            PieceOfTest piece = _PieceOfTestManager.Get(id);

            // Nếu tìm không thấy bài Test
            if (piece == null)
            {
                return(NotFoundTest());
            }

            if (piece.InstructorId != User.Id() && piece.UserId != User.Id())
            {
                this.NotifyError("You are not authorized to view or manipulate this test");
                return(RedirectToAction(nameof(HomeController.Index), NameUtils.ControllerName <HomeController>()));
            }

            // Lấy chủ sở hữu của bài kiểm tra
            User owner = _UserManager.Get(piece.UserId);

            ViewData["Owner"] = new User
            {
                Avatar    = owner.Avatar,
                FirstName = owner.FirstName,
                LastName  = owner.LastName
            };

            // Nếu bài thi đã hoàn thành, thì chuyển sang màn hình review
            if (piece.ResultOfUserJson != null && piece.ResultOfUserJson.Length > 0 && piece.UpdatedTime != null)
            {
                return(RedirectToAction(nameof(SpeakingReview), new { id }));
            }

            // Tránh timer bị reset
            if (piece.CreatedTime != null)
            {
                ViewBag.Timer = DateTime.UtcNow.Subtract((DateTime)piece.CreatedTime).TotalSeconds;
            }

            SpeakingTestPaper paper = JsonConvert.DeserializeObject <SpeakingTestPaper>(piece.ResultOfTestJson);


            paper.PiceOfTestId = piece.Id;

            this.NotifySuccess("Try your best, Good Luck!");

            return(View(paper));
        }
Пример #9
0
        public IActionResult Index(
            long topic                 = -1,
            int topicPage              = 1,
            int vocabularyPage         = 1,
            string topicSearchKey      = "",
            string vocabularySearchKey = "")
        {
            #region For topic
            int topicStart = (topicPage - 1) * Config.PAGE_PAGINATION_LIMIT;

            var topics = _TopicManager.GetByPagination(topicStart, Config.PAGE_PAGINATION_LIMIT);
            ViewBag.Topics = topics;

            // Tạo đối tượng phân trang cho Category
            ViewBag.TopicPagination = new Pagination(nameof(Index), NameUtils.ControllerName <DictionaryManagerController>())
            {
                PageKey     = nameof(topicPage),
                PageCurrent = topicPage,
                NumberPage  = PaginationUtils.TotalPageCount(
                    _TopicManager.Count().ToInt(),
                    Config.PAGE_PAGINATION_LIMIT),
                Offset = Config.PAGE_PAGINATION_LIMIT
            };
            #endregion

            #region For vocabulary
            int vocabularyStart = (vocabularyPage - 1) * Config.PAGE_PAGINATION_LIMIT;

            int total = _VocabularyManager.CountFor(topic).ToInt();

            // Tạo đối tượng phân trang cho Câu hỏi
            ViewBag.VocabularyPagination = new Pagination(nameof(Index), NameUtils.ControllerName <ReadingManagerController>())
            {
                PageKey     = nameof(vocabularyPage),
                PageCurrent = vocabularyPage,
                TypeKey     = nameof(topic),
                Type        = "0",
                NumberPage  = PaginationUtils.TotalPageCount(total, Config.PAGE_PAGINATION_LIMIT),
                Offset      = Config.PAGE_PAGINATION_LIMIT
            };

            ViewBag.TopicName = _TopicManager.Get(topic)?.Name ?? "";

            if (topic <= 0)
            {
                ViewBag.TopicName = "ALL";
            }

            ViewBag.Vocabularies = _VocabularyManager.GetByPagination(topic, vocabularyStart, Config.PAGE_PAGINATION_LIMIT);
            #endregion

            return(View());
        }
        public IActionResult SubmitToolResultForWriting(WritingTestPaper wtp, WritingPartTwoDTO wp2DTO)
        {
            // Định nghĩa đích đến
            var dest = RedirectToAction(nameof(TestPaperController.ReviewHandler), NameUtils.ControllerName <TestPaperController>(), new { id = wtp.PiceOfTestId });

            // Nếu không xác định được bài thi
            if (wtp == null || wtp.PiceOfTestId <= 0)
            {
                this.NotifyError("Cannot determine the test");
                return(dest);
            }

            // Nếu nội dung đánh giá rỗng
            if (wp2DTO == null || string.IsNullOrEmpty(wp2DTO.TeacherReviewParagraph))
            {
                this.NotifyError("You must correct paragraph for your student");
                return(dest);
            }

            // Điểm cho bài thi
            if (wp2DTO.Scores < 0 || wp2DTO.Scores > Config.SCORES_FULL_WRITING_PART_2)
            {
                this.NotifyError("Score invalid");
                return(dest);
            }

            // Nếu tất cả đã hợp lệ, tiến hành lấy bản ghi
            var pot = _PieceOfTestManager.Get(wtp.PiceOfTestId);

            // Lấy dữ liệu gốc
            var constWtp = JsonConvert.DeserializeObject <WritingTestPaper>(pot.ResultOfUserJson) as WritingTestPaper;

            // Cập nhật điểm số mới
            pot.Scores = constWtp.WritingPartOnes.Scores + wp2DTO.Scores;

            // Cập nhật điểm số
            constWtp.WritingPartTwos.Scores = wp2DTO.Scores;
            constWtp.WritingPartTwos.TeacherReviewParagraph = wp2DTO.TeacherReviewParagraph;

            // Lưu lại json
            pot.ResultOfUserJson = JsonConvert.SerializeObject(constWtp);

            // Cập nhật vào CSDL
            _PieceOfTestManager.Update(pot);

            // Gửi thông báo thành công
            this.NotifySuccess("Update your review to student success!");

            // Về điểm đích đã khai báo
            return(dest);
        }
Пример #11
0
        public IActionResult YourOwnInstructor(int page = 1, string searchKey = "")
        {
            int start = (page - 1) * Config.PAGE_PAGINATION_LIMIT;

            long total = _PieceOfTestManager.CountAllInstructorOfStudent(User.Id());
            IEnumerable <User> users = _UserManager.GetAllInstructorsOfStudent(User.Id(), start, Config.PAGE_PAGINATION_LIMIT);

            // Tạo đối tượng phân trang
            ViewBag.Pagination = new Pagination(nameof(Index), NameUtils.ControllerName <UserManagementController>())
            {
                PageCurrent = page,
                NumberPage  = PaginationUtils.TotalPageCount(total.ToInt(), Config.PAGE_PAGINATION_LIMIT),
                Offset      = Config.PAGE_PAGINATION_LIMIT
            };
            // Get data
            return(View(users));
        }
Пример #12
0
        public IActionResult Index(int page = 1, string searchKey = "")
        {
            // Lấy danh sách các cuộc thảo luận của người dùng hiện tại
            int start       = (page - 1) * Config.PAGE_PAGINATION_LIMIT;
            var discussions = _DiscussionManager.GetByPaginationFor(User.Id(), start, Config.PAGE_PAGINATION_LIMIT);

            // Tạo đối tượng phân trang
            ViewBag.Pagination = new Pagination(nameof(Index), NameUtils.ControllerName <DiscussController>())
            {
                PageCurrent = page,
                NumberPage  = PaginationUtils.TotalPageCount(
                    _DiscussionManager.CountAllFor(User.Id()).ToInt(),
                    Config.PAGE_PAGINATION_LIMIT),
                Offset = Config.PAGE_PAGINATION_LIMIT
            };

            return(View(discussions));
        }
Пример #13
0
        private IEnumerable <TestCategory> CategoryRender(string actionName, string typeCode, int partId, int categoryPage = 1, string categorySearchKey = "")
        {
            int categoryStart = (categoryPage - 1) * Config.PAGE_PAGINATION_LIMIT;

            var testCategories = _TestCategoryManager.GetByPagination(typeCode, partId, categoryStart, Config.PAGE_PAGINATION_LIMIT);

            // Tạo đối tượng phân trang cho Category
            ViewBag.CategoryPagination = new Pagination(actionName, NameUtils.ControllerName <SpeakingManagerController>())
            {
                PageKey     = nameof(categoryPage),
                PageCurrent = categoryPage,
                NumberPage  = PaginationUtils.TotalPageCount(
                    _TestCategoryManager.GetAll(typeCode, partId).Count(),
                    Config.PAGE_PAGINATION_LIMIT),
                Offset = Config.PAGE_PAGINATION_LIMIT
            };
            return(testCategories);
        }
        public IActionResult DownloadUserMedia(string username, string type, string filename)
        {
            try
            {
                var uploads = Path.Combine(host.GetContentPathRootForUploadUtils(), NameUtils.ControllerName <UploadsController>().ToLower(), username, type, filename);

                if (System.IO.File.Exists(uploads))
                {
                    return(File(System.IO.File.ReadAllBytes(uploads), "application/octet-stream"));
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (Exception)
            {
                return(NotFound());
            }
        }
Пример #15
0
        public IActionResult Index(
            int notePage = 1,
            int noteId   = -1)
        {
            // Lấy danh sách các ghi chú của User
            IEnumerable <UserNote> userNotes = _UserNoteManager.GetAll(User.Id());

            // Tạo đối tượng phân trang cho Grammars
            ViewBag.NotePagination = new Pagination(nameof(Index), NameUtils.ControllerName <DictionaryController>())
            {
                PageKey     = nameof(notePage),
                PageCurrent = notePage,
                NumberPage  = PaginationUtils.TotalPageCount(
                    _UserNoteManager.CountFor(User.Id()),
                    Math.Min(10, Config.PAGE_PAGINATION_LIMIT)),
                Offset = Math.Min(10, Config.PAGE_PAGINATION_LIMIT)
            };

            return(View(userNotes));
        }
Пример #16
0
        public IActionResult Result(int id, params float[] scoresPart)
        {
            if (id <= 0)
            {
                return(BadRequest());
            }

            var piece = _PieceOfTestManager.Get(id);

            if (piece == null)
            {
                return(NotFoundTest());
            }

            if (piece.InstructorId != User.Id() && piece.UserId != User.Id())
            {
                this.NotifyError("You are not authorized to view or manipulate this test");
                return(RedirectToAction(nameof(HomeController.Index), NameUtils.ControllerName <HomeController>()));
            }

            ViewBag.Title = $"{piece.TypeCode.ToUpper()} TESTING RESULT";
            if (piece.Scores >= 0)
            {
                ViewBag.Scores = piece.Scores;
            }
            else
            {
                ViewBag.Scores = 0;
            }

            ViewBag.MaxScores = ScoresUtils.GetMaxScores(piece.TypeCode);

            // Nếu đây là bài thi viết
            if (piece.TypeCode == TestCategory.WRITING)
            {
                // Cập nhật điểm mới của phần cho đúng
                ViewBag.Scores = scoresPart[0];

                // Cập nhật điểm gới hạn cho đúng
                ViewBag.MaxScores = Config.SCORES_FULL_WRITING_PART_1;

                // Gắn cờ xác minh
                ViewBag.IsWriting = true;

                // Đổi tin nhắn thông báo thành công
                ViewBag.Msg = "Congratulations, you finished the test, with <span class=\"font-weight-bold text-danger\">PART 1</span> score is";
            }

            if (piece.TypeCode == TestCategory.SPEAKING)
            {
                ViewBag.IsSpeaking = true;
                // Đổi tin nhắn thông báo thành công
                ViewBag.Msg = "<i class=\"\">Congratulations, you finished the test, your teacher will review your test and mark for you later.</i>";
            }

            if (piece.TypeCode == TestCategory.TEST_ALL)
            {
                //ViewBag.Title = "GENERAL TESTING RESULT";
                //ViewBag.IsGeneral = true;
                //// Đổi tin nhắn thông báo thành công
                //ViewBag.Msg = "<i class=\"\">Congratulations, you finished the test, your teacher will review your test and mark for you later.</i>";
                this.NotifySuccess("Here are the results of your test");
                return(RedirectToAction(nameof(GeneralReview), new { piece.Id }));
            }


            this.NotifySuccess("Your test is completed!");

            return(View(piece));
        }
Пример #17
0
        public IActionResult Delete(long id)
        {
            var      user               = _UserManager.Get(id);
            var      userRole           = user.UserTypeUser.OrderBy(it => it.UserType.Priority).Last();
            UserType maxCurrentUserType = UserType.GetMaxUserType((User.FindFirstValue(ClaimTypes.Role) ?? "").Split(","));

            if (user != null)
            {
                if (user.Username == User.FindFirstValue(ClaimTypes.NameIdentifier))
                {
                    return(Json(new { success = false, responseText = "You cannot remove yourself!" }));
                }
                else if (userRole != null && maxCurrentUserType != null && UserType.CompareRole(maxCurrentUserType.UserTypeName, userRole.UserType.UserTypeName) < 0)
                {
                    return(Json(new { success = false, responseText = "You do not have sufficient authority to delete this account!" }));
                }
                else
                {
                    _UserManager.Delete(user);
                    user.HashPassword = "";
                    var uploads = Path.Combine(host.GetContentPathRootForUploadUtils(), NameUtils.ControllerName <UploadsController>().ToLower(), user.Username.ToLower());
                    // Xóa thư mục tệp tin của người dùng này nếu có tồn tại
                    if (Directory.Exists(uploads))
                    {
                        Directory.Delete(uploads, true);
                    }
                    return(Json(new { success = true, user = JsonConvert.SerializeObject(user), responseText = "Deleted" }));
                }
            }
            else
            {
                return(Json(new { success = false, responseText = "Can not find this user!" }));
            }
        }
Пример #18
0
        public IActionResult Index(string type = "all", int page = 1, string searchKey = "")
        {
            int start = (page - 1) * Config.PAGE_PAGINATION_LIMIT;

            long allUserCount     = _UserManager.Count();
            long allLearnersCount = _UserManager.Count(UserType.ROLE_NORMAL_USER);
            long allManagersCount = _UserManager.Count(UserType.ROLE_MANAGER_USER) + _UserManager.Count(UserType.ROLE_MANAGER_LIBRARY) + _UserManager.Count(UserType.ROLE_ALL);
            long allBlockedCount  = _UserManager.Count(null);

            if (searchKey != null && searchKey.Length > 0)
            {
                type = "all"; // Nếu có tìm, thì sẽ là tìm tất cả
            }

            ViewBag.AllUserCount     = allUserCount;
            ViewBag.AllLearnersCount = allLearnersCount;
            ViewBag.AllManagersCount = allManagersCount;
            ViewBag.AllBlockedCount  = allBlockedCount;

            long total;
            IEnumerable <User> users = new List <User>();

            if (type.ToUpper() == "LEARNER".ToUpper())
            {
                total = allLearnersCount;
                users = _UserManager.GetByPagination(start, Config.PAGE_PAGINATION_LIMIT, UserType.ROLE_NORMAL_USER);

                ViewBag.TableName        = "LIST ALL LEARNERS";
                ViewBag.TableDescription = "List all learners using your system";
            }
            else if (type.ToUpper() == "MANAGER".ToUpper())
            {
                total = allManagersCount;
                users = users
                        .Concat(_UserManager.GetByPagination(start, Config.PAGE_PAGINATION_LIMIT, UserType.ROLE_ALL))
                        .Concat(_UserManager.GetByPagination(start, Config.PAGE_PAGINATION_LIMIT, UserType.ROLE_MANAGER_LIBRARY))
                        .Concat(_UserManager.GetByPagination(start, Config.PAGE_PAGINATION_LIMIT, UserType.ROLE_MANAGER_USER)).Distinct();

                ViewBag.TableName        = "LIST ALL MANAGER";
                ViewBag.TableDescription = "List all manager of your system";
            }
            else if (type.ToUpper() == "BLOCKED".ToUpper())
            {
                total = allBlockedCount;
                users = _UserManager.GetByPagination(start, Config.PAGE_PAGINATION_LIMIT, null);

                ViewBag.TableName        = "LIST ALL BLOCKED USERS";
                ViewBag.TableDescription = "List all blocked user using your system";
            }
            else
            {
                // ALL
                total = allUserCount;
                users = _UserManager.GetByPagination(searchKey, start, Config.PAGE_PAGINATION_LIMIT);

                if (searchKey != null && searchKey.Length > 0)
                {
                    ViewBag.TableName        = $"RESULT FOR \"{searchKey}\"";
                    ViewBag.TableDescription = $"Match with {users.Count()} results";
                }
                else
                {
                    ViewBag.TableName        = "LIST ALL USERS";
                    ViewBag.TableDescription = "List all user using your system";
                }
            }

            // Tạo đối tượng phân trang
            ViewBag.Pagination = new Pagination(nameof(Index), NameUtils.ControllerName <UserManagementController>())
            {
                PageCurrent = page,
                Type        = type,
                NumberPage  = PaginationUtils.TotalPageCount(total.ToInt(), Config.PAGE_PAGINATION_LIMIT),
                Offset      = Config.PAGE_PAGINATION_LIMIT
            };

            // Get data
            return(View(users));
        }
Пример #19
0
        // https://viblo.asia/p/su-dung-cookie-authentication-trong-aspnet-core-djeZ1VG8lWz
        public async Task <IActionResult> LogIn(UserLogin userLogin)
        {
            TempData["ShowQuickTest"] = true;
            if (ModelState.IsValid)
            {
                User user = _UserManager.Get(userLogin.Identity);
                if (user != null)
                {
                    var(Verified, NeedsUpgrade) = Utils.PasswordUtils.PasswordHasher.VerifyHashedPassword(user.HashPassword, userLogin.Password);
                    if (Verified)
                    {
                        // create claims
                        List <Claim> claims = new List <Claim>
                        {
                            new Claim(CustomClaimTypes.Id, user.Id.ToString() ?? "0"),
                            new Claim(ClaimTypes.NameIdentifier, user.Username ?? ""),
                            new Claim(ClaimTypes.Email, user.Email ?? ""),
                            new Claim(ClaimTypes.DateOfBirth, user.BirthDay.ToString() ?? ""),
                            new Claim(ClaimTypes.Name, $"{user.LastName} {user.FirstName}" ?? ""),
                            new Claim(ClaimTypes.GivenName, user.FirstName ?? ""),
                            new Claim(ClaimTypes.Surname, user.LastName ?? ""),
                            new Claim(ClaimTypes.Gender, user.Gender.ToString() ?? ""),
                            new Claim(CustomClaimTypes.Avatar, user.Avatar ?? ""),
                            new Claim(ClaimTypes.Role, string.Join(",", _UserTypeManager.GetAll(user.Id).Select(role => role.UserTypeName)) ?? "")
                        };

                        // create identity
                        ClaimsIdentity identity = new ClaimsIdentity(claims, "user-info-cookie");

                        // create principal
                        ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                        // sign-in
                        await HttpContext.SignInAsync(
                            scheme : CookieAuthenticationDefaults.AuthenticationScheme,
                            principal : principal,
                            properties : new AuthenticationProperties
                        {
                            IsPersistent = userLogin.IsRemember,         // for 'remember me' feature
                            ExpiresUtc   = DateTime.UtcNow.AddMinutes(Config.MAX_COOKIE_LIFE_MINUTES)
                        });

                        this.NotifySuccess("Login success");

                        if (User.IsInRole(UserType.ROLE_INSTRUCTOR_USER))
                        { // Nếu là giáo viên hướng dẫn thì chuyển về trang danh sách bài chấm của Học Viên
                            return(RedirectToAction(nameof(InstructorController.StudentTest), NameUtils.ControllerName <InstructorController>()));
                        }

                        if (string.IsNullOrEmpty(userLogin.RequestPath))
                        {
                            return(RedirectToAction(nameof(HomeController.Index), NameUtils.ControllerName <HomeController>()));
                        }
                        else
                        {
                            return(Redirect(userLogin.RequestPath));
                        }
                    }
                    else
                    {
                        this.NotifyError("Account or password is incorrect");
                        ModelState.AddModelError(string.Empty, "Account or password is incorrect");
                    }
                }
                else
                {
                    this.NotifyError("Account or password is incorrect");
                    ModelState.AddModelError(string.Empty, "Account or password is incorrect");
                }
            }
            else
            {
                this.NotifyError("Please check your input again!");
            }

            return(View(nameof(Index), userLogin));
        }
        public IActionResult Listening(ListeningTestPaper paper)
        {
            if (paper == null)
            {
                this.NotifyError("Not found yor test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            if (paper.PiceOfTestId <= 0)
            {
                this.NotifyError("Not found yor test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            // Sau khi hoàn tất lọc các lỗi, tiến hành xử lý, đếm số câu đúng
            PieceOfTest piece = _PieceOfTestManager.Get(paper.PiceOfTestId);

            if (piece == null)
            {
                this.NotifyError("Not found yor test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            if (piece.InstructorId != User.Id() && piece.UserId != User.Id())
            {
                this.NotifyError("You are not authorized to view or manipulate this test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            int total = paper.TotalQuestions(); // Tổng số câu hỏi

            if (total <= 0)
            {
                return(Json(new { status = false, message = "The test does not have any questions", location = string.Empty }));
            }

            // Tính toán số điểm
            float scores = paper.ScoreCalculate(piece.ResultOfTestJson);

            // Thời gian kết thúc bài thi
            float timeToFinished = DateTime.UtcNow.Subtract((DateTime)piece.CreatedTime).TotalSeconds.ToFloat();

            // Cập nhật dữ liệu
            piece.ResultOfUserJson = JsonConvert.SerializeObject(paper);
            piece.Scores           = scores;
            piece.TimeToFinished   = timeToFinished;
            _PieceOfTestManager.Update(piece);

            // Chuyển đến trang kết quả
            return(Json(new { status = true, message = "Successful submission of exams", location = $"{Url.Action(nameof(Result), NameUtils.ControllerName<TestPaperController>())}/{piece.Id}" }));
        }
Пример #21
0
        public IActionResult Index(string type = "ALL", int page = 1, string searchKey = "", int instructorId = -1)
        {
            // Truyền gửi tên bảng
            if (type.ToUpper() == TestCategory.TEST_ALL)
            {
                ViewBag.TableName = "GENERAL";
            }
            else
            {
                ViewBag.TableName = type.ToUpper();
            }

            ViewBag.SearchKey = searchKey;
            // Lấy các đếm chuẩn
            ViewBag.UserTestCountOfAll       = _PieceOfTestManager.UserTestCountOfType(User.Id(), "ALL", string.Empty, instructorId);
            ViewBag.UserTestCountOfListening = _PieceOfTestManager.UserTestCountOfType(User.Id(), TestCategory.LISTENING, string.Empty, instructorId);
            ViewBag.UserTestCountOfReading   = _PieceOfTestManager.UserTestCountOfType(User.Id(), TestCategory.READING, string.Empty, instructorId);
            ViewBag.UserTestCountOfSpeaking  = _PieceOfTestManager.UserTestCountOfType(User.Id(), TestCategory.SPEAKING, string.Empty, instructorId);
            ViewBag.UserTestCountOfWriting   = _PieceOfTestManager.UserTestCountOfType(User.Id(), TestCategory.WRITING, string.Empty, instructorId);
            ViewBag.UserTestCountOfGeneral   = _PieceOfTestManager.UserTestCountOfType(User.Id(), TestCategory.TEST_ALL, string.Empty, instructorId);

            // Tiến hành cấu hình phân trang

            int start = (page - 1) * Config.PAGE_PAGINATION_LIMIT;
            // Lấy danh sách
            IEnumerable <PieceOfTest> PieceOfTests = _PieceOfTestManager.GetByPagination(User.Id(), type, start, Config.PAGE_PAGINATION_LIMIT, searchKey, instructorId);

            // Tạo đối tượng phân trang
            ViewBag.Pagination = new Pagination(nameof(Index), NameUtils.ControllerName <TestController>())
            {
                PageCurrent = page,
                Type        = type,
                NumberPage  = PaginationUtils.TotalPageCount(
                    _PieceOfTestManager.UserTestCountOfType(
                        User.Id(),
                        type.ToUpper().Trim(),
                        searchKey,
                        instructorId
                        ).ToInt(),
                    Config.PAGE_PAGINATION_LIMIT
                    ),
                Offset = Config.PAGE_PAGINATION_LIMIT
            };

            // Lấy GVHD nếu có
            if (instructorId > 0)
            {
                ViewBag.Instructor = _UserManager.Get(instructorId);
            }

            if (type == "ALL")
            {
                type = string.Empty;
            }

            // Thực hiện phần thống kê nho nhỏ
            ViewBag.Passed       = _PieceOfTestManager.PassedTestsCount(User.Id(), type);
            ViewBag.Failed       = _PieceOfTestManager.FaildTestsCount(User.Id(), type);
            ViewBag.HighestScore = _PieceOfTestManager.HightestScore(User.Id(), type).ToScores();

            return(View(PieceOfTests));
        }
Пример #22
0
        public IActionResult SubmitToolResultForGeneral(GeneralTestPaper gtp, string InstructorComments = "")
        {
            // Định nghĩa đích đến
            var dest = RedirectToAction(nameof(TestPaperController.ReviewHandler), NameUtils.ControllerName <TestPaperController>(), new { id = gtp.PieceOfTestId });

            // Nếu không xác định được bài thi
            if (gtp == null || gtp.PieceOfTestId <= 0)
            {
                this.NotifyError("Cannot determine the test");
                return(dest);
            }

            // Nếu nội dung đánh giá cho writing rỗng
            if (gtp.WritingTestPaper == null || gtp.WritingTestPaper.WritingPartTwos == null || string.IsNullOrEmpty(gtp.WritingTestPaper.WritingPartTwos.TeacherReviewParagraph))
            {
                this.NotifyError("You must correct paragraph for your student");
                return(dest);
            }

            // Nếu chưa cho điểm bài thi viết
            if (gtp.WritingTestPaper.WritingPartTwos.Scores < 0 || gtp.WritingTestPaper.WritingPartTwos.Scores > Config.SCORES_FULL_WRITING_PART_2)
            {
                this.NotifyError("Writing part 2 Score invalid");
                return(dest);
            }

            // Nếu chưa cho điểm bài thi nói
            if (gtp.SpeakingTestPaper.SpeakingPart.Scores < 0 || gtp.SpeakingTestPaper.SpeakingPart.Scores > Config.SCORES_FULL_SPEAKING)
            {
                this.NotifyError("Speaking Score invalid");
                return(dest);
            }

            // Nếu tất cả đã hợp lệ, tiến hành lấy bản ghi dữ liệu bài thi
            var pot = _PieceOfTestManager.Get(gtp.PieceOfTestId);

            // Lấy dữ liệu gốc của bài thi
            GeneralTestPaper _gtp = JsonConvert.DeserializeObject <GeneralTestPaper>(pot.ResultOfUserJson);

            // Cập nhật điểm và review part 2 của writing
            _gtp.WritingTestPaper.WritingPartTwos.TeacherReviewParagraph = gtp.WritingTestPaper.WritingPartTwos.TeacherReviewParagraph;
            _gtp.WritingTestPaper.WritingPartTwos.Scores = gtp.WritingTestPaper.WritingPartTwos.Scores;

            // Cập nhật điểm cho speaking
            _gtp.SpeakingTestPaper.SpeakingPart.Scores = gtp.SpeakingTestPaper.SpeakingPart.Scores;

            // Lưu lại json
            pot.ResultOfUserJson = JsonConvert.SerializeObject(_gtp);

            // Cập nhật lại comment nếu có
            if (!string.IsNullOrEmpty(InstructorComments))
            {
                pot.InstructorComments = InstructorComments;
            }

            // Tổng điểm lại
            pot.Scores = 0;
            if (_gtp.ListeningTestPaper.Part1Scores >= 0)
            {
                pot.Scores += _gtp.ListeningTestPaper.Part1Scores;
            }

            if (_gtp.ListeningTestPaper.Part2Scores >= 0)
            {
                pot.Scores += _gtp.ListeningTestPaper.Part2Scores;
            }

            if (_gtp.ReadingTestPaper.ReadingPartOnes.Scores >= 0)
            {
                pot.Scores += _gtp.ReadingTestPaper.ReadingPartOnes.Scores;
            }

            if (_gtp.ReadingTestPaper.ReadingPartTwos.Scores >= 0)
            {
                pot.Scores += _gtp.ReadingTestPaper.ReadingPartTwos.Scores;
            }

            if (_gtp.ReadingTestPaper.ReadingPartThrees.Scores >= 0)
            {
                pot.Scores += _gtp.ReadingTestPaper.ReadingPartThrees.Scores;
            }

            if (_gtp.ReadingTestPaper.ReadingPartFours.Scores >= 0)
            {
                pot.Scores += _gtp.ReadingTestPaper.ReadingPartFours.Scores;
            }

            if (_gtp.WritingTestPaper.WritingPartOnes.Scores >= 0)
            {
                pot.Scores += _gtp.WritingTestPaper.WritingPartOnes.Scores;
            }

            if (_gtp.WritingTestPaper.WritingPartTwos.Scores >= 0)
            {
                pot.Scores += _gtp.WritingTestPaper.WritingPartTwos.Scores;
            }

            if (_gtp.SpeakingTestPaper.SpeakingPart.Scores >= 0)
            {
                pot.Scores += _gtp.SpeakingTestPaper.SpeakingPart.Scores;
            }

            // Cập nhật vào CSDL
            _PieceOfTestManager.Update(pot);

            // Gửi thông báo thành công
            this.NotifySuccess("Update your review to student success!");

            // Về điểm đích đã khai báo
            return(dest);
        }
Пример #23
0
 private IActionResult NotFoundTest()
 {
     this.NotifyError("Can't find this test");
     return(RedirectToAction(nameof(HomeController.Index), NameUtils.ControllerName <HomeController>()));
 }
        public async Task <IActionResult> General(GeneralTestPaper paper, string audioBase64)
        {
            if (paper == null)
            {
                this.NotifyError("Not found yor test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            if (paper.PieceOfTestId <= 0)
            {
                this.NotifyError("Not found yor test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            // Lấy bài thi từ mã số
            PieceOfTest piece = _PieceOfTestManager.Get(paper.PieceOfTestId);

            if (piece == null)
            {
                this.NotifyError("Not found yor test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            if (piece.InstructorId != User.Id() && piece.UserId != User.Id())
            {
                this.NotifyError("You are not authorized to view or manipulate this test");
                return(Json(new { status = false, message = string.Empty, location = "/" }));
            }

            // Lấy chủ sở hữu của bài kiểm tra
            User owner = _UserManager.Get(piece.UserId);

            string fileName = $"{owner.Username.ToLower()}_{piece.TypeCode}_{piece.Id}";

            if (!string.IsNullOrEmpty(audioBase64))
            {
                // Chuyển base64 thành stream
                var bytes        = Convert.FromBase64String(audioBase64.Replace("data:audio/mpeg;base64,", ""));
                var memoryStream = new MemoryStream(bytes);

                // Tạo tệp tin
                IFormFile file = new FormFile(memoryStream, 0, bytes.Length, null, $"{fileName}.mp3")
                {
                    Headers     = new HeaderDictionary(),
                    ContentType = "audio/mpeg"
                };

                // Nếu file null
                if (file == null)
                {
                    return(Json(new { status = false, message = "Can not upload your audio, please try again!", location = "/" }));
                }

                // Tiến hành lưu tệp tin cho người dùng
                string path = await host.UploadForUserAudio(file, owner);

                // Nếu path không đúng
                if (string.IsNullOrEmpty(path))
                {
                    return(Json(new { status = false, message = "Can not upload your audio, please try again!", location = "/" }));
                }

                // Cập nhật đường dẫn bài nói của HV cho bài thi
                paper.SpeakingTestPaper.SpeakingPart.UserAudioPath = path;
            }

            // Tính toán số điểm
            paper.ScoreCalculate(piece.ResultOfTestJson);

            // Thời gian kết thúc bài thi
            float timeToFinished = DateTime.UtcNow.Subtract((DateTime)piece.CreatedTime).TotalSeconds.ToFloat();

            // Cập nhật dữ liệu
            piece.ResultOfUserJson = JsonConvert.SerializeObject(paper);
            piece.TimeToFinished   = timeToFinished;
            _PieceOfTestManager.Update(piece);

            // Chuyển đến trang kết quả
            return(Json(new { status = true, message = "Successful submission of exams", location = $"{Url.Action(nameof(Result), NameUtils.ControllerName<TestPaperController>())}/{piece.Id}" }));
        }
Пример #25
0
        public IActionResult Part1(
            long category,
            int categoryPage         = 1,
            int questionPage         = 1,
            string categorySearchKey = "",
            string questionSearchKey = "")
        {
            int categoryStart = (categoryPage - 1) * Config.PAGE_PAGINATION_LIMIT;
            int questionStart = (questionPage - 1) * Config.PAGE_PAGINATION_LIMIT;

            var testCategories = _TestCategoryManager.GetByPagination(TestCategory.WRITING, 1, categoryStart, Config.PAGE_PAGINATION_LIMIT);

            ViewBag.TestCategories = testCategories;

            var quesitons = new List <WritingPartOne>();

            if (category > 0)
            {
                var testCategory = _TestCategoryManager.Get(category);
                if (testCategory == null)
                {
                    return(NotFound());
                }
                else
                {
                    ViewBag.QuestionType = testCategory.Name ?? "";
                    quesitons            = _WritingPartOneManager.GetByPagination(category, questionStart, Config.PAGE_PAGINATION_LIMIT).ToList();
                }
            }
            else
            {
                ViewBag.QuestionType = "ALL";
                quesitons            = _WritingPartOneManager.GetByPagination(questionStart, Config.PAGE_PAGINATION_LIMIT).ToList();
            }

            ViewBag.Questions = quesitons;
            // Tạo đối tượng phân trang cho Category
            ViewBag.CategoryPagination = new Pagination(nameof(Part1), NameUtils.ControllerName <WritingManagerController>())
            {
                PageKey     = nameof(categoryPage),
                PageCurrent = categoryPage,
                NumberPage  = PaginationUtils.TotalPageCount(
                    _TestCategoryManager.GetAll(TestCategory.WRITING, 1).Count(),
                    Config.PAGE_PAGINATION_LIMIT),
                Offset = Config.PAGE_PAGINATION_LIMIT
            };
            var s = _WritingPartOneManager.CountAll(category.ToInt());

            // Tạo đối tượng phân trang cho Reading Part 1
            ViewBag.QuestionPagination = new Pagination(nameof(Part1), NameUtils.ControllerName <WritingManagerController>())
            {
                PageKey     = nameof(questionPage),
                PageCurrent = questionPage,
                TypeKey     = nameof(category),
                Type        = "0",
                NumberPage  = PaginationUtils.TotalPageCount(
                    _WritingPartOneManager.CountAll(category.ToInt()),
                    Config.PAGE_PAGINATION_LIMIT),
                Offset = Config.PAGE_PAGINATION_LIMIT
            };

            return(View($"{nameof(Part1)}/Index"));
        }
Пример #26
0
 public IActionResult Index()
 {
     return(RedirectToAction(nameof(TestController.NewTest), NameUtils.ControllerName <TestController>()));
 }