Esempio n. 1
0
        public void InvokeMapperMethodMapTo_WhenParametersAreCorrect()
        {
            //Arrange
            var mapperMock     = new Mock <IMappingProvider>();
            var saverMock      = new Mock <ISaver>();
            var answerRepoMock = new Mock <IRepository <Answer> >();

            var answerService = new AnswersService(saverMock.Object, mapperMock.Object, answerRepoMock.Object);

            var data = new List <Answer>()
            {
                new Answer {
                    Id = 1, Content = "AlaBala", QuestionId = 1
                }
            };

            answerRepoMock.Setup(a => a.All).Returns(data.AsQueryable());
            var mapperData = new AnswerDto()
            {
                Id = 1, Content = "AlaBala", QuestionId = 1
            };

            mapperMock.Setup(m => m.MapTo <AnswerDto>(It.IsAny <Answer>())).Returns(mapperData);

            //Act
            var dto = answerService.GetById(1);

            //Assert
            mapperMock.Verify(x => x.MapTo <AnswerDto>(It.IsAny <Answer>()), Times.Once);
        }
Esempio n. 2
0
        public async Task UpdateAnswerAsync(AnswerDto answerDto)
        {
            var answerEntity = AnswerMapper.Map(answerDto);

            _unitOfWork.AnswerRepository.Update(answerEntity);
            await _unitOfWork.CommitAsync();
        }
        public Answer Create(AnswerDto answerDto)
        {
            var newAnswer = new Answer()
            {
                AuthorId     = Guid.NewGuid(),
                AnswerString = answerDto.AnswerString,
                EntityId     = Guid.NewGuid(),
                QuestionId   = answerDto.QuestionId,
            };

            _repository.Insert(newAnswer);
            _repository.Save();

            var questionEntityId = this._repository.GetLastByFilter <Question>(x => x.Id == newAnswer.QuestionId).EntityId;

            var question = this._questionLogic.GetById(questionEntityId);

            var body         = "For the question: '" + question.QuestionString + "' this answer was added: '" + newAnswer.AnswerString + "'.";
            var notification = new Notification
            {
                Subject  = "A new answer was added",
                Body     = body,
                Receiver = "*****@*****.**"
            };

            _questionNotification.SendEmail(notification);

            return(newAnswer);
        }
Esempio n. 4
0
        public void ReturnAnswerDto_WhenParametersAreCorrect()
        {
            //Arrange
            var mapperMock     = new Mock <IMappingProvider>();
            var saverMock      = new Mock <ISaver>();
            var answerRepoMock = new Mock <IRepository <Answer> >();

            var answerService = new AnswersService(saverMock.Object, mapperMock.Object, answerRepoMock.Object);

            var data = new List <Answer>()
            {
                new Answer {
                    Id = 1, Content = "AlaBala", QuestionId = 1
                }
            };

            answerRepoMock.Setup(a => a.All).Returns(data.AsQueryable());
            var mapperData = new AnswerDto()
            {
                Id = 1, Content = "AlaBala", QuestionId = 1
            };

            mapperMock.Setup(m => m.MapTo <AnswerDto>(It.IsAny <Answer>())).Returns(mapperData);

            //Act
            var dto = answerService.GetById(1);

            //Assert
            Assert.IsNotNull(dto);
            Assert.IsInstanceOfType(dto, typeof(AnswerDto));
        }
        public AnswerFeedbackDto Post(int id, [FromBody] AnswerDto answer)
        {
            var result = new AnswerFeedbackDto();
            var quiz   = Quiz.Missions[id - 1];

            var question = quiz.Questions.FirstOrDefault(q => q.Id == answer.QuestionId);

            if (question != null)
            {
                if (string.Equals(answer.Text.Trim(), question.CorrectAnswer, StringComparison.OrdinalIgnoreCase))
                {
                    _repository.AddAchievement(answer.TeamName, answer.QuestionId);

                    result.IsCorrect = true;
                }
                else
                {
                    var hint = question.Hints.FirstOrDefault(
                        h => string.Equals(answer.Text.Trim(), h.GivenAnswer, StringComparison.OrdinalIgnoreCase));

                    if (hint != null)
                    {
                        result.Hint = hint.Text;
                    }
                }
            }

            return(result);
        }
