Example #1
0
        public async Task <Response <int> > Handle(CreateQuestionCommand request, CancellationToken cancellationToken)
        {
            var question = _mapper.Map <Question>(request);
            await _questionRepo.AddAsync(question);

            return(new Response <int>(question.Id));
        }
Example #2
0
        public async Task <IActionResult> CreateQuestion(QuestionCreateDto question)
        {
            try
            {
                var existing = _repository.GetQuestionByNumberAsync(question.Number);

                if (existing != null)
                {
                    return(BadRequest("Question is use"));
                }

                var entity = question.MapCreateDtoToEntity();

                await _repository.AddAsync(entity);

                if (!(await _unitOfWork.SaveChangeAsync()))
                {
                    return(BadRequest());
                }

                return(CreatedAtRoute(nameof(GetQuestionByNumber),
                                      new { number = question.Number },
                                      entity.MapToReadModel()));
            }
            catch (Exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, "Database Failure"));
            }
        }
Example #3
0
        public ActionResult  Create(Question questionDto)
        {
            if (ModelState.IsValid)
            {
                var question = new Question
                {
                    Title              = questionDto.Title,
                    Description        = questionDto.Description,
                    QuestionCategoryId = questionDto.QuestionCategoryId,
                    QuestionTypeId     = 2,
                    Price              = 200,
                    Active             = true,
                    UserId             = 10,
                    CreatedOnUtc       = DateTime.Now,
                    IsPay              = true,
                    LastStatusId       = 2,
                    Score              = 22,
                    Immediate          = true,
                    ScoreConsultant    = 3
                };
                questionRepository.AddAsync(question, cancellationToken);
                return(RedirectToAction("Index"));
            }

            //ViewData["LastStatusId"] = new SelectList(_context.QuestionStatus, "Id", "Name", question.LastStatusId);
            //ViewData["QuestionCategoryId"] = new SelectList(questions, "Id", "Name", questions.Select(x=>x.Id));
            //ViewData["QuestionTypeId"] = new SelectList(_context.QuestionType, "Id", "Name", question.QuestionTypeId);
            //ViewData["SelectConsultantId"] = new SelectList(_context.Consultant, "Id", "Address", question.SelectConsultantId);
            //ViewData["UserId"] = new SelectList(_context.User, "Id", "FirstName", question.UserId);
            //return View(question);
            return(null);
        }
Example #4
0
        public async Task <IActionResult> Create([Bind("Title,Description,QuestionCategoryId")] Question questionDto)
        {
            if (ModelState.IsValid)
            {
                var question = new Question
                {
                    Title              = questionDto.Title,
                    Description        = questionDto.Description,
                    QuestionCategoryId = questionDto.QuestionCategoryId,
                    QuestionTypeId     = questionDto.QuestionTypeId,
                    Price              = questionDto.Price,
                    Active             = questionDto.Active,
                    UserId             = questionDto.UserId,
                    CreatedOnUtc       = questionDto.CreatedOnUtc,
                    IsPay              = questionDto.IsPay,
                    LastStatusId       = questionDto.LastStatusId,
                    Score              = questionDto.Score,
                    Immediate          = questionDto.Immediate,
                    ScoreConsultant    = questionDto.ScoreConsultant
                };
                await questionRepository.AddAsync(question, cancellationToken);

                return(RedirectToAction(nameof(Index)));
            }

            //ViewData["LastStatusId"] = new SelectList(_context.QuestionStatus, "Id", "Name", question.LastStatusId);
            //ViewData["QuestionCategoryId"] = new SelectList(questions, "Id", "Name", questions.Select(x=>x.Id));
            //ViewData["QuestionTypeId"] = new SelectList(_context.QuestionType, "Id", "Name", question.QuestionTypeId);
            //ViewData["SelectConsultantId"] = new SelectList(_context.Consultant, "Id", "Address", question.SelectConsultantId);
            //ViewData["UserId"] = new SelectList(_context.User, "Id", "FirstName", question.UserId);
            //return View(question);
            return(RedirectToAction(nameof(Index)));
        }
Example #5
0
        public async Task <ProcessResult> AddQuestionAsync(Question question)
        {
            if (!await IsTrackAvailableAsync(question.TrackId))
            {
                return(new ProcessResult {
                    Message = $"O Id de trilha {question.TrackId} não está disponível", Result = false
                });
            }
            else if (question.Answers.Count <= 1)
            {
                return(new ProcessResult {
                    Message = "A questão deve ter mais de uma alternativa possível.", Result = false
                });
            }
            else if (question.Answers.Count(q => q.IsAnswerCorrect) != 1)
            {
                return(new ProcessResult {
                    Message = "A questão deve ter apenas uma resposta correta.", Result = false
                });
            }

            await _questionRepository.AddAsync(question);

            await _unitOfWork.CommitAsync();

            return(new ProcessResult {
                Result = true, Message = "Pergunta adicionada com sucesso"
            });
        }
