示例#1
0
        public async Task <TestResultDTO> EndTesting(Guid testResultId)
        {
            TestResult testResult = await _uow.TestResultRepository.GetById(testResultId);

            IEnumerable <TestAnswer> testAnswers = await _uow.TestAnswerRepository.GetForTestResult(testResultId);

            testResult.CorrectAnswers = testAnswers.Where(e => e.IsCorrect).Count();
            testResult.EndDateTime    = DateTime.UtcNow;

            _uow.TestResultRepository.Update(testResult);
            await _uow.SaveAsync();

            TestResultDTO testResultDto = _mapper.Map <TestResultDTO>(testResult);

            testResultDto.TotalCorrectAnswers = await _uow.QuestionRepository.CountForTest(testResult.TestId);

            Test test = await _uow.TestRepository.GetById(testResult.TestId);

            testResultDto.TestName = test.Name;

            if (!string.IsNullOrWhiteSpace(testResult.UserId))
            {
                UserProfile userProfile = await _uow.UserProfileRepository.GetById(testResult.UserId);

                testResultDto.UserFullName = $"{userProfile.FirstName} {userProfile.LastName}";
            }

            return(testResultDto);
        }
示例#2
0
        public void AddTestResult(TestResultDTO testResult)
        {
            TestResult newTestResult = map.Map <TestResult>(testResult);

            db.TestResults.Add(newTestResult);
            db.Save();
        }
