Exemple #1
0
        public async Task <ApiResult <CreateQuestionCommand> > GetQuestionOptionByIdAsync(GetQuestionOptionByIdQuery filter)
        {
            try
            {
                var questionqultion = await _unit.Context.Tblquestion.Include(t => t.Category).Include(t => t.Tblquestionoptions).Where(p => p.Id == filter.Filter.QuestionId && p.Status == 1).FirstOrDefaultAsync();

                var result = new CreateQuestionCommand
                {
                    Id         = questionqultion.Id,
                    Name       = questionqultion.Name,
                    NoOfOption = questionqultion.NoOfOptions.HasValue ? questionqultion.NoOfOptions.Value : Convert.ToInt16(0),
                    CategoryId = questionqultion.CategoryId.Value,
                    DurationId = questionqultion.QuestionDuration.Value,
                    Options    = questionqultion.Tblquestionoptions.Select(x => new CreateOptionCommand
                    {
                        Id        = x.Id,
                        Name      = x.Name,
                        IsMatched = x.IsMatched == 1 ? true : false
                    }).ToList()
                };
                return(new ApiResult <CreateQuestionCommand>(new ApiResultCode(ApiResultType.Success), result));
            }
            catch (Exception ex)
            {
                ErrorTrace.Logger(LogArea.RepositoryLayer, ex);
                return(new ApiResult <CreateQuestionCommand>(new ApiResultCode(ApiResultType.Error, messageText: "Error while geting data")));
            }
        }
Exemple #2
0
        public async Task <ActionResult> CreateQuestionAsync([FromBody] CreateQuestionRequest model, CancellationToken token)
        {
            var command = new CreateQuestionCommand(model.Course, model.University, model.Text, model.Country.ToString("G"));
            await _commandBus.Value.DispatchAsync(command, token);

            return(Ok());
        }
        public bool Handle(CreateQuestionCommand request)
        {
            var question = request.Adapt <Model.Question>();
            int id       = FindCountInDB(string.Format("select count(*) from Questions where Topics_topic_id = {0} and Topics_Courses_course_id = {1}",
                                                       question.TopicId.ToString(), question.CourseId.ToString())) + 1;

            try
            {
                using (MySqlConnection conn = _context.GetConnection())
                {
                    conn.Open();
                    string query = string.Format("insert into Questions(question_id, question, answer_1, is_answer_1_true, answer_2, is_answer_2_true, answer_3, is_answer_3_true, answer_4, is_answer_4_true, answer_5, is_answer_5_true, Topics_topic_id, Topics_Courses_course_id) " +
                                                 "values('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}')",
                                                 id, question.Description, question.Answer1, IsOneOrZero(question.IsAnswer1True),
                                                 question.Answer2, IsOneOrZero(question.IsAnswer2True), question.Answer3, IsOneOrZero(question.IsAnswer3True),
                                                 question.Answer4, IsOneOrZero(question.IsAnswer4True), question.Answer5, IsOneOrZero(question.IsAnswer5True), question.TopicId, question.CourseId);
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    cmd.ExecuteNonQuery();
                    conn.CloseAsync();
                }
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        public async Task <IActionResult> Create(CreateQuestionViewModel model)
        {
            try
            {
                CreateQuestionCommand command = new CreateQuestionCommand()
                {
                    Name        = model.Name,
                    Description = model.Description,
                    Email       = model.Email
                };
                var result = await QuestionService.CreateQuestionAsync(command);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Questions"));
                }
                else
                {
                    return(View());
                }
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, "Error while creating question");
                return(View());
            }
        }
        public async Task DeleteQuestion_ShouldReturnForbidden_WhenRequestNotFromAuthor()
        {
            // Arrange
            await AuthenticateTestUser("iAmTheAuthor" +
                                       nameof(DeleteQuestion_ShouldReturnForbidden_WhenRequestNotFromAuthor));

            var question = new CreateQuestionCommand
            {
                Title   = "Help me with my account protection!",
                Content = "Please..."
            };
            var serverResponse = await HttpClient.PostAsJsonAsync(Question, question);

            var createdQuestionResponse =
                await serverResponse.Content.ReadFromJsonAsync <CreateQuestionCommandResponse>();

            // Act
            await AuthenticateTestUser("iAmTheDataStealer" +
                                       nameof(DeleteQuestion_ShouldReturnForbidden_WhenRequestNotFromAuthor));

            serverResponse = await HttpClient.DeleteAsync($"{Question}/{createdQuestionResponse!.Id}");

            // Assert
            serverResponse.IsSuccessStatusCode.Should().BeFalse();
            serverResponse.StatusCode.Should().Be(HttpStatusCode.Forbidden);
        }