Example #6
0
        public async Task <ApiResult <Question> > Create(Question questionDto, CancellationToken cancellationToken)
        {
            //var exists = await userRepository.TableNoTracking.AnyAsync(p => p.UserName == questionDto.UserName);
            //if (exists)
            //    return BadRequest("نام کاربری تکراری است");

            var question = new Question
            {
                Title              = questionDto.Title,
                Description        = questionDto.Description,
                QuestionCategoryId = questionDto.QuestionCategoryId,
                QuestionTypeId     = questionDto.QuestionTypeId,
                Price              = questionDto.Price,
                Active             = questionDto.Active,
                UserId             = questionDto.UserId,
                CreatedOnUtc       = questionDto.CreatedOnUtc,
                IsPay              = questionDto.IsPay,
                LastStatusId       = questionDto.LastStatusId,
                Score              = questionDto.Score,
                Immediate          = questionDto.Immediate,
                ScoreConsultant    = questionDto.ScoreConsultant
            };
            await questionRepository.AddAsync(question, cancellationToken);

            return(question);
        }
Example #7
0
        public async Task AddQuestion(QuestionDto dto)
        {
            var question = _mapper.Map <Question>(dto);

            await _questionRepository.AddAsync(question);

            dto.Id = question.Id;
        }
Example #8
0
        public async Task <IActionResult> Add(QuestionDTO dto)
        {
            var entity = dto.MapTo <Question>();

            await _questionRepos.AddAsync(entity);

            return(Ok());
        }
        public async Task <IActionResult> Add([FromBody] QuestionModel questionModel)
        {
            if (!ModelState.IsValid || questionModel == null)
            {
                return(BadRequest());
            }

            var question      = questionModel.ToEntity();
            var savedQuestion = await _questionRepository.AddAsync(question);

            return(CreatedAtRoute("GetQuestion", new { id = savedQuestion.Id }, savedQuestion));
        }
Example #10
0
        public async Task <IResultModel> Add(QuestionAddModel model)
        {
            var entity = _mapper.Map <QuestionEntity>(model);
            //if (await _repository.Exists(entity))
            //{
            //return ResultModel.HasExists;
            //}

            var result = await _repository.AddAsync(entity);

            return(ResultModel.Result(result));
        }
Example #11
0
        public async Task <QuestionGetModel> AskQuestionAsync(QuestionCreateModel questionModel)
        {
            var tags = await _tagService.GetTagsAsync(questionModel.TagIds);

            var user = await _userRepository.GetByIdAsync(questionModel.UserId);

            var question = Question.Create(user, questionModel.Title, questionModel.Body, tags, _limits);
            await _questionRepository.AddAsync(question);

            await _uow.SaveAsync();

            return(_mapper.Map <QuestionGetModel>(question));
        }
Example #12
0
        public async Task <int> AddQuestionToSurveyAsync(int surveyId, int questionPosition, string content,
                                                         string select, bool isRequired)
        {
            var survey = await _surveyRepository.GetByIdAsync(surveyId);

            if (content == "")
            {
                content = "Brak pytania";
            }
            var question = new Question(questionPosition, content, select, isRequired);

            survey.AddQuestion(question);
            await _questionRepository.AddAsync(question);

            return(question.Id);
        }
Example #13
0
        public async Task <bool> AddQuestionAsync(Question question)
        {
            if (!await IsTrackAvailableAsync(question.TrackId))
            {
                throw new Exception($"This track id {question.TrackId} is not available");
            }
            else if (question.Answers.Count <= 1)
            {
                throw new Exception("A questão deve ter mais de uma alternativa possível.");
            }
            else if (question.Answers.Count(q => q.IsAnswerCorrect) != 1)
            {
                throw new Exception("A questão deve ter apenas uma resposta correta.");
            }

            await _questionRepository.AddAsync(question);

            await _unitOfWork.CommitAsync();

            return(true);
        }
Example #14
0
        public async Task ExecuteAsync(CreateQuestionCommand message, CancellationToken token)
        {
            var user = await _userRepository.LoadAsync(message.UserId, token);

            if (await _questionRepository.GetSimilarQuestionAsync(message.Text, token))
            {
                throw new DuplicateRowException();
            }

            var course = await _courseRepository.LoadAsync(message.Course, token);

            await _courseRepository.UpdateAsync(course, token);


            var question = new Question(
                message.Text,
                user, course, user.University);

            //await _userRepository.UpdateAsync(user, token);

            await _questionRepository.AddAsync(question, token);
        }
