public IHttpActionResult UpdateQuestion(int id, [FromBody] CreateQuestion question) { if (question == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var questionToUpdate = QuestionRepository.GetQuestionById(id); if (questionToUpdate == null) { return(NotFound()); } questionToUpdate.Title = question.Title; questionToUpdate.Status = question.Status; QuestionRepository.UpdateQuestion(questionToUpdate); return(StatusCode(HttpStatusCode.NoContent)); }
public async Task Check_If_Query_Was_Added() { await LogInAsAdministrator(); var createQuestion = new CreateQuestion( questionText: "Some question?", answers: new[] { "First answer", "Second answer" }); var createQuestionResponse = await Mediator.Send(createQuestion); var getQuestions = new GetQuestions(); var questionsResponse = await Mediator.Send(getQuestions); var addedQuestionId = AssertNotError.Of(createQuestionResponse); var allQuestions = AssertNotError.Of(questionsResponse); var questionThatWasAdded = allQuestions.Questions.SingleOrDefault(q => q.Id == addedQuestionId); Assert.That(questionThatWasAdded, Is.Not.Null); Assert.Multiple(() => { Assert.That( questionThatWasAdded !.QuestionText, Is.EqualTo(createQuestion.QuestionText)); CollectionAssert.AreEqual( questionThatWasAdded.Answers.Select(a => a.Text), createQuestion.Answers); }); }
public async Task <string> Execute(CreateQuestion command) { var nextQuestionSequence = await sequenceGenerator.GetNextAsync(SequenceType.SurveyQuestionBank); string questionId = $"{config["EnvironmentName"][0]}{nextQuestionSequence}"; var question = new SurveyQuestionBank { UID = Guid.NewGuid(), //remove IdQuestion = questionId, DsQuestion = command.QuestionText, CdQuestionType = command.QuestionType, CdCodeType = command.CodeType, InBankQuestion = command.SaveToBank, InAnswered = false, DtAdded = DateTime.Now, IdAdded = command.UserId }; await writeContext.SurveyQuestionBank.AddAsync(question); await writeContext.SaveChangesAsync(); return(questionId); }
public async Task <IActionResult> PostQuestionAsync([FromBody] CreateQuestion command) { await rules .NoDuplicateQuestionText() .Apply(command, ModelState); command.UserId = User.Identity.Name; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var createdQuestionId = await service.Execute(command); var uri = Url.Action("Get", new { id = createdQuestionId }); return(Created(uri, new QuestionDto { QuestionId = createdQuestionId, QuestionText = command.QuestionText, CodeType = command.CodeType, QuestionType = command.QuestionType, SaveToBank = command.SaveToBank, HasBeenAnswered = command.HasBeenAnswered, })); }
public async Task Should_Return_Error_On_Twice_Vote_On_Same_Question() { await LogInAsAdministrator(); var createQuestion = new CreateQuestion( questionText: "Some question?", answers: new[] { "First answer", "Second answer" }); var createQuestionResponse = await Mediator.Send(createQuestion); var createdQuestionId = AssertNotError.Of(createQuestionResponse); var getQuestion = new GetQuestion(createdQuestionId); var questionResponse = await Mediator.Send(getQuestion); var createdQuestion = AssertNotError.Of(questionResponse); await LogInAsVoter(); var voteFor = new VoteFor( questionId: createdQuestion.Id, answerId: createdQuestion.Answers[1].Id); var voteForResponse = await Mediator.Send(voteFor); var voteForDuplicate = new VoteFor( questionId: createdQuestion.Id, answerId: createdQuestion.Answers[0].Id); var voteForResponseDuplicate = await Mediator.Send(voteForDuplicate); AssertError <DomainError> .Of(voteForResponseDuplicate); }
private async Task AddQuestion(string question, IList <string> answers) { var createQuestion = new CreateQuestion(question, answers); QuestionViewModel questionViewModel; try { var questionId = await _mediator.Send(createQuestion) .OnError(error => throw new InvalidOperationException(error.ToString())); var getQuestion = new GetQuestion(questionId); questionViewModel = await _mediator.Send(getQuestion) .OnError(error => throw new InvalidOperationException(error.ToString())); } catch (Exception exception) { exception.WriteToConsole(); return; } Console.WriteLine(); Console.WriteLine(questionViewModel); Console.WriteLine(); }
public async Task Check_If_Votes_Incremented() { await LogInAsAdministrator(); var createQuestion = new CreateQuestion( questionText: "Some question?", answers: new[] { "First answer", "Second answer" }); var createQuestionResponse = await Mediator.Send(createQuestion); var createdQuestionId = AssertNotError.Of(createQuestionResponse); var getQuestion = new GetQuestion(createdQuestionId); var questionResponse = await Mediator.Send(getQuestion); var createdQuestion = AssertNotError.Of(questionResponse); await LogInAsVoter(); var voteFor = new VoteFor( questionId: createdQuestion.Id, answerId: createdQuestion.Answers[1].Id); var voteForResponse = await Mediator.Send(voteFor); var getQuestionResult = new GetQuestionResult(createdQuestion.Id); var questionResultResponse = await Mediator.Send(getQuestionResult); AssertNotError.Of(voteForResponse); var questionResult = AssertNotError.Of(questionResultResponse); Assert.Multiple(() => { Assert.That(questionResult.Answers[0].Votes, Is.EqualTo(0)); Assert.That(questionResult.Answers[1].Votes, Is.EqualTo(1)); }); }
public async Task Should_Return_Error_When_Not_Logged() { await LogInAsAdministrator(); var createQuestion = new CreateQuestion( questionText: "Some question?", answers: new[] { "First answer", "Second answer" }); var createQuestionResponse = await Mediator.Send(createQuestion); var createdQuestionId = AssertNotError.Of(createQuestionResponse); var getQuestion = new GetQuestion(createdQuestionId); var questionResponse = await Mediator.Send(getQuestion); var createdQuestion = AssertNotError.Of(questionResponse); LogOut(); var voteFor = new VoteFor( questionId: createdQuestion.Id, answerId: createdQuestion.Answers[1].Id); var voteForResponse = await Mediator.Send(voteFor); AssertError <AuthorizationError> .Of(voteForResponse); }
public async Task <IActionResult> CreateQuestion([FromBody] CreateQuestion cmd) { var dep = new QuestionDependencies(); // var questions = await _dbContext.QuestionModel.ToListAsync(); // var ctx = new QuestionWriteContext(questions); //.QuestionModel.AttachRange(questions); var ctx = new QuestionWriteContext(new EFList <QuestionModel>(_dbContext.QuestionModel)); var expr = from CreateQuestionResult in QuestionDependencies.CreateQuestion(createQuestionCmd) //let checkLanguageCmd = new CheckLanguage() //select CreateQuestionResult; //from checkLanguageResult in QuestionContext.CheckLanguage(new CheckLanguageCmd()) from sendAckToQuestionOwnerCmd in QuestionContext.SendAckToOwner(new SendAckToOwnerCmd(1, 2)) select CreateQuestionResult; var r = await _interpreter.Interpret(expr, ctx, dep); //dbContext.QuestionModel.Add(new DatabaseModel.Models.QuestionModel { QuestionId = Guid.NewGuid(), Title = cmd.Title, Description = cmd.Description, Tags = cmd.Tags }); //var reply = await _dbContext.QuestionModel.Where(r => r.Title == "Intrebarea1").SingleOrDefaultAsync(); //_dbContext.QuestionModel.Update(reply); // await _dbContext.SaveChangesAsync(); return(r.Match( succ => (IActionResult)Ok("Successfully"), fail => BadRequest("Reply could not be added") )); }
public static async Task Seed(this IContainer container) { await using var scope = container.BeginLifetimeScope(); var mediator = scope.Resolve <IMediator>(); var authenticationService = scope.Resolve <AuthenticationService>(); var logIn = new LogIn("12312312312"); var logInResult = await mediator.Send(logIn); if (!logInResult.TryGet(out var voter)) { var createVoter = new CreateVoter("12312312312"); await mediator.Send(createVoter) .OnError(error => throw new InvalidOperationException($"cannot create voter while seeding: {error}")); logIn = new LogIn("12312312312"); voter = await mediator.Send(logIn) .OnError(error => throw new InvalidOperationException($"cannot create voter while seeding: {error}")); } var identity = new VoterIdentity(voter.Id, voter.Pesel, voter.IsAdministrator); authenticationService.SetIdentity(identity); var getQuestionsCount = new GetQuestionsCount(); var questionsCount = await mediator.Send(getQuestionsCount) .OnError(error => throw new InvalidOperationException($"cannot get questions count while seeding: {error}")); if (questionsCount.Count == 0) { var createQuestion = new CreateQuestion("Some question?", new[] { "Answer 1", "Answer 2", "Answer 3" }); await mediator.Send(createQuestion) .OnError(error => throw new InvalidOperationException($"cannot create question while seeding: {error}")); } }
public async Task Create_3_Questions_And_Check_If_Added() { await LogInAsAdministrator(); var createFirstQuestion = new CreateQuestion( questionText: "Some question?", answers: new[] { "First answer", "Second answer" }); var createFirstQuestionResponse = await Mediator.Send(createFirstQuestion); var firstQuestionId = AssertNotError.Of(createFirstQuestionResponse); var createSecondQuestion = new CreateQuestion( questionText: "Another question?", answers: new[] { "Any answer", "Some answer" }); var createSecondQuestionResponse = await Mediator.Send(createSecondQuestion); var secondQuestionId = AssertNotError.Of(createSecondQuestionResponse); var createThirdQuestion = new CreateQuestion( questionText: "Third question?", answers: new[] { "Any answer", "Some answer", "I don't know answer" }); var createThirdQuestionResponse = await Mediator.Send(createThirdQuestion); var thirdQuestionId = AssertNotError.Of(createThirdQuestionResponse); await LogInAsVoter(); var expectedQuestions = new Dictionary <Guid, CreateQuestion> { [firstQuestionId] = createFirstQuestion, [secondQuestionId] = createSecondQuestion, [thirdQuestionId] = createThirdQuestion }; var getQuestions = new GetQuestions(); var getQuestionsResponse = await Mediator.Send(getQuestions); var questions = AssertNotError.Of(getQuestionsResponse); Assert.That(questions.Questions, Has.Count.EqualTo(3)); CollectionAssert.AreEquivalent( expectedQuestions.Select(q => q.Value.QuestionText), questions.Questions.Select(q => q.QuestionText)); foreach (var question in questions.Questions) { var expectedAnswers = expectedQuestions .Single(q => q.Key == question.Id) .Value .Answers; CollectionAssert.AreEqual( expectedAnswers, question.Answers.Select(a => a.Text)); } }
public async Task <IActionResult> Create([FromBody] CreateQuestion request) { var questionId = await _mediator.Send(request); var getQuestion = new GetQuestion(questionId); var response = await _mediator.Send(getQuestion); return(HandleErrors(response, Ok)); }
public async Task Should_Return_Error_On_Not_Logged_In() { var createQuestion = new CreateQuestion( questionText: "Some question?", answers: new[] { "First answer", "Second answer" }); var createQuestionResponse = await Mediator.Send(createQuestion); AssertError <AuthorizationError> .Of(createQuestionResponse); }
public Question Handle(CreateQuestion request) { return(_questionDataStorage.Create(new Question(0, request.Text) { Periodicity = request.Periodicity, Type = request.Type, Options = request.Options })); }
public async Task Check_If_Votes_Exists_In_My_Votes_After_Voting_2_Of_3_Questions() { await LogInAsAdministrator(); var createFirstQuestion = new CreateQuestion( questionText: "Some question?", answers: new[] { "First answer", "Second answer" }); var createFirstQuestionResponse = await Mediator.Send(createFirstQuestion); var firstQuestionId = AssertNotError.Of(createFirstQuestionResponse); var getFirstQuestion = new GetQuestion(firstQuestionId); var firstQuestionResponse = await Mediator.Send(getFirstQuestion); var firstQuestion = AssertNotError.Of(firstQuestionResponse); var createSecondQuestion = new CreateQuestion( questionText: "Another question?", answers: new[] { "Any answer", "Some answer" }); var createSecondQuestionResponse = await Mediator.Send(createSecondQuestion); _ = AssertNotError.Of(createSecondQuestionResponse); // I will not vote on this question var createThirdQuestion = new CreateQuestion( questionText: "Third question?", answers: new[] { "Any answer", "Some answer", "I don't know answer" }); var createThirdQuestionResponse = await Mediator.Send(createThirdQuestion); var thirdQuestionId = AssertNotError.Of(createThirdQuestionResponse); var getThirdQuestion = new GetQuestion(thirdQuestionId); var thirdQuestionResponse = await Mediator.Send(getThirdQuestion); var thirdQuestion = AssertNotError.Of(thirdQuestionResponse); await LogInAsVoter(); var voteForFirst = new VoteFor( questionId: firstQuestion.Id, answerId: firstQuestion.Answers[0].Id); await Mediator.Send(voteForFirst); var voteForThird = new VoteFor( questionId: thirdQuestion.Id, answerId: thirdQuestion.Answers[2].Id); await Mediator.Send(voteForThird); var getMyVotes = new GetMyVotes(); var getMyVotesResponse = await Mediator.Send(getMyVotes); var myVotes = AssertNotError.Of(getMyVotesResponse); CollectionAssert.AreEquivalent( new[] { firstQuestion.Id, thirdQuestion.Id }, myVotes.QuestionsId); }
public void CreateQuestion_ShouldCreateAQuestion() { CreateQuestion q = new CreateQuestion { Title = "test", Status = true }; var x = questionController.CreateQuestion(q) as CreatedNegotiatedContentResult <Question>; Assert.AreEqual(q.Title, x.Content.Title); }
public void UpdateQuestion_ShouldUpdateQuestion() { CreateQuestion q = new CreateQuestion { Title = "test_update", Status = true }; questionController.UpdateQuestion(1, q); Assert.AreEqual(q.Title, repository.updatedQuestion.Title); }
public JsonResult PostQuestion([FromBody] CreateQuestion inQuestion) { if (TryValidateModel(inQuestion)) { var custServAccessLayer = new CustomerServiceAccessLayer(_context); var question = custServAccessLayer.PostQuestion(inQuestion); return(Json(question)); } return(Json(null)); }
private async Task <OperationResult <question> > PutLike(CreateQuestion item) { using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var question = await questionRepo.GetByIdAsync(item.id); var user = await userService.GetByIdAsync(item.liked_user); if (question == null) { return new OperationResult <question>() { Success = false, Message = Messages.QUESTION_NOT_EXIST } } ; if (!user.Success) { return new OperationResult <question>() { Success = false, Message = user.Message } } ; var userRes = user.Result; if (question.user_like.Any(elem => userRes.id == elem.id) || [email protected](elem => ((elem.userId == userRes.id) && (elem.checkIn.Value)))) { return(new OperationResult <question>() { Success = false, Message = Messages.LIKE_ERROR }); } try { await questionRepo.insertLiker(userRes, question); scope.Complete(); return(new OperationResult <question>() { Success = true, Message = Messages.QUESTION_UPDATED, Result = question }); } catch (Exception ex) { return(new OperationResult <question>() { Success = false, Message = ex.Message }); } } }
//<------------------------------------------------------------------------------------------------------> //<------------------------------------------------------------------------------------------------------> private async Task <OperationResult <int> > Post(CreateQuestion item) { using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { if (!item.ParameterValid()) { return new OperationResult <int>() { Success = false, Message = Messages.PARAMETERS_NOT_NULL } } ; var session = await sessionService.GetByIdAsync(item.sessionId); if (!session.Success) { return new OperationResult <int>() { Success = false, Message = session.Message } } ; if ([email protected](elem => (elem.userId == item.authorId) && elem.checkIn == true)) { return new OperationResult <int>() { Success = false, Message = Messages.USER_NO_PERMISSION } } ; try { var id = await questionRepo.PostAsync(item); scope.Complete(); return(new OperationResult <int>() { Success = true, Message = Messages.QUESTION_CREATED, Result = id }); } catch (Exception ex) { return(new OperationResult <int>() { Success = false, Message = ex.Message }); } } }
public async Task <IActionResult> Post([FromBody] QustionWithAnserwsDto question, [FromRoute] string tagName) { if (question == null) { return(BadRequest(new ArgumentNullException($"{nameof(question)}"))); } if (string.IsNullOrWhiteSpace(question.Question)) { return(BadRequest(new ArgumentNullException($"{nameof(question.Question)}"))); } if (string.IsNullOrWhiteSpace(tagName)) { return(BadRequest(new ArgumentNullException($"{nameof(tagName)}"))); } var isAnyAnswer = question.Answers != null && question.Answers.Any(); if (isAnyAnswer && question.Answers.Any(a => a.IsCorrect) == false) { return(BadRequest(new ArgumentException("Any answer isn't correct", $"{nameof(question.Answers)}"))); } var command = new CreateQuestion() { Question = question.Question, CreatedOn = "PawelHaracz", Tag = tagName }; var questionId = await _commandDispatcher.DispatchAsync(command).ConfigureAwait(false); //implement service bus for that if (isAnyAnswer) { var aneswerCommands = question.Answers.Select(a => new CreateAnswer() { QuestionId = questionId, Answer = a.Answer, IsCorrect = a.IsCorrect, CreatedBy = command.CreatedOn }); var answerTasks = aneswerCommands.Select(answer => _commandDispatcher.DispatchAsync(answer)).Cast <Task>().ToList(); await Task.WhenAll(answerTasks).ConfigureAwait(false); } return(Ok(questionId)); }
/// <summary> /// Posts a question to the database based on the CreateQuestion's title value, and binds it /// to the Categories table using the CreateQuestion's CategoryId value. /// </summary> /// <param name="inQuestion">Contains question title ie. the question and a category id.</param> /// <returns>The added question.</returns> public Question PostQuestion(CreateQuestion inQuestion) { try { Question question = new Question() { Title = inQuestion.Title, Category = _context.Categories.Find(inQuestion.CategoryId) }; _context.Add(question); _context.SaveChanges(); return(question); }catch (Exception e) { Console.Error.WriteLine("Something went wrong in Oblig3.CustomerServiceAccessLayer.PostQuestion(CreateQuestion inQuestion)", e); return(null); } }
public async Task Should_Return_Error_When_Request_For_Result_Of_Not_Voted_Question() { await LogInAsAdministrator(); var createQuestion = new CreateQuestion( questionText: "Some question?", answers: new[] { "First answer", "Second answer" }); var createQuestionResponse = await Mediator.Send(createQuestion); var questionId = AssertNotError.Of(createQuestionResponse); await LogInAsVoter(); var getResult = new GetQuestionResult(questionId); var getResultResponse = await Mediator.Send(getResult); AssertError <AuthorizationError> .Of(getResultResponse); }
private async Task <OperationResult <int> > Delete(CreateQuestion item) { using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var question = await questionRepo.GetByIdAsync(item.id); if (question == null) { return new OperationResult <int>() { Success = false, Message = Messages.QUESTION_NOT_EXIST } } ; if (question.authorId != item.authorId) { return new OperationResult <int>() { Success = false, Message = Messages.USER_NO_QUESTION } } ; try { var id = await questionRepo.DeleteAsync(question); scope.Complete(); return(new OperationResult <int>() { Success = true, Message = Messages.QUESTION_DELETED, Result = id }); } catch (Exception ex) { return(new OperationResult <int>() { Success = false, Message = ex.Message }); } } } } }
public IApiResult Create(CreateQuestion operation) { var result = operation.ExecuteAsync().Result; if (result is ValidationsOutput) { return(new ApiResult <List <ValidationItem> >() { Data = ((ValidationsOutput)result).Errors }); } else { return(new ApiResult <object>() { Status = ApiResult <object> .ApiStatus.Success }); } }
public Task <int> PostAsync(CreateQuestion item) { return(Task.Factory.StartNew(() => { var result = new question() { authorId = item.authorId, message = item.message, sessionId = item.sessionId, likes = 0 }; context.question.Add(result); try { context.SaveChanges(); return result.id; } catch (Exception e) { throw new ArgumentException(e.InnerException.InnerException.Message); } })); }
public IHttpActionResult Add([FromBody] CreateQuestion CQ) { var Answer = new DataTable(); Answer.Columns.Add("Answer", typeof(string)); foreach (var item in CQ.Answer) { Answer.Rows.Add(item); } var parameter1 = new SqlParameter("Question", SqlDbType.NVarChar); parameter1.Value = CQ.Question; var parameter2 = new SqlParameter("courseID", SqlDbType.Int); parameter2.Value = CQ.courseID; var parameter3 = new SqlParameter("TypeID", SqlDbType.Int); parameter3.Value = CQ.TypeID; var parameter4 = new SqlParameter("@Answer", SqlDbType.Structured); parameter4.Value = Answer; parameter4.TypeName = "dbo.ListOFAnswers"; var parameter5 = new SqlParameter("R_Answer", SqlDbType.Int); parameter5.Value = CQ.R_Answer; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.Database.ExecuteSqlCommand("exec dbo.CreateQuestion @Question, @courseID, @TypeID, @Answer, @R_Answer", parameter1, parameter2, parameter3, parameter4, parameter5); return(CreatedAtRoute("DefaultApi", new { Question = CQ.Question }, CQ)); }
public IHttpActionResult CreateQuestion( [FromBody] CreateQuestion questionItem) { if (questionItem == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var itemToInsert = new Models.Question() { Title = questionItem.Title, Status = questionItem.Status }; var item = QuestionRepository.CreateQuestion(Mapper.Map <Entities.Question>(itemToInsert)); return(Created("Created", Mapper.Map <Models.Question>(item))); }
public IActionResult Create([FromBody] CreateQuestion command) { _bus.Dispatch(command); return(NoContent()); }
public async Task Check_If_Question_Results_Are_Valid() { await LogInAsAdministrator(); var createFirstQuestion = new CreateQuestion( questionText: "Some question?", answers: new[] { "First answer", "Second answer" }); var createFirstQuestionResponse = await Mediator.Send(createFirstQuestion); var firstQuestionId = AssertNotError.Of(createFirstQuestionResponse); var getFirstQuestion = new GetQuestion(firstQuestionId); var firstQuestionResponse = await Mediator.Send(getFirstQuestion); var firstQuestion = AssertNotError.Of(firstQuestionResponse); var createSecondQuestion = new CreateQuestion( questionText: "Another question?", answers: new[] { "Any answer", "Some answer" }); var createSecondQuestionResponse = await Mediator.Send(createSecondQuestion); var secondQuestionId = AssertNotError.Of(createSecondQuestionResponse); var getSecondQuestion = new GetQuestion(secondQuestionId); var secondQuestionResponse = await Mediator.Send(getSecondQuestion); var secondQuestion = AssertNotError.Of(secondQuestionResponse); var firstVoteFor = new VoteFor(firstQuestion.Id, firstQuestion.Answers[0].Id); await Mediator.Send(firstVoteFor); var secondVoteFor = new VoteFor(secondQuestion.Id, secondQuestion.Answers[1].Id); await Mediator.Send(secondVoteFor); await LogInAsVoter(); var thirdVoteFor = new VoteFor(firstQuestion.Id, firstQuestion.Answers[0].Id); await Mediator.Send(thirdVoteFor); var fourthVoteFor = new VoteFor(secondQuestion.Id, secondQuestion.Answers[0].Id); await Mediator.Send(fourthVoteFor); var getFirstResult = new GetQuestionResult(firstQuestion.Id); var firstResultResponse = await Mediator.Send(getFirstResult); var firstResult = AssertNotError.Of(firstResultResponse); var getSecondResult = new GetQuestionResult(secondQuestion.Id); var secondResultResponse = await Mediator.Send(getSecondResult); var secondResult = AssertNotError.Of(secondResultResponse); Assert.Multiple(() => { Assert.That(firstResult.Answers[0].Votes, Is.EqualTo(2)); Assert.That(firstResult.Answers[1].Votes, Is.EqualTo(0)); Assert.That(secondResult.Answers[0].Votes, Is.EqualTo(1)); Assert.That(secondResult.Answers[1].Votes, Is.EqualTo(1)); }); }