Exemple #6
0
        public async Task <ActionResult> CreateQuestion(int questionId, string title, string tags)
        {
            CreateQuestionCommand cmd = new CreateQuestionCommand();
            var questionWriteContext  = new QuestionWriteContext(new List <CreateQuestionCommand>()
            {
                new CreateQuestionCommand()
                {
                    QuestionId = 7
                },
                new CreateQuestionCommand()
                {
                    Title = "How to convert from Guid to string in C#?"
                },
                new CreateQuestionCommand()
                {
                    Tags = "C#"
                }
            });

            var expr = from questionResult in QuestionDomain.CreateQuestion(questionId, "123", "C#")
                       select questionResult;

            var result = await _interpreter.Interpret(expr, questionWriteContext, new object());

            return(result.Match(
                       created => Ok(created),
                       notCreated => BadRequest(notCreated),
                       invalidRequest => ValidationProblem()));
        }
        public async Task GetQuestion_ShouldReturnAuthorId_WhenQuestionExist()
        {
            // Arrange
            var userId = await AuthenticateTestUser(nameof(GetQuestion_ShouldReturnAuthorId_WhenQuestionExist));

            var question = new CreateQuestionCommand
            {
                Title   = "What is the difference between constants and read-only?",
                Content = "When would you use one over the other?"
            };
            var serverResponse = await HttpClient.PostAsJsonAsync(Question, question);

            var createQuestionResponseModel =
                await serverResponse.Content.ReadFromJsonAsync <CreateQuestionCommandResponse>();

            // Act
            serverResponse = await HttpClient.GetAsync($"{Question}/{createQuestionResponseModel!.Id}");

            var getQuestionResponseModel =
                await serverResponse.Content.ReadFromJsonAsync <GetQuestionQueryResponse>();

            // Assert
            getQuestionResponseModel.Should().NotBeNull();
            getQuestionResponseModel !.CreatedBy.Id.Should().Be(userId);
        }
Exemple #8
0
        public bool UpdateQuestion(int id, [FromBody] CreateQuestionCommand request)
        {
            QuestionContext       context = HttpContext.RequestServices.GetService(typeof(QuestionContext)) as QuestionContext;
            UpdateQuestionHandler handler = new UpdateQuestionHandler(context);

            return(handler.Handle(id, request));
        }
Exemple #9
0
        public async Task <ActionResult> Create([FromRoute] Guid challengeId, CreateQuestionCommand command)
        {
            if (challengeId != command.ChallengeId)
            {
                return(BadRequest());
            }

            return(Ok(await Mediator.Send(command)));
        }
        public async Task <IActionResult> Post([FromBody] CreateQuestionCommand createQuestionCommand)
        {
            using (var scope = _tracer.BuildSpan("CreateQuestion").StartActive(finishSpanOnDispose: true))
            {
                var response = await _mediator.Send(createQuestionCommand);

                //catch if failure
                return(Ok(response));
            }
        }
Exemple #11
0
        public async Task <ActionResult <int> > PostQuestion([FromRoute] int id, [FromBody] CreateQuestionCommand command)
        {
            if (id != command.TopicId)
            {
                return(BadRequestNonMatchingIds());
            }

            int result = await _Mediator.Send(command);

            return(Ok(new { result }));
        }
Exemple #12
0
        public async Task <int> InsertQuestionAsync(CreateQuestionCommand command)
        {
            try
            {
                var result = await client.PostAsync($"{baseUrl}/api/question/", RequestHelper.GetStringContentFromObject(command));

                return(Convert.ToInt32(result.Content.ReadAsStringAsync().Result));
            }
            catch (Exception e)
            {
                throw;
            }
        }
        public Question Create(CreateQuestionCommand command)
        {
            var service = new Question(command.TypeReply, command.TypeQuestion, command.StepQuestion, command.Enunciation, command.Education, command.Reply, command.PhaseQuestion, command.Group);

            service.Validate();
            _repository.Create(service);

            if (Commit())
            {
                return(service);
            }

            return(null);
        }