Example #15
0
        public async Task <bool> CreateQuestion(CreateQuestionDTO questionModel)
        {
            var question = _mapper.Map <Question>(questionModel);
            var choices  = _mapper.Map <Choice>(questionModel);

            question.Choices = choices;

            if (choices.Answers.Length > 1)
            {
                question.MultipleAnswers = true;
            }

            var result = await _questionRepository.AddAsync(question);

            if (result != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
 public async Task <Question> AddAsync(Question entity)
 {
     return(await repository.AddAsync(entity));
 }
Example #17
0
        public async Task InsertQuestionToDBAsync(string url, int chapterId)
        {
            var web = new HtmlWeb()
            {
                OverrideEncoding = Encoding.UTF8
            };
            var doc = web.Load(url);

            var strongNode = doc.DocumentNode.QuerySelectorAll("div.entry-content.article > h2 > strong").ToList();

            if (strongNode.Count() == 0)
            {
                strongNode = doc.DocumentNode.QuerySelectorAll("div.entry-content.article > p > strong").ToList();
            }

            var questionNodes = strongNode.GetListQuestionNodeFromStrongNode();

            var imgNodes    = doc.DocumentNode.QuerySelectorAll("div.entry-content.article > p > img").ToList();
            var answerNodes = new List <HtmlNode>();

            var answerNodesTable = doc.DocumentNode.QuerySelectorAll("div.entry-content.article > table");
            var answerNodesOL    = doc.DocumentNode.QuerySelectorAll("div.entry-content.article > ol");

            answerNodes.AddRange(answerNodesTable);
            answerNodes.AddRange(answerNodesOL);

            var pNodes             = doc.DocumentNode.QuerySelectorAll("div.entry-content.article > p").ToList();
            var correctAnswerNodes = pNodes.TakeCorrectAnswerNode();

            foreach (var(item, index) in questionNodes.WithIndex())
            {
                var splitedString = item.InnerText.Split(":");
                var id            = new string(splitedString[0].Where(Char.IsDigit).ToArray());

                if (splitedString.Count() > 1)
                {
                    if (string.IsNullOrEmpty(splitedString[1]))
                    {
                        Console.WriteLine("It's not a question");
                        Console.WriteLine("---------------------------------------");
                    }
                    else if (string.IsNullOrEmpty(id))
                    {
                        Console.WriteLine("It's not a question");
                        Console.WriteLine("---------------------------------------");
                    }
                    else
                    {
                        int questNum = Convert.ToInt32(id);

                        var image = new ImageVM();

                        if (imgNodes.Count() > 1 && imgNodes.Last().Attributes["src"].Value != "http://daotaolaixehcm.vn/wp-content/uploads/2020/04/onthilaixe-610x1024.jpg")
                        {
                            var imgNode = answerNodes[index].CheckTableNode() ? answerNodes[index].GetImageNodeFromTable() : imgNodes.SearchImageNodeByQuestionNumber(questNum);

                            if (imgNode != null)
                            {
                                image = imgNode.GenerateImageFromNode();
                            }
                        }

                        var question = new Question()
                        {
                            ChapterId     = chapterId,
                            Number        = questNum,
                            Content       = splitedString[1].Replace("&#8221;", "\"").Replace("&#8220;", "\""),
                            CorrectAnswer = correctAnswerNodes.Count() > 0 ? correctAnswerNodes[index].GetCorrectAnswerFromNode() : 0,
                            ImageTitle    = image.ImageTitle,
                            ImageData     = image.ImageData,
                        };

                        question.Answers = new List <Answer>(answerNodes[index].CheckTableNode() ? answerNodes[index].GetListAnswerFromTable() : answerNodes[index].GetListAnswerFromNode());

                        try
                        {
                            await _question.AddAsync(question);

                            Console.WriteLine($"Added question: Cau {question.Number}");
                            Console.WriteLine("---------------------------------------");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Failed to add question !");
                            Console.WriteLine("Error: " + ex.Message);
                            Console.WriteLine("-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-");
                        }
                    }
                }
            }
        }
Example #18
0
        public async Task <bool> CreateAsync(QuestionRequest questionRequest)
        {
            Question question = _mapper.Map <QuestionRequest, Question>(questionRequest);

            return(await _questionRepository.AddAsync(question));
        }