Exemple #1
0
        public async Task <IHttpActionResult> UpdateById(int id, TestModel test)
        {
            if (test == null)
            {
                return(BadRequest("Test must not be null."));
            }

            try
            {
                test.Id = id;

                TestDTO testDTO = _mapper.Map <TestModel, TestDTO>(test);

                TestDTO updatedTest = await _testService.Update(testDTO);

                TestModel returnedTest = _mapper.Map <TestDTO, TestModel>(updatedTest);

                return(Ok(returnedTest));
            }
            catch (EntityNotFoundException)
            {
                return(NotFound());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Exemple #2
0
        public async Task <IHttpActionResult> Create(TestModel test)
        {
            if (test == null)
            {
                return(BadRequest("Test must not be null."));
            }

            try
            {
                TestDTO testDTO = _mapper.Map <TestModel, TestDTO>(test);

                TestDTO createdTest = await _testService.Create(testDTO);

                TestModel returnedTest = _mapper.Map <TestDTO, TestModel>(createdTest);

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

                return(Created(createdAtUrl, returnedTest));
            }
            catch (EntityNotFoundException)
            {
                return(NotFound());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Exemple #3
0
        public void GetTestById_ReturnsCorrectTest()
        {
            //arrange
            var expectedTest = new Test()
            {
                Id = correctGuid
            };
            var expectedTestDto = new TestDTO()
            {
                Id = correctGuid
            };

            var all = new List <Test>()
            {
                expectedTest,
                new Test()
                {
                    Id = wrongGuid
                }
            };

            repoTestMock.Setup(x => x.All).Returns(all.AsQueryable);
            mapperMock.Setup(x => x.MapTo <TestDTO>(expectedTest)).Returns(expectedTestDto);

            //act
            var foundTest = fakeTestService.GetTestById(correctGuid);

            //assert
            Assert.AreEqual(expectedTestDto, foundTest);
            Assert.AreSame(expectedTestDto, foundTest);
        }
Exemple #4
0
        public void GetTestByName_ReturnsCorrectTest()
        {
            //arrange
            var testCorrectName = "Petko";
            var testWrongName   = "Marto Stamatov";
            var expectedTest    = new Test()
            {
                Name = testCorrectName
            };
            var expectedTestDto = new TestDTO()
            {
                Name = testCorrectName
            };

            var all = new List <Test>()
            {
                expectedTest,
                new Test()
                {
                    Name = testWrongName
                }
            };

            repoTestMock.Setup(x => x.All).Returns(all.AsQueryable);
            mapperMock.Setup(x => x.MapTo <TestDTO>(expectedTest)).Returns(expectedTestDto);

            //act
            var foundTest = fakeTestService.GetTestByName(testCorrectName);

            //assert
            Assert.AreEqual(expectedTestDto, foundTest);
            Assert.AreSame(expectedTestDto, foundTest);
        }
Exemple #5
0
        public void Get_IfGet_GetsSuccess()
        {
            // arrange
            const int id     = 1;
            var       title  = Guid.NewGuid().ToString();
            var       entity = new TestEntity
            {
                Id    = id,
                Title = title
            };
            var dto = new TestDTO
            {
                Id    = id,
                Title = title
            };
            var entities = new[] { entity };
            var dtos     = new[] { dto };

            _currentRepositoryMock.Setup(_ => _.FindAll(false)).Returns(entities.AsQueryable());
            _mapperMock.Setup(_ => _.Map <TestEntity, TestDTO>(entity)).Returns(dto);

            // act
            var actualDTOs = _sut.Get().ToArray();

            // assert
            _currentRepositoryMock.Verify(_ => _.FindAll(false), Times.Once);
            _mapperMock.Verify(_ => _.Map <TestEntity, TestDTO>(entity), Times.Once);
            Assert.NotNull(actualDTOs);
            Assert.True(actualDTOs.Length == 1);
            Assert.True(dtos.SequenceEqual(actualDTOs));
        }
Exemple #6
0
        public void Add_IfAdd_AddsSuccess()
        {
            // arrange
            var entity = new TestEntity
            {
                Id    = 1,
                Title = Guid.NewGuid().ToString()
            };
            var dto = new TestDTO
            {
                Id    = 1,
                Title = Guid.NewGuid().ToString()
            };

            _mapperMock.Setup(_ => _.Map <TestDTO, TestEntity>(dto)).Returns(entity);
            _currentRepositoryMock.Setup(_ => _.Insert(entity));
            _unitOfWorkMock.Setup(_ => _.Commit());
            _mapperMock.Setup(_ => _.Map <TestEntity, TestDTO>(entity)).Returns(dto);

            // act
            var result = _sut.Add(dto);

            // assert
            Assert.Equal(dto, result);
            _mapperMock.Verify(_ => _.Map <TestDTO, TestEntity>(dto), Times.Once);
            _currentRepositoryMock.Verify(_ => _.Insert(entity), Times.Once);
            _unitOfWorkMock.Verify(_ => _.Commit(), Times.Once);
            _mapperMock.Verify(_ => _.Map <TestEntity, TestDTO>(entity), Times.Once);
        }
Exemple #7
0
        public void Get_IfGetById_GetsByIdSuccess()
        {
            const int id     = 1;
            var       entity = new TestEntity
            {
                Id    = id,
                Title = Guid.NewGuid().ToString()
            };
            var dto = new TestDTO
            {
                Id    = id,
                Title = Guid.NewGuid().ToString()
            };

            _currentRepositoryMock.Setup(_ => _.FindById(id)).Returns(entity);
            _mapperMock.Setup(_ => _.Map <TestEntity, TestDTO>(entity)).Returns(dto);

            // act
            var actualDTO = _sut.Get(id);

            // assert
            _currentRepositoryMock.Verify(_ => _.FindById(id), Times.Once);
            _mapperMock.Verify(_ => _.Map <TestEntity, TestDTO>(entity), Times.Once);
            Assert.Equal(dto, actualDTO);
        }
 public static void UpdateTest(TestDTO newTest)
 {
     using (Entities e = new Entities())
     {
     }
     //todo
 }
Exemple #9
0
        public TestDTO GetTest(int?id)
        {
            if (id == null)
            {
                throw new ValidationException("Не установлен id теста", "");
            }
            var test = Database.Tests.Get(id.Value);

            if (test == null)
            {
                throw new ValidationException("Тест не найден", "");
            }
            var     mapper  = new MapperConfiguration(cfg => cfg.CreateMap <Test, TestDTO>()).CreateMapper();
            TestDTO testDTO = mapper.Map <Test, TestDTO>(test);

            mapper = new MapperConfiguration(cfg => cfg.CreateMap <Question, QuestionDTO>()).CreateMapper();

            testDTO.Questions =
                mapper.Map <IEnumerable <Question>, List <QuestionDTO> >(Database.Questions.GetAll().Where(quest => quest.Test_ID == testDTO.Test_ID));

            mapper = new MapperConfiguration(cfg => cfg.CreateMap <Answer, AnswerDTO>()).CreateMapper();

            foreach (var quest in testDTO.Questions)
            {
                quest.Answers =
                    mapper.Map <IEnumerable <Answer>, List <AnswerDTO> >(Database.Answers.GetAll().Where(answ => answ.Question_ID == quest.Question_ID));
            }


            return(testDTO);
        }
Exemple #10
0
        public ActionResult <int> PutTestById([FromBody] TestInputModel testModel)
        {
            Mapper           mapper = new Mapper();
            AuthorDataAccess tests  = new AuthorDataAccess();

            if (string.IsNullOrWhiteSpace(testModel.Name))
            {
                return(BadRequest("Введите название теста"));
            }
            if (string.IsNullOrWhiteSpace(testModel.DurationTime))
            {
                return(BadRequest("Введите время прохождения теста"));
            }
            if (testModel.QuestionNumber == null)
            {
                return(BadRequest("Введите количество вопросов в тесте"));
            }
            if (testModel.SuccessScore == null)
            {
                return(BadRequest("Введите минимальный балл для прохождения теста"));
            }
            TestDTO testDto = mapper.ConvertTestInputModelToTestDTO(testModel);

            return(Ok(tests.UpdateTestById(testDto)));
        }
Exemple #11
0
        public ActionResult EnterTest()
        {
            string title  = Request["Title"];
            string desc   = Request["Description"];
            string sec    = Request["Section"];
            string dt     = Request["Date"];
            int    t_mrks = int.Parse(Request["marks"]);

            TestDTO t_dto = new TestDTO();

            t_dto.Title       = title;
            t_dto.Description = desc;
            t_dto.Section     = sec;
            t_dto.Date        = dt;
            t_dto.TotalMarks  = t_mrks;
            UserDTO usr = (UserDTO)Session["User"];

            t_dto.TeacherUname = usr.Username;

            UserRepository repo = new UserRepository();
            int            tid  = repo.SaveTest(t_dto);

            ViewBag.tid = tid;
            if (tid > 0)
            {
                repo.SaveStudentsQuiz(t_dto);
                return(View("FillTest"));
            }
            else
            {
                return(View("CreateTest", tid));
            }
        }
Exemple #12
0
        public void EditTest(TestDTO testDTO)
        {
            var  mapper = new MapperConfiguration(cfg => cfg.CreateMap <TestDTO, Test>()).CreateMapper();
            Test test   = mapper.Map <TestDTO, Test>(testDTO);

            Database.Tests.Update(test);
        }
Exemple #13
0
        public TestDTO GetByID(int testID)
        {
            Test    test   = db.Tests.Get(testID);
            TestDTO result = map.Map <TestDTO>(test);

            return(result);
        }
        public static test TestToDAL(TestDTO t)
        {
            return(new test()
            {
                over_mark = t.over_mark,
                test_date = t.test_date,
                test_start_time = t.test_start_time,
                test_end_time = t.test_end_time,
                test_id = t.test_id,
                // test_question = e.test_question.Where(tq => tq.test_id == t.test_id).ToList(),

                level = t.level,
                quesPercent = t.quesPercent,
                teacherId = t.teacherId,
                name = t.name
                       //class_test = e.class_test.Where(c => c.test_id == t.test_id).ToList()
                       //            public int test_id { get; set; }
                       //public System.DateTime test_date_start { get; set; }
                       //public System.DateTime test_date_end { get; set; }
                       //public double over_mark { get; set; }
                       //public int class_id { get; set; }
                       //public bool enable { get; set; }
                       //public int level { get; set; }
            });
        }
        public void MappingToDataRow_test()
        {
            // this is the mapper
            var mapper = ObjectMapperManager.DefaultInstance.GetMapper <TestDTO, DataRow>(new Map2DataRowConfig());

            // initialization of test DTO object
            TestDTO testDataObject = new TestDTO
            {
                field1 = "field1",
                field2 = 10,
                field3 = true
            };

            // Initializing of test table. Usual this table is read from database.
            DataTable dt = new DataTable();

            dt.Columns.Add("field1", typeof(string));
            dt.Columns.Add("field2", typeof(int));
            dt.Columns.Add("field3", typeof(bool));
            dt.Rows.Add();
            DataRow dr = dt.Rows[0];

            // Mapping test object to datarow
            mapper.Map(testDataObject, dr);

            // Check if object is correctly mapped
            Assert.AreEqual("field1", dr["field1"]);
            Assert.AreEqual(10, dr["field2"]);
            Assert.AreEqual(true, dr["field3"]);
        }
Exemple #16
0
        public TestDTO GetAndWriteParcelDetailsById(TestViewModel testViewModel)
        {
            // this is where ViewModel validation is being arranged normally

            try
            {
                var parcel = _parcelService.GetById(testViewModel.ParcelId);

                var result = new TestDTO
                {
                    Status         = TestStatus.Success,
                    SenderName     = parcel.SenderData.FirstName,
                    ReceiverName   = parcel.ReceiverData.FirstName,
                    StoragePointId = (int)parcel.StorePlaceId
                };

                return(result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);

                var result = new TestDTO
                {
                    Status = TestStatus.Failure
                };

                return(result);
            }
        }
Exemple #17
0
        public async Task <IActionResult> TestForm(ManageTestModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                TestDTO test = new TestDTO()
                {
                    IsRandomQuestionsOrder = model.IsRandomQuestions,
                    Name   = model.TestName,
                    TestId = model.TestId
                };

                if (!string.IsNullOrEmpty(model.Questions))
                {
                    test.TestQuestions = JsonConvert.DeserializeObject <List <TestQuestionDTO> >(model.Questions);
                }

                await TestService.Test_SaveAsync(test);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                return(View(model));
            }

            return(RedirectToAction("Index"));
        }
Exemple #18
0
        public ResultDTO GetScore(int Test_ID, string User_ID, List <int> user_answers, string FullOpen)
        {
            ResultDTO resultDTO = new ResultDTO();

            resultDTO.FullOpenAnswer = FullOpen;
            List <Answer> answers   = new List <Answer>();
            TestDTO       testDTO   = testService.GetTest(Test_ID);
            List <int>    true_list = new List <int>();

            foreach (var tru in testDTO.Questions)
            {
                foreach (var true_answers in tru.Answers)
                {
                    if (true_answers.ISCorrect)
                    {
                        true_list.Add(true_answers.Answer_ID);
                    }
                }
            }
            CheckTest checkTest = new CheckTest(true_list, user_answers);

            resultDTO.Test_ID = Test_ID;
            resultDTO.User_ID = User_ID;
            resultDTO.Score   = checkTest.GetScore();
            resultDTO.Date    = DateTime.Now;
            var    mapper = new MapperConfiguration(cfg => cfg.CreateMap <ResultDTO, Result>()).CreateMapper();
            Result result = mapper.Map <ResultDTO, Result>(resultDTO);

            Database.Results.Create(result);
            return(resultDTO);
        }
Exemple #19
0
        public void UpdateTest(TestDTO test)
        {
            var testDAL = _mapper.Map <TestDTO, Test>(test);

            db.Tests.Update(testDAL);
            db.Save();
        }
Exemple #20
0
        private void btnView_Click(object sender, EventArgs e)
        {
            TestDTO test = (sender as Button).Tag as TestDTO;
            FTest   f    = new FTest(test.code, test.courseID, test.examID, false);

            f.ShowDialog();
        }
Exemple #21
0
        public List <TestDTO> getListFullTestbyManager(string idmanager)
        {
            List <TestDTO> lst = new List <TestDTO>();

            string    query  = $" select * from test  join COURSE on COURSE.courseID= test.courseID where  test.courseID in (select courseID from course where IDmngLecturer='{UserDTO.Instance.userID}')       ";
            DataTable result = DataProvider.Instance.ExecuteQuery(query);

            foreach (DataRow i in result.Rows)
            {
                TestDTO t = new TestDTO();
                t.courseID    = i["courseID"].ToString().Trim();
                t.code        = i["Code"].ToString().Trim();
                t.DateComfirm = (DateTime)i["DateConfirm"];
                t.examID      = i["examID"].ToString().Trim();
                t.corseName   = i["CourseName"].ToString().Trim();
                try
                {
                    t.DateAppove = (DateTime)i["DateAppove1"];
                }
                catch
                {
                }
                lst.Add(t);
            }
            return(lst);
        }
Exemple #22
0
        public List <TestDTO> GetAllTest(string board_Id)
        {
            List <TestDTO> listTest = new List <TestDTO>();

            this.ConnectToDatabase();

            MySqlCommand command = this.mySQLConnection.CreateCommand();

            command.CommandText = "SELECT * FROM TEST where TEST_ID = " + board_Id;

            MySqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                string   testId   = reader.GetString(0);
                string   classId  = reader.GetString(1);
                DateTime testDate = reader.GetDateTime(2);
                string   testHour = reader.GetString(3);

                TestDTO test = new TestDTO(testId, classId, testDate, testHour);
                listTest.Add(test);
            }

            reader.Close();
            this.Close();
            return(listTest);
        }
Exemple #23
0
        public TestDTO GetTest(string id)
        {
            TestDTO test;

            this.ConnectToDatabase();

            MySqlCommand command = this.mySQLConnection.CreateCommand();

            command.CommandText = "SELECT * FROM TEST WHERE TEST_ID = " + id;

            MySqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                string   testId   = reader.GetString(0);
                string   classId  = reader.GetString(1);
                DateTime testDate = reader.GetDateTime(2);
                string   testHour = reader.GetString(3);

                test = new TestDTO(testId, classId, testDate, testHour);
                return(test);
            }

            reader.Close();
            this.Close();
            return(null);
        }
Exemple #24
0
        public void UpdateTestInfo(TestDTO entity)
        {
            Test test = _mapper.Map <Test>(entity);

            _unitOfWork.Tests.Update(test);
            _unitOfWork.SaveChanges();
        }
Exemple #25
0
        //[Authorize(Roles = "Admin, Editor")]
        public IHttpActionResult UpdateTestInfo(int id, [FromBody] UpdateTestInfoBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            TestDTO testToUpdate = _testService.GetById(id);

            if (testToUpdate == null)
            {
                return(Content(HttpStatusCode.NotFound,
                               $"Test with id={id} does not exist."));
            }

            TestDTO updatedTest = new TestDTO()
            {
                Id          = id,
                Title       = model.Title,
                Descr       = model.Descr,
                DurationMin = model.DurationMin,
                CategoryId  = model.CategoryId
            };

            _testService.UpdateTestInfo(updatedTest);

            return(Ok());
        }
Exemple #26
0
        public void CreateTest(TestDTO test)
        {
            var testToAdd = _mapper.Map <TestDTO, Test>(test);

            db.Tests.Create(testToAdd);
            db.Save();
        }
Exemple #27
0
        public void CreateTest(TestDTO test)
        {
            TestResult newTestResult = map.Map <TestResult>(test);

            db.TestResults.Add(newTestResult);
            db.Save();
        }
Exemple #28
0
        public async Task <ApiResult <TestVO> > GetResultTest1(TestDTO dto)
        {
            //参数校验
            if (!dto.IsValid(out Exception ex))
            {
                throw ex;
            }

            var expression = dto.GetExpression();
            var orders     = dto.GetOrder();

            //var count = await _testRepository.CountAsync(expression);

            //var updateResult1 = await _testRepository.SetAsync(() => new { user_id = "eeeee" }, oo => oo.UserId == "4444");

            TestDO demoDO = new TestDO {
                UserId = dto?.UserId, UserName = this.CurrentUser?.UserName
            };

            //var updateResult3 = await _testRepository.SetAsync(demoDO);

            TestVO demoVO = this.ObjectMapper.Map <TestVO>(demoDO);
            var    result = ApiResultUtil.IsSuccess(demoVO);

            return(await Task.FromResult(result));
        }
Exemple #29
0
        public void DeleteScheduledTest(TestDTO test, CourseDTO course)
        {
            ScheduledEvent scheduledLection = db.ScheduledEvents.Find(x => x.Test.TestID == test.TestID && x.Course.CourseID == course.CourseID).FirstOrDefault();

            db.ScheduledEvents.Delete(scheduledLection.ScheduledEventID);
            db.Save();
        }
Exemple #30
0
        public void Create(TestDTO dto)
        {
            var model = this.mapper.MapTo <Test>(dto);

            this.tests.Add(model);
            this.saver.SaveChanges();
        }
        public async Task SimpleTest()
        {
            var item = new TestDTO();
            var config = new PersistentQueueConfiguration(_queueName);
            config.DataDirectory = Path.GetTempPath();

            var sut = new PersistentQueue<TestDTO>(config);
            await sut.EnqueueAsync(item);
            var actual = await sut.DequeueAsync();

            actual.Id.Should().Be(item.Id);
            actual.UserName.Should().Be(item.UserName);
        }
        public void ValicationErrorCodeShouldSetInvalidUserInputErrorCode()
        {
            const int invalidUserIntputErrorCode = 15;
            RestCore.Configuration = new Configuration { InvalidUserIntputErrorCode = invalidUserIntputErrorCode };
            var testDTO = new TestDTO { Name = "1234567890123456789012345678901234567890" };

            _controller = TestControllerBuilder.TestController().Build();

            _controller.Create(testDTO);

            _controller.Headers.Get(Constants.Headers.ErrorCode).ShouldEqual(invalidUserIntputErrorCode.ToString());
        }