Exemple #14
0
        static void Main(string[] args)
        {
            var cmd    = new CreateQuestionCommand("How to add a reference to my project in VS2017?", "Issues", "VisualStudio2017", "Fixed Issues in VisualStudio 2017");
            var result = CreateQuestion(cmd);

            result.Match(
                ProcessQuestionPublished,
                ProcessQuestionNotPublished,
                ProcessInvalidQuestion
                );

            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }
Exemple #15
0
        public async Task ShouldGetModelForValidInformation()
        {
            var createQuestionCommand = new CreateQuestionCommand
            {
                TenantId   = _tenantId,
                CreatedBy  = _adminUserId,
                Text       = "Asagidakilerden hangisi asagidadir?",
                Duration   = 3,
                TagsIdList = null
            };

            var questionModel = await _createQuestionCommandHandler.Handle(createQuestionCommand, CancellationToken.None);

            Assert.Null(questionModel.Errors);
        }
Exemple #16
0
        public async Task CreateQuestion_ShouldReturnUnauthorized_WhenNotAuthenticated()
        {
            // Arrange
            var question = new CreateQuestionCommand
            {
                Title   = "Is there a difference between authentication and authorization?",
                Content = "I see these two terms bandied about quite a bit"
            };

            // Act
            var serverResponse = await HttpClient.PostAsJsonAsync(Question, question);

            // Assert
            serverResponse.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
        }
        public async Task Handle_GivenValidRequest_ShouldCreateQuestion()
        {
            // Arrange
            var command = new CreateQuestionCommand {
                UserId = Guid.NewGuid().ToString(), Text = "Question Text"
            };

            // Act
            var questionId = await _sut.Handle(command, CancellationToken.None);

            var result = await _context.Questions.FindAsync(questionId);

            // Assert
            Assert.NotNull(result);
        }
        public bool Handle(int questionId, CreateQuestionCommand request)
        {
            var model = request.Adapt <Model.Question>();

            using (MySqlConnection conn = _context.GetConnection())
            {
                conn.Open();

                string query = string.Format("update questions set question='{1}', Answer_1='{2}', Is_Answer_1_True={3}," +
                                             "Answer_2='{4}', Is_Answer_2_True={5}, Answer_3='{6}', Is_Answer_3_True={7}," +
                                             "Answer_4='{8}', Is_Answer_4_True={9}, Answer_5='{10}', Is_Answer_5_True={11}," +
                                             "topics_topic_id={12}, topics_courses_course_id={13} where question_id={0}",
                                             questionId.ToString(),
                                             model.Description,
                                             model.Answer1,
                                             IsOneOrZero(model.IsAnswer1True),
                                             model.Answer2,
                                             IsOneOrZero(model.IsAnswer2True),
                                             model.Answer3,
                                             IsOneOrZero(model.IsAnswer3True),
                                             model.Answer4,
                                             IsOneOrZero(model.IsAnswer4True),
                                             model.Answer5,
                                             IsOneOrZero(model.IsAnswer5True),
                                             model.TopicId,
                                             model.CourseId);



                MySqlCommand cmd = new MySqlCommand(query, conn);

                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    string s = ex.Message;
                    return(false);
                }
                finally
                {
                    conn.CloseAsync();
                }
            }

            return(true);
        }
        public async Task <ActionResult> CreateQuestion([FromBody] CreateQuestionCommand cmd)
        {
            var posts = _dbContext.Post.ToList();
            QuestionWriteContext questionWriteContext = new QuestionWriteContext(
                new EFList <Post>(_dbContext.Post));

            var expr = from questionResult in QuestionDomain.CreateQuestion(cmd.QuestionId, cmd.Title, cmd.Tags)
                       select questionResult;

            var result = await _interpreter.Interpret(expr, questionWriteContext, new object());

            return(result.Match(
                       created => Ok(created),
                       notCreated => BadRequest(notCreated),
                       invalidRequest => ValidationProblem()));
        }