Esempio n. 6
0
        protected virtual async Task Create(AnswerDto input)
        {
            Answer answerDto = MappingProfile.MappingConfigurationSetups().Map <Answer>(input);

            _context.Answer.Add(answerDto);
            await _context.SaveChangesAsync();
        }
        public void LinkingHelperTests_Nulls_ReturnsNull()
        {
            var answerDto = new AnswerDto()
            {
                LeftWord  = "a",
                RightWord = "b",
                Phrase    = "c"
            };

            var result = LinkingHelper.ParseUrlToAnswer(null);

            Assert.Null(result);

            result = LinkingHelper.ParseUrlToAnswer("    ");
            Assert.Null(result);

            result = LinkingHelper.ParseUrlToAnswer("random");
            Assert.Null(result);

            result = LinkingHelper.ParseUrlToAnswer(null, null);
            Assert.Null(result);

            result = LinkingHelper.ParseUrlToAnswer(null, "    ");
            Assert.Null(result);

            var commonStrings = new CommonStringsDto()
            {
                Best = "x", For = "y", Is = "z"
            };

            result = LinkingHelper.ParseUrlToAnswer(commonStrings, "random");
            Assert.Null(result);
        }
        public void LinkingHelperTests_ParseUrlToAnswer_Parses()
        {
            var answerDto = new AnswerDto()
            {
                LeftWord  = "a",
                RightWord = "b",
                Phrase    = "c"
            };

            var url = "/best-a-for-b-is-c";

            var result = LinkingHelper.ParseUrlToAnswer(url);

            Assert.Equal(result.LeftWord, answerDto.LeftWord);
            Assert.Equal(result.RightWord, answerDto.RightWord);
            Assert.Equal(result.Phrase, answerDto.Phrase);

            var commonStrings = new CommonStringsDto()
            {
                Best = "x", For = "y", Is = "z"
            };

            url = "/x-a-y-b-z-c";

            result = result = LinkingHelper.ParseUrlToAnswer(commonStrings, url);
            Assert.Equal(result.LeftWord, answerDto.LeftWord);
            Assert.Equal(result.RightWord, answerDto.RightWord);
            Assert.Equal(result.Phrase, answerDto.Phrase);
        }
        public void LinkingHelperTests_ConvertAnswerToUrl_Converts()
        {
            var answerDto = new AnswerDto()
            {
                LeftWord  = "a",
                RightWord = "b",
                Phrase    = "c"
            };

            var result = LinkingHelper.ConvertAnswerToUrl(answerDto);

            Assert.Equal(result, "/best-a-for-b-is-c");

            result = LinkingHelper.ConvertAnswerToText(answerDto);

            Assert.Equal(result, "Best a for b is c");

            var commonStrings = new CommonStringsDto()
            {
                Best = "x", For = "y", Is = "z"
            };

            result = LinkingHelper.ConvertAnswerToText(commonStrings, answerDto);
            Assert.Equal(result, "x a y b z c");

            result = LinkingHelper.ConvertAnswerToUrl(commonStrings, answerDto);
            Assert.Equal(result, "/x-a-y-b-z-c");

            result = LinkingHelper.ConvertAnswerToUrlWithCulture("f", commonStrings, answerDto);
            Assert.Equal(result, "/f/x-a-y-b-z-c");
        }
        public IHttpActionResult Get(int id)
        {
            var       answear = AnswerService.GetAnswer(id);
            AnswerDto ans     = answear.ToAnswerDto();

            return(Ok(new { Answer = ans }));
        }
Esempio n. 11
0
        public async Task <IActionResult> CreateQuiz(QuizViewModel model)
        {
            if (ModelState.IsValid)
            {
                var questionDtos = new List <QuestionDto>();

                foreach (QuestionViewModel questionViewModel in model.QuestionViewModels)
                {
                    AnswerDto answer = questionViewModel.Question.AnswerDtos[questionViewModel.CorrectAnswerIndex];
                    answer.IsCorrectAnswer = true;

                    questionDtos.Add(questionViewModel.Question);
                }

                var loggedInUser = await _userManager.FindByNameAsync(User.Identity.Name);

                await _questionService.SaveQuizAsync(questionDtos, model.Title, model.Content, loggedInUser.Id);

                TempData["SUCCESS"] = "Sınav başarıyla oluşturuldu!";
                return(RedirectToAction("List"));
            }

            PrepareViewData();
            return(View(model));
        }
        public IActionResult PushAnswer([FromRoute] int questionId, [FromBody] AnswerDto answerDto)
        {
            if (!ModelState.IsValid)
            {
                _logger.LogDebug(string.Join(Environment.NewLine, ModelState.Select(m => $"{m.Key}-{m.Value.Errors}")));
                return(BadRequest(ModelState));
            }
            var answer = new Answer
            {
                QuestionId     = questionId,
                AnswerOptionId = answerDto.AnswerId.Value,
                DepartmentId   = answerDto.Department,
                UserId         = answerDto.UserId
            };

            try
            {
                _repository.PushAnswer(answer);
                return(Ok());
            }
            catch (ArgumentException ex)
            {
                _logger.LogError(ex.ToString());
                return(BadRequest(ex.Message));
            }
        }