示例#3
0
        public async Task <IHttpActionResult> Create(TestResultModel result)
        {
            if (result == null)
            {
                return(BadRequest("Test must not be null."));
            }

            try
            {
                result.UserId      = User.Identity.GetUserId();
                result.PassageDate = DateTime.Now;

                TestResultDTO resultDTO = _mapper.Map <TestResultModel, TestResultDTO>(result);

                TestResultDTO createdResult = await _resultService.Create(resultDTO);

                TestResultModel returnedResult = _mapper.Map <TestResultDTO, TestResultModel>(createdResult);

                string createdAtUrl = "http://www.google.com";

                return(Created(createdAtUrl, returnedResult));
            }
            catch (EntityNotFoundException)
            {
                return(NotFound());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
示例#4
0
        public async Task <ActionResult> _EndTesting(Guid testResultId)
        {
            System.Threading.Thread.Sleep(5000);
            TestResultDTO testResultDto = await _testingService.EndTesting(testResultId);

            return(PartialView("_EndTesting", testResultDto));
        }
        public int CreateTestResult(TestResultDTO testResult, Dictionary <int, bool> markedAnswers)
        {
            TestResult newTestResult = Mapping.Mapper.Map <TestResult>(testResult);
            //newTestResult.Test = context.Tests.Find(testResult.Test.TestID);

            int points = 0;

            foreach (var item in testResult.Test.Questions)
            {
                int correctAnswersCount = 0;
                foreach (var answer in item.Answers)
                {
                    if (markedAnswers.ContainsKey(answer.AnswerID))
                    {
                        correctAnswersCount += (markedAnswers[answer.AnswerID] == answer.IsCorrect) ? 1 : 0;
                    }
                }
                if (item.Answers.Count == correctAnswersCount)
                {
                    points += item.Points;
                }
            }

            newTestResult.Points = points;

            context.Database.Log = Console.WriteLine;
            var x = context.TestResults.Add(newTestResult);

            context.SaveChanges();
            return(x.TestResultID);
        }
示例#6
0
        public TestResultDTO GetTestResult(int testResultID)
        {
            TestResult    testResult = db.TestResults.Get(testResultID);
            TestResultDTO result     = map.Map <TestResultDTO>(testResult);

            return(result);
        }
示例#7
0
        public void ChangeArchievedTest(TestResultDTO test)
        {
            TestResult editedTestResult = db.TestResults.Get(test.TestResultID);

            map.Map(test, editedTestResult);
            db.TestResults.Update(editedTestResult);
            db.Save();
        }
        public IHttpActionResult Delete(int id)
        {
            TestResultDTO toDelete = _db.PerformanceService.GetTestResult(id);

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

            _db.PerformanceService.DeleteTestResult(id);
            return(Ok(toDelete));
        }
示例#9
0
        public TestResultDTO Test1(string input)
        {
            TestResultDTO dto = new TestResultDTO();

            dto.P1 = string.Format("I'm TestService {0}", DateTime.Now.ToString());
            dto.P2 = "111111111";
            dto.P3 = DateTime.Now;

            //throw new Exception("fffffffffff");

            return dto;
        }
示例#10
0
 /// <summary>
 /// The method converts an object of type TestResultDTO to an object of type TestResult.
 /// </summary>
 /// <param name="testResultDto">An object of type TestResultDTO.</param>
 /// <returns>An object of type TestResult.</returns>
 public static TestResult ToTestResultEntity(this TestResultDTO testResultDto)
 {
     return(new TestResult()
     {
         Id = testResultDto.Id,
         Name = testResultDto.Name,
         GoodAnswers = testResultDto.GoodAnswers,
         BadAnswers = testResultDto.BadAnswers,
         DateComplete = testResultDto.DateCompleted,
         User = testResultDto.User?.ToUserEntity()
     });
 }
示例#11
0
 public static TestResultViewModel ToMvcTestResult(this TestResultDTO testResultEntity)
 {
     return(new TestResultViewModel()
     {
         Id = testResultEntity.Id,
         Name = testResultEntity.Name,
         GoodAnswers = testResultEntity.GoodAnswers,
         BadAnswers = testResultEntity.BadAnswers,
         DateComleted = testResultEntity.DateCompleted,
         User = testResultEntity.User
     });
 }
示例#12
0
        // Topic test result details list.
        public async Task <ActionResult> TopicTestResultDetails(int?id)
        {
            try
            {
                // I.Checks.
                // Check id.
                if (!int.TryParse(id.ToString(), out int intId))
                {
                    return(RedirectToAction("Index"));
                }
                // Get TestResultDTO object.
                TestResultDTO testResultDTO = await TestResultService.GetAsync(intId);

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

                // II. AutoMapper Setup.
                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap <TestResultDTO, TestResultViewModel>()
                    .ForMember("Id", opt => opt.MapFrom(tr => tr.TestResultId))
                    .ForMember("TestTitle", opt => opt.MapFrom(tr => tr.TestResultDetails.FirstOrDefault().Question.Topic.TopicTitle))
                    .ForMember(tr => tr.UserEmail, option => option.Ignore());
                    cfg.CreateMap <TestResultDetailDTO, TestResultDetailViewModel>()
                    .ForMember("Question", opt => opt.MapFrom(trd => trd.Question.QuestionText))
                    .ForMember("Topic", opt => opt.MapFrom(trd => trd.Question.Topic.TopicTitle));
                });
                IMapper iMapper = config.CreateMapper();

                // III. Set ViewBag properties.
                TestResultViewModel testResult = iMapper.Map <TestResultDTO, TestResultViewModel>(testResultDTO);
                ViewBag.CourseName = testResultDTO.TestResultDetails.FirstOrDefault().Question.Topic.Course.CourseTitle;
                ViewBag.TopicName  = testResultDTO.TestResultDetails.FirstOrDefault().Question.Topic.TopicTitle;
                ViewBag.Result     = testResult.Result * 1000 / testResult.MaxScore;
                ViewBag.MaxScore   = 1000;
                ViewBag.ParentId   = testResultDTO.TestResultDetails.FirstOrDefault().Question.Topic.CourseId;

                // IV. Get data for a view.
                IEnumerable <TestResultDetailDTO>       source = TestResultDetailService.Find(trd => trd.TestResultId == intId);//.ToList();
                IEnumerable <TestResultDetailViewModel> testResultDetailList = iMapper.Map <IEnumerable <TestResultDetailDTO>, IEnumerable <TestResultDetailViewModel> >(source).OrderBy(trd => trd.Topic);

                // V.
                return(View(testResultDetailList));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
示例#13
0
        public ActionResult SubmitTest(TestResultDTO t)
        {
            var User = (TaiKhoan)Session["User"];

            if (User == null)
            {
                return(RedirectToAction("Login", "Login"));
            }
            var Member = ClassService.CheckUserRole(User.ID, (long)t.CourseID) == 2 ? true : false;

            if (Member && ClassService.GetTestResult((long)t.TestID, User.ID) == null)
            {
                return(Json(ClassService.SubmitTest(t), JsonRequestBehavior.AllowGet));
            }
            return(Json(null, JsonRequestBehavior.AllowGet));
        }
示例#14
0
        public TestResultDTO Get(int id)
        {
            if (id <= 0)
            {
                throw new ArgumentException("Incorrect result id.");
            }

            TestResult testResult = _database.TestResults.Get(id);

            if (testResult == null)
            {
                throw new EntityNotFoundException($"Test result with id = {id} not found.");
            }

            TestResultDTO returnedTestResult = _mapper.Map <TestResult, TestResultDTO>(testResult);

            return(returnedTestResult);
        }
示例#15
0
        private static TestResult ConvertDto(TestResultDTO resultDTO, Test test, int acSessionId)
        {
            var instance = new TestResult
            {
                Score           = resultDTO.score,
                StartTime       = resultDTO.startTime.ConvertFromUnixTimeStamp(),
                EndTime         = resultDTO.endTime.ConvertFromUnixTimeStamp(),
                Email           = resultDTO.email.With(x => x.Trim()),
                ACEmail         = resultDTO.acEmail.With(x => x.Trim()),
                IsArchive       = resultDTO.isArchive,
                DateCreated     = DateTime.Now,
                ParticipantName = resultDTO.participantName.With(x => x.Trim()),
                Test            = test,
                ACSessionId     = acSessionId,
                IsCompleted     = resultDTO.isCompleted
            };

            return(instance);
        }
示例#16
0
        public async Task <TestResultDTO> Create(TestResultDTO testResultDTO)
        {
            if (testResultDTO == null)
            {
                throw new ArgumentNullException("TestDTO must not be null.");
            }

            TestResult result = _mapper.Map <TestResultDTO, TestResult>(testResultDTO);

            result.Result = CalculateResult(_database.Tests.Get(result.TestId), testResultDTO.Details);

            TestResult createdTestResult = _database.TestResults.Create(result);

            await _database.SaveAsync();

            TestResultDTO returnedTestResult = _mapper.Map <TestResult, TestResultDTO>(createdTestResult);

            return(returnedTestResult);
        }
示例#17
0
        public async Task <TestResultDTO> StartTesting(Guid testId, string userId)
        {
            TestResult testResult = new TestResult
            {
                TestId         = testId,
                UserId         = userId,
                StartDateTime  = DateTime.UtcNow,
                CorrectAnswers = 0
            };

            _uow.TestResultRepository.Create(testResult);
            await _uow.SaveAsync();

            TestResultDTO testResultDto = _mapper.Map <TestResultDTO>(testResult);

            testResultDto.TotalCorrectAnswers = await _uow.QuestionRepository.CountForTest(testResultDto.TestId);

            return(testResultDto);
        }
示例#18
0
        public async Task <TestResultDTO> Delete(int id)
        {
            if (id <= 0)
            {
                throw new ArgumentException("Incorrect result id.");
            }

            TestResult deletedTestResult = _database.TestResults.Delete(id);

            if (deletedTestResult == null)
            {
                throw new EntityNotFoundException($"Test result with id = {id} not found.");
            }

            await _database.SaveAsync();

            TestResultDTO returnedTestresult = _mapper.Map <TestResult, TestResultDTO>(deletedTestResult);

            return(returnedTestresult);
        }
        public async Task <TestResultDTO> GetTestResult(Guid testResultId)
        {
            TestResult testResult = await _uow.TestResultRepository.GetById(testResultId);

            TestResultDTO testResultDto = _mapper.Map <TestResultDTO>(testResult);

            testResultDto.TotalCorrectAnswers = await _uow.QuestionRepository.CountForTest(testResult.TestId);

            Test test = await _uow.TestRepository.GetById(testResultDto.TestId);

            testResultDto.TestName = test.Name;

            if (!string.IsNullOrWhiteSpace(testResult.UserId))
            {
                UserProfile userProfile = await _uow.UserProfileRepository.GetById(testResult.UserId);

                testResultDto.UserFullName = $"{userProfile.FirstName} {userProfile.LastName}";
            }

            return(testResultDto);
        }
示例#20
0
        public IHttpActionResult GetById(int id)
        {
            if (id <= 0)
            {
                return(BadRequest("Incorrect result id."));
            }

            try
            {
                TestResultDTO resultDTO = _resultService.Get(id);

                TestResultModel returnedResult = _mapper.Map <TestResultDTO, TestResultModel>(resultDTO);

                return(Ok(returnedResult));
            }
            catch (EntityNotFoundException)
            {
                return(NotFound());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
 // PUT: api/TestResults/5
 public IHttpActionResult Put(int id, TestResultModel value)
 {
     if (id != value.TestResultID)
     {
         return(BadRequest());
     }
     try
     {
         TestResultDTO edited = map.Map <TestResultDTO>(value);
         _db.TestService.ChangeArchievedTest(edited);
     }
     catch
     {
         if (!TestResultExists(id))
         {
             return(NotFound());
         }
         else
         {
             throw;
         }
     }
     return(StatusCode(HttpStatusCode.NoContent));
 }
示例#22
0
        public static TestCompleteViewModel ToMvcTestComplete(this TestResultDTO testResult)
        {
            string Description = String.Empty;
            string result      = String.Empty;
            double questions   = testResult.BadAnswers + testResult.GoodAnswers;
            string points      = (testResult.GoodAnswers / questions).ToString("####.#");

            switch (points)
            {
            case "":
                Description = "It's very bad. Try your hand again, maybe you just got lucky. Or you were tested at random.";
                result      = "Test is not completed.";
                break;

            case ",1":
                Description = "It's very bad. Try your hand again, maybe you just got lucky. Or you were tested at random.";
                result      = "Test is not completed.";
                break;

            case ",2":
                Description = "Not bad, but it could have been worse.";
                result      = "Test is not completed.";
                break;

            case ",3":
                Description = "The important thing is not to win but to take part.";
                result      = "Test is not completed.";
                break;

            case ",4":
                Description = "The important thing is not to win but to take part.";
                result      = "Test is not completed.";
                break;

            case ",5":
                Description = "The important thing is not to win but to take part.";
                result      = "Test is not completed.";
                break;

            case ",6":
                Description = "You do not have quite a bit.";
                result      = "Test is not completed.";
                break;

            case ",7":
                Description = "Congratulations!";
                result      = "Test is completed.";
                break;

            case ",8":
                Description = "Congratulations!";
                result      = "Test is cmpleted.";
                break;

            case ",9":
                Description = "Congratulations! ";
                result      = "Test is completed.";
                break;

            case "1":
                Description = "Congratulations! You have very good data in this area. If you have the desire and time, you can build your test!";
                result      = "Test is completed.";
                break;

            default:
                Description = "Sorry, but while checking something went wrong test. Try to go through again.";
                result      = "Error.";
                break;
            }
            return(new TestCompleteViewModel()
            {
                GoodAnswers = testResult.GoodAnswers,
                Questions = testResult.BadAnswers + testResult.GoodAnswers,
                Description = Description,
                Result = result
            });
        }
示例#23
0
 public TestRunModel()
 {
     MarkedAnswers = new Dictionary <int, bool>();
     TestResult    = new TestResultDTO();
 }
 public void TestResult(TestResultDTO result)
 {
 }
 public void DeleteTestResult(TestResultDTO test)
 {
     _uow.TestResults.Delete(test.ToTestResultEntity());
 }
 public void CreateTestResult(TestResultDTO test)
 {
     _uow.TestResults.Create(test.ToTestResultEntity());
 }
示例#27
0
        public void SendTo3ndParty([FromBody] IEnumerable <AdminOnlineModels.TestRegistration> testRegis)
        {
            var sheetForSend = repoSheet.ListExamSheetByID(testRegis.Where(x => x.SheetId != string.Empty).Select(x => x.SheetId).ToList());

            if (testRegis.FirstOrDefault().SiteId == "01")
            {
                List <TestResultDTO> _testresult = new List <TestResultDTO>();

                foreach (var item in sheetForSend)
                {
                    DateTime regDate    = item.TestReg.RegDate;
                    DateTime examDate   = item.ExamDateTime.Value;
                    var      APPLY_DATE = regDate.Year < 2500 ? regDate.AddYears(543).ToString("yyyyMMdd", CultureInfo.GetCultureInfo("en-us")) : regDate.Year > 3000 ? regDate.AddYears(-543).ToString("dd-MMM-yyyy", CultureInfo.GetCultureInfo("en-us")) : regDate.ToString("yyyyMMdd", CultureInfo.GetCultureInfo("en-us"));
                    var      EXAM_DATE  = examDate.Year < 2500 ? examDate.AddYears(543).ToString("yyyyMMdd", CultureInfo.GetCultureInfo("en-us")) : examDate.Year > 3000 ? examDate.AddYears(-543).ToString("dd-MMM-yyyy", CultureInfo.GetCultureInfo("en-us")) : examDate.ToString("yyyyMMdd", CultureInfo.GetCultureInfo("en-us"));

                    DateTime currDate   = DateTime.Now;
                    string   insertDate = currDate.Year < 2500 ? currDate.ToString("dd-MMM-yyyy", CultureInfo.GetCultureInfo("en-us")) : currDate.Year > 3000 ? currDate.AddYears(-543).ToString("dd-MMM-yyyy", CultureInfo.GetCultureInfo("en-us")) : currDate.ToString("dd-MMM-yyyy", CultureInfo.GetCultureInfo("en-us"));

                    var testResult = new TestResultDTO()
                    {
                        CERT_YY = Convert.ToInt32(item.TestReg.CertData.CertYear),
                        CERT_NO = item.TestReg.CertData.CertNo,
                        //REQ_DATE = APPLY_DATE,
                        REQ_DATE         = item.TestReg.RegDateString,
                        REQ_NO           = item.TestReg.PID,
                        SEQ_NO           = item.TestCount.ToString(),
                        EXAM_DATE        = EXAM_DATE,
                        PASS_NO          = item.TestCount,
                        EXAM_RESULT      = item.LatestStatus == "PASS",
                        PLT_CODE         = item.Subject.SubjectCode,
                        Qxx              = null,
                        EXAM_FLAG        = item.TestCount - 1,
                        UPD_USER_CODE    = item.TestReg.CertData.UserCode,
                        LAST_UPD_DATE    = DateTime.Parse(insertDate),
                        CREATE_USER_CODE = item.TestReg.CertData.UserCode,
                        CREATE_DATE      = insertDate,
                        QDETAIL          = "NULL",
                        IsPass           = item.LatestStatus == "PASS",
                        EXAM_SCORE       = item.CorrectScore,
                        PASS_EXAM_DATE   = EXAM_DATE,
                        UPD_USER_ID      = item.TestReg.CertData.UserCode,
                        //APPLY_DATE = APPLY_DATE,
                        APPLY_DATE      = item.TestReg.RegDateString,
                        OUT_COURSE_CODE = item.Subject.SubjectCode == "11" ? "201" : "301",
                    };

                    var    qxx     = new List <bool>();
                    string QDETAIL = "";

                    foreach (var question in item.RandomQuestions)
                    {
                        bool isCorrect = false;
                        if (question.UserAnswer.IsCorrect.HasValue && question.UserAnswer.IsCorrect.Value)
                        {
                            isCorrect = true;
                        }
                        qxx.Add(isCorrect);

                        //TODO : ADD REf ID
                        //QDETAIL += q.RefId + "|";
                        QDETAIL += question.QuestionNumber + "|";
                    }

                    testResult.Qxx = qxx.ToArray();

                    testResult.QDETAIL = QDETAIL.Substring(0, QDETAIL.Length - 1); //ตัด "|" ตัวสุดท้ายออก

                    _testresult.Add(testResult);

                    item.TestReg.ExamStatus = "SEND";
                }

                var endpointUrl           = "http://61.91.64.134/DataSyncResult/Services/SyncResultDataService.svc";
                BasicHttpBinding binding  = new BasicHttpBinding();
                EndpointAddress  endpoint = new EndpointAddress(endpointUrl);
                ChannelFactory <ISyncResultDataService> channelFactory = new ChannelFactory <ISyncResultDataService>(binding, endpoint);
                ISyncResultDataService clientProxy = channelFactory.CreateChannel();

                WebClient web = new WebClient();
                web.DownloadString("http://61.91.64.134/DataSyncResult/Services/SyncResultQueService.svc");

                clientProxy.SyncResultToFileAsync(_testresult.ToArray());

                channelFactory.Close();

                repoSheet.UpdateExamSheet(sheetForSend.ToList());
            }
        }
        // Private method to save User test results.
        private async Task <OperationDetails> SaveCurrentTestResults(int?id, string currentUserId, TestResultViewModel testResult)
        {
            bool             isTopicTest;
            OperationDetails operationDetails;

            try
            {
                // I. Checks.
                if (id != null)
                {
                    if (!int.TryParse(id.ToString(), out int intId) || intId > 1 || intId < 0)
                    {
                        operationDetails = new OperationDetails(false, "Incorrect parameter id!", "TestController.SaveCurrentTestResults");
                        return(operationDetails);
                    }
                    if (intId == 1)
                    {
                        isTopicTest = true;
                    }
                    else
                    {
                        isTopicTest = false;
                    }
                }
                else
                {
                    operationDetails = new OperationDetails(false, "Incorrect parameter id!", "TestController.SaveCurrentTestResults");
                    return(operationDetails);
                }

                // II. Create TestResultDTO object and set its properties.
                TestResultDTO testResultDTO = new TestResultDTO()
                {
                    UserProfileId = currentUserId,
                    Result        = testResult.Result,
                    MaxScore      = testResult.MaxScore,
                    IsPassedTest  = testResult.IsPassedTest,
                    IsTopicTest   = isTopicTest
                };

                // III. Add a test result to DB.
                operationDetails = await TestResultService.CreateAsync(testResultDTO, currentUserId);

                if (!operationDetails.Succedeed)
                {
                    return(operationDetails);
                }

                // IV. Add test result details to DB.
                foreach (var item in testResult.TestResultDetails)
                {
                    TestResultDetailDTO testResultDetailDTO = new TestResultDetailDTO()
                    {
                        TestResultId   = testResultDTO.TestResultId,
                        QuestionId     = item.QuestionId,
                        IsProperAnswer = item.IsProperAnswer
                    };
                    operationDetails = await TestResultDetailService.CreateAsync(testResultDetailDTO, currentUserId);

                    if (!operationDetails.Succedeed)
                    {
                        return(operationDetails);
                    }
                }

                // V.
                return(new OperationDetails(true, "Test results have successfully added to DB!", "TestController.SaveCurrentTestResults"));
            }
            catch (Exception ex)
            {
                return(new OperationDetails(false, "Failed to add test results to DB! Exception: " + ex.Message, "TestController.SaveCurrentTestResults"));
            }
        }