Exemple #20
0
        public async Task <ActionResult <int> > Post([FromBody] CreateQuestionCommand command)
        {
            var entity = new Question
            {
                Content     = command.Content,
                Question_No = command.Question_No,
                Row_No      = command.Row_No,
                QuizId      = command.QuizId,
            };

            _context.Question.Add(entity);

            await _context.SaveChangesAsync();

            return(Ok(entity.Id));
        }
Exemple #21
0
        public async Task CreateQuestion_ShouldReturnBadRequest_WhenBodyIsEmpty(string title, string content)
        {
            // Arrange
            await AuthenticateTestUser($"{nameof(CreateQuestion_ShouldReturnBadRequest_WhenBodyIsEmpty)}-{title}-{content}");

            var question = new CreateQuestionCommand
            {
                Title   = string.Empty,
                Content = string.Empty
            };

            // Act
            var serverResponse = await HttpClient.PostAsJsonAsync(Question, question);

            // Assert
            serverResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
        public async Task <ActionResult> CreateQuestion([FromBody] CreateQuestionCommand cmd)
        {
            var posts = _dbContext.Post.ToList();
            QuestionWriteContext questionWriteContext = new QuestionWriteContext(
                new EFList <Post>(_dbContext.Post));

            var expr = from questionResult in QuestionDomain.CreateQuestion(cmd.QuestionId, cmd.Title, cmd.Tags)
                       select questionResult;

            var result = await _interpreter.Interpret(expr, questionWriteContext, new object());

            _dbContext.SaveChanges();

            return(result.Match(
                       created => Ok(created),
                       notCreated => StatusCode(StatusCodes.Status500InternalServerError, "Tenant could not be created."),
                       invalidRequest => BadRequest("Invalid request.")));
        }
Exemple #23
0
        static void Main(string[] args)
        {
            List <string> tags = new List <string>()
            {
                "C#",
                "VS2019"
            };

            var user       = new CreateUserCommand("alexandra", "lacau", "*****@*****.**");
            var userResult = CreateUser(user);

            var question       = new CreateQuestionCommand("Add reference to a project", "Issue", tags, "How to add reference to a C# project in Visual Studio 2019?");
            var questionResult = CreateQuestion(question, (UserCreated)userResult);

            ((QuestionPublished)questionResult).VoteQuestion((UserCreated)userResult, true);
            ((QuestionPublished)questionResult).VoteQuestion((UserCreated)userResult, false);
            Console.WriteLine("The total number of votes for the question is:" + ((QuestionPublished)questionResult).Votes.ToString());
        }
        private CommandResponse ExecuteCreateQuestion(CreateQuestionCommand command)
        {
            var question = new Question
            {
                Id        = Guid.NewGuid(),
                Author    = command.IssuedBy,
                Tags      = command.Tags?.ToList() ?? new List <Tag>(),
                Text      = command.Text,
                Title     = command.Title,
                Votes     = new List <Vote>(),
                Timestamp = DateTime.Now,
                Comments  = new List <Comment>(),
                Answers   = new List <Answer>()
            };

            Questions.Add(question);
            return(CommandResponse.Success(question));
        }
        public async Task Handler_ValidQuestionData_ShouldSuccess()
        {
            //Arrange
            _quizRepositoryMock.Setup(x => x.AnyAsync(It.IsAny <ISpecification <Quiz> >()))
            .ReturnsAsync(true);
            _questionRepositoryMock.Setup(x => x.SaveAsync(It.IsAny <Question>()))
            .Callback <Question>(x => x.Id = Guid.NewGuid())
            .ReturnsAsync(true);

            var createQuestionCommand = new CreateQuestionCommand()
            {
                QuizId        = Guid.NewGuid(),
                Title         = "anonymousText",
                CorrectAnswer = "anonymousText",
                Options       = new List <Option>()
                {
                    new Option()
                    {
                        Value = "anonymousOption1"
                    },
                    new Option()
                    {
                        Value = "anonymousOption2"
                    },
                    new Option()
                    {
                        Value = "anonymousOption3"
                    },
                    new Option()
                    {
                        Value = "anonymousOption4"
                    },
                }
            };

            //Act
            var result = await _questionCommandHandler.Handle(createQuestionCommand, CancellationToken.None);

            //Assert
            Assert.NotEqual(Guid.Empty, result);
        }
Exemple #26
0
        public async Task CreateQuestion_ShouldReturnQuestionId_WhenDataValid()
        {
            // Arrange
            await AuthenticateTestUser(nameof(CreateQuestion_ShouldReturnQuestionId_WhenDataValid));

            var question = new CreateQuestionCommand
            {
                Title   = "What is the difference between a reference type and value type in C#?",
                Content = "Can you explain it to me in a professional way?"
            };

            // Act
            var serverResponse = await HttpClient.PostAsJsonAsync(Question, question);

            var createQuestionResponseModel =
                await serverResponse.Content.ReadFromJsonAsync <CreateQuestionCommandResponse>();

            // Assert
            createQuestionResponseModel.Should().NotBeNull();
            createQuestionResponseModel !.Id.Should().BeGreaterThan(0);
        }
Exemple #27
0
        public static ICreateQuestionResult CreateQuestion(CreateQuestionCommand createQuestionCommand)
        {
            if (string.IsNullOrWhiteSpace(createQuestionCommand.Category) || string.IsNullOrWhiteSpace(createQuestionCommand.Title))
            {
                var errors = new List <string>()
                {
                    "Invalid category or title!"
                };
                return(new QuestionValidationFailed(errors));
            }

            if (new Random().Next(7) > 1)
            {
                return(new QuestionNotPublished("Category or title could not be verified"));
            }

            var questionId = Guid.NewGuid();
            var result     = new QuestionPublished(questionId, createQuestionCommand.Category, createQuestionCommand.Title);

            return(result);
        }
        public async Task Handle_ValidQuestionData_SaveShouldFailed()
        {
            //Arrange
            _quizRepositoryMock.Setup(x => x.AnyAsync(It.IsAny <ISpecification <Quiz> >()))
            .ReturnsAsync(true);
            _questionRepositoryMock.Setup(x => x.SaveAsync(It.IsAny <Question>()))
            .ReturnsAsync(false);

            var createQuestionCommand = new CreateQuestionCommand()
            {
                QuizId        = Guid.NewGuid(),
                Title         = "anonymousText",
                CorrectAnswer = "anonymousText",
                Options       = new List <Option>()
                {
                    new Option()
                    {
                        Value = "anonymousOption1"
                    },
                    new Option()
                    {
                        Value = "anonymousOption2"
                    },
                    new Option()
                    {
                        Value = "anonymousOption3"
                    },
                    new Option()
                    {
                        Value = "anonymousOption4"
                    },
                }
            };

            //Act
            //Assert
            await Assert.ThrowsAsync <InvalidOperationException>(() => _questionCommandHandler.Handle(createQuestionCommand, CancellationToken.None));

            _autoMocker.VerifyAll();
        }
Exemple #29
0
        public async Task <IActionResult> CreateQuestionAsync([FromBody] CreateQuestionDTO createQuestionDTO)
        {
            try
            {
                var command = new CreateQuestionCommand
                {
                    Description = createQuestionDTO.Description,
                    Email       = createQuestionDTO.Email,
                    Name        = createQuestionDTO.Name
                };

                var createQuestionResult = await QuestionService.CreateQuestionAsync(command);

                var result = Mapper.Map <CreateQuestionResult, CreateQuestionResultDTO> (createQuestionResult);

                return(Ok(result));
            }
            catch (Exception exception)
            {
                return(Exception(exception, "Failed to create question"));
            }
        }
Exemple #30
0
        public static ICreateQuestionResult CreateQuestion(CreateQuestionCommand receivedQuestion, UserCreated fromUser)
        {
            List <string> errors = new List <string>();

            if (string.IsNullOrWhiteSpace(receivedQuestion.Title) || string.IsNullOrWhiteSpace(receivedQuestion.Question))
            {
                errors.Add("Empty title");
                errors.Add("Empty question");
            }

            if (receivedQuestion.Tags.Count() < 1 || receivedQuestion.Tags.Count() > 3)
            {
                errors.Add("Incorrect number of tags");
            }

            if (errors.Count() > 0)
            {
                return(new QuestionValidationFailed(errors.AsEnumerable()));
            }

            return(new QuestionPublished(receivedQuestion, Guid.NewGuid(), fromUser));
        }