Esempio n. 13
0
        public async Task CreateAnswerAsync(AnswerDto answerDto)
        {
            var answer = AnswerMapper.ToEntity(answerDto);

            answer.AnswerId = Guid.Empty;
            await _answerRepo.CreateAnswerAsync(answer);
        }
Esempio n. 14
0
            public void ConvertsToBoardCorrectly()
            {
                string    prompt          = "prompt";
                string    correctResponse = "correctResponse";
                AnswerDto answerDto       = new AnswerDto()
                {
                    Prompt          = prompt,
                    CorrectResponse = correctResponse
                };
                List <AnswerDto> answerDtos = new List <AnswerDto>()
                {
                    answerDto
                };
                string   topicName = "topicName";
                TopicDto topicDto  = new TopicDto()
                {
                    Answers = answerDtos,
                    Name    = topicName
                };
                List <TopicDto> topicDtos = new List <TopicDto>()
                {
                    topicDto
                };
                string   boardName = "boardName";
                BoardDto boardDto  = new BoardDto
                {
                    Name   = boardName,
                    Topics = topicDtos
                };

                var board = boardDto.ToBoard();

                Assert.True(board.Name == boardName, "Board.Name was not copied correctly.");
                Assert.True(board.Topics.Count() == topicDtos.Count(), "Board.Topics was not copied correctly");
            }
Esempio n. 15
0
        public IHttpActionResult Create(AnswerDto answerDto)
        {
            if (string.IsNullOrWhiteSpace(answerDto.AnswerText))
            {
                return(BadRequest());
            }

            var currentAnswer = new Answer()
            {
                AnswerText = answerDto.AnswerText,
                DateTime   = DateTime.Now,
                QuestionId = answerDto.QuestionId,
                UserId     = User.Identity.GetUserId()
            };

            _unitOfWork.Answers.Add(currentAnswer);

            var notification = new Notification()
            {
                Answer           = currentAnswer,
                NotificationType = NotificationType.Answer
            };

            var whoAsked = _unitOfWork.Questions
                           .GetQuestionByQuestionId(answerDto.QuestionId)
                           .WhoAsked;

            whoAsked.Notify(notification);

            _unitOfWork.Complete();
            return(Ok());
        }
Esempio n. 16
0
        public async Task <ActionResult> PlayBinaryMode([FromForm] string answer)
        {
            var user = await GetUser();

            var answerDto = new AnswerDto
            {
                QuoteId           = (int)HttpContext.Session.GetInt32(QuoteId),
                AuthorName        = HttpContext.Session.GetString(AuthorName),
                CorrectAuthorName = HttpContext.Session.GetString(CorrectAuthorName),
                IsAnswerTrue      = answer == "Yes"
            };

            var result          = gameService.SaveAnswer(user, answerDto, true);
            var resultViewModel = new ResultViewModel
            {
                IsAnswerTrue = result.IsAnswerTrue
            };

            if (result.IsAnswerTrue)
            {
                resultViewModel.AuthorName = answerDto.CorrectAuthorName;
                return(this.View(resultViewModel));
            }

            resultViewModel.AuthorName = result.AuthorName;
            return(View(resultViewModel));
        }
Esempio n. 17
0
        public void EditAnswer(AnswerDto test)
        {
            var newAnswer = _mapper.Map <AnswerDto, Answer>(test);

            _database.Answers.Update(newAnswer);
            _database.Save();
        }
Esempio n. 18
0
        public async Task <long> CreateAsync(AnswerDto comment, CancellationToken cancellation = default)
        {
            var entity = Mapper.Map <AnswerDto, Answer>(comment);
            var result = await _answerRepository.CreateAsync(entity, cancellation);

            return(result.Id);
        }
Esempio n. 19
0
        public void MapAnswerToEntity()
        {
            //Arrange
            var userDto = new UserDto {
                UserId   = Guid.NewGuid(),
                UserName = "******"
            };
            var questionDto = new QuestionDto {
                QuestionId = Guid.NewGuid(),
            };

            var answerDto = new AnswerDto
            {
                AnswerId     = Guid.NewGuid(),
                AnswerText   = "Answer text",
                CreatedDate  = DateTime.Today,
                ModifiedDate = DateTime.Today,
                QuestionId   = Guid.NewGuid(),
                UserId       = Guid.NewGuid(),
            };

            //Act
            var answer = AnswerMapper.ToEntity(answerDto);

            //Assert
            Assert.Equal(answerDto.AnswerId, answer.AnswerId);
            Assert.Equal(answerDto.AnswerText, answer.AnswerText);
            Assert.Equal(answerDto.CreatedDate, answer.CreatedDate);
            Assert.Equal(answerDto.ModifiedDate, answer.ModifiedDate);
            Assert.Equal(answerDto.QuestionId, answer.QuestionId);
            Assert.Equal(answerDto.UserId, answer.UserId);
        }
Esempio n. 20
0
        public async Task <IActionResult> Answer(string uuid, [FromBody] AnswerDto dto, CancellationToken ct)
        {
            try
            {
                var question = await _context.Questions
                               .SingleOrDefaultAsync(q => q.Uuid == uuid, ct);

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

                var answer = new Answer
                {
                    QuestionId   = question.Id,
                    QuestionUuid = uuid,
                    User         = dto.User,
                    Text         = dto.Text,
                    Time         = dto.Time
                };

                _context.Answers.Add(answer);
                await _context.SaveChangesAsync(ct);
            }
            catch (Exception ex)
            {
                _logger.LogError(EventIds.DatabaseError, ex, ex.Message);
                throw;
            }

            return(Accepted());
        }
Esempio n. 21
0
            public void ConvertsToTopicProperly()
            {
                string    prompt          = "prompt";
                string    correctResponse = "correctResponse";
                AnswerDto answerDto       = new AnswerDto()
                {
                    Prompt          = prompt,
                    CorrectResponse = correctResponse
                };
                List <AnswerDto> answerDtos = new List <AnswerDto>()
                {
                    answerDto
                };
                string   topicName = "topicName";
                TopicDto topicDto  = new TopicDto()
                {
                    Answers = answerDtos,
                    Name    = topicName
                };

                var topic = topicDto.ToTopic();

                Assert.True(topic.Answers.Count() == answerDtos.Count(), "Topic.Answers were not copied correctly.");
                Assert.True(topic.Name == topicName, "Topic.Name was not copied correctly.");
            }
Esempio n. 22
0
        // 清单导入
        public List <AnswerDto> AnswerImport(string ossPath)
        {
            // 从OSS下载文件
            string downLoadFilePath = basePath + @"Content\Excel\ExcelImport\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx";

            OSSClientHelper.GetObject(ossPath, downLoadFilePath);
            Workbook         book  = Workbook.Load(downLoadFilePath, false);
            Worksheet        sheet = book.Worksheets[0];
            List <AnswerDto> list  = new List <AnswerDto>();

            for (int i = 0; i < 100000; i++)
            {
                string shopCode = sheet.GetCell("A" + (i + 2)).Value == null ? "" : sheet.GetCell("A" + (i + 2)).Value.ToString().Trim();
                if (string.IsNullOrEmpty(shopCode))
                {
                    break;
                }
                AnswerDto answer = new AnswerDto();
                answer.ShopCode      = shopCode;
                answer.ShopName      = sheet.GetCell("B" + (i + 2)).Value == null ? "" : sheet.GetCell("B" + (i + 2)).Value.ToString().Trim();
                answer.CheckCode     = sheet.GetCell("C" + (i + 2)).Value == null ? "" : sheet.GetCell("C" + (i + 2)).Value.ToString().Trim();
                answer.CheckTypeName = sheet.GetCell("D" + (i + 2)).Value == null ? "" : sheet.GetCell("D" + (i + 2)).Value.ToString().Trim();
                answer.Column1       = sheet.GetCell("E" + (i + 2)).Value == null ? "" : sheet.GetCell("E" + (i + 2)).Value.ToString().Trim();
                answer.Column2       = sheet.GetCell("F" + (i + 2)).Value == null ? "" : sheet.GetCell("F" + (i + 2)).Value.ToString().Trim();
                answer.Column3       = sheet.GetCell("G" + (i + 2)).Value == null ? "" : sheet.GetCell("G" + (i + 2)).Value.ToString().Trim();
                answer.Column4       = sheet.GetCell("H" + (i + 2)).Value == null ? "" : sheet.GetCell("H" + (i + 2)).Value.ToString().Trim();
                answer.Column5       = sheet.GetCell("I" + (i + 2)).Value == null ? "" : sheet.GetCell("I" + (i + 2)).Value.ToString().Trim();
                answer.Column6       = sheet.GetCell("J" + (i + 2)).Value == null ? "" : sheet.GetCell("J" + (i + 2)).Value.ToString().Trim();
                answer.Column7       = sheet.GetCell("K" + (i + 2)).Value == null ? "" : sheet.GetCell("K" + (i + 2)).Value.ToString().Trim();
                answer.Column8       = sheet.GetCell("L" + (i + 2)).Value == null ? "" : sheet.GetCell("L" + (i + 2)).Value.ToString().Trim();
                answer.Column9       = sheet.GetCell("M" + (i + 2)).Value == null ? "" : sheet.GetCell("M" + (i + 2)).Value.ToString().Trim();
                list.Add(answer);
            }
            return(list);
        }
        public async Task <AnswerDto> GetAnswerByIdAsync(Guid id)
        {
            AnswerDto answer = AnswerConverter.Convert(await _answerRepo.GetByIdAsync(id));

            answer.QuestionName = _questionRepo.GetByIdAsync(answer.QuestionId).Result.Text;
            return(answer);
        }
Esempio n. 24
0
        public ActionResult AddAnswerToQuestion(int id, AnswerDto answerDto)
        {
            if (answerDto == null)
            {
                return(BadRequest());
            }

            var questionInDb = _context.Questions.SingleOrDefault(q => q.Id == id);

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

            var questionAnswer = new QuestionAnswer
            {
                Question = questionInDb,
                Answer   = _mapper.Map <Answer>(answerDto)
            };

            _context.QuestionAnswer.Add(questionAnswer);
            _context.SaveChanges();

            var displayUrl = (Request != null) ? Request.GetDisplayUrl() : "http://localhost/question" + id;

            return(Created(new Uri(displayUrl + "/" + questionAnswer.Id), questionAnswer));
        }
Esempio n. 25
0
        public async Task <AnswerDto> CreateAnswerAsync(AnswerDto answer)
        {
            var dbAnswer      = AnswerMapper.ToDb(answer);
            var createdAnswer = await _answerRepo.CreateAnswerAsync(dbAnswer);

            return(AnswerMapper.ToDto(createdAnswer));
        }
Esempio n. 26
0
        /// <summary>
        /// Try to parse answer from the url
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static AnswerDto ParseUrlToAnswer(string url)
        {
            const int GROUP_LEFT_WORD   = 1;
            const int GROUP_RIGHT_WORD  = 2;
            const int GROUP_PHRASE_WORD = 3;

            // const int NUMBER_GROUPS = 4;
            if (string.IsNullOrEmpty(url))
            {
                return(null);
            }
            if (string.IsNullOrWhiteSpace(url))
            {
                return(null);
            }

            var matches = Regex.Matches(url.Replace("-", " "), "^/best\\s+(.*)\\s+for\\s+(.*)\\s+is\\s+(.*)");

            // Good check but we will never run into this
            // if (matches == null) return null; // Should not be null. Could be count zero but not null.
            if (matches.Count == 0)
            {
                return(null);
            }
            // Good check but we will never run into this
            //if (matches[0].Groups.Count != NUMBER_GROUPS) return null;
            var answer = new AnswerDto()
            {
                LeftWord  = matches[0].Groups[GROUP_LEFT_WORD].Value,
                RightWord = matches[0].Groups[GROUP_RIGHT_WORD].Value,
                Phrase    = matches[0].Groups[GROUP_PHRASE_WORD].Value
            };

            return(answer);
        }
Esempio n. 27
0
        public AnswerDto AddAnswer(AnswerDto answerDto)
        {
            var questionId  = _vacancyQuestionService.GetVacancyQuestionById(answerDto.VacancyQuestionId).QuestionId;
            var questionDto = _questionService.GetQuestionById(questionId);

            answerDto.Estimation *= questionDto.Complexity;
            return(_mapper.Map <Answer, AnswerDto>(_answerRepository.AddAnswer(_mapper.Map <AnswerDto, Answer>(answerDto))));
        }
Esempio n. 28
0
        public void AddAnswer(AnswerDto answer)
        {
            var addAnswer = _mapper.Map <AnswerDto, Answer>(answer);

            addAnswer.Question = _database.Questions.Get(answer.AnswerId);
            _database.Answers.Create(addAnswer);
            _database.Save();
        }
Esempio n. 29
0
 //Map object from answerdto to answermodel
 public Answer AMapToModel(AnswerDto AServiceObj)
 {
     return(new Answer
     {
         Answerlist = AServiceObj.Answerlist,
         QuestionId = AServiceObj.QuestionId,
     });
 }
Esempio n. 30
0
        public async Task <AnswerDto> Insert(AnswerDto request)
        {
            var entity = AutoMapper.Mapper.Map <Answer>(request);

            var result = await entityRepository.InsertAsync(entity);

            return(AutoMapper.Mapper.Map <AnswerDto>(result));
        }