public void CreateQuestionResourceNames() { moq::Mock <QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock <QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); CreateQuestionRequest request = new CreateQuestionRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Question = new Question(), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.CreateQuestion(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question response = client.CreateQuestion(request.ParentAsLocationName, request.Question); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
public async Task <Guid> CreateQuestion(CreateQuestionRequest request, Guid gameId) { var game = await gameRepository.GetGameWithQuestions(gameId); var questionResult = game.AddQuestion(request.Variants, request.Name, request.MultipleAnswers); if (!questionResult.IsSuccess) { throw new DomainValidationException(questionResult); } await gameRepository.SaveChanges(); var question = questionResult.Value; await hubContext.Clients.All.SendAsync(gameId.ToString(), new QuestionDto { Id = question.Id, Name = question.Name, Order = question.Order, MultipleAnswers = question.MultipleAnswers, Variants = question.Variants.Select(v => new QuestionVariantDto { Id = v.Id, Name = v.Name, Notation = v.Notation }).OrderBy(x => x.Notation).ToList() }); return(question.Id); }
public async Task <Question> CreateQuestionAsync(int loggedUser, CreateQuestionRequest question) { // validate admin user var user = await _uow.UserRepository.FindByAsync(u => u.Id == loggedUser && u.Role == RoleEnum.ADMIN); if (user.Count == 0) { throw new NotAllowedException(ExceptionConstants.NOT_ALLOWED); } var poll = await _uow.PollRepository.GetAsync(question.PollId); if (poll == null) { throw new NotFoundException(ExceptionConstants.NOT_FOUND, "Poll"); } var q = new Question(); q.CreatedAt = DateTime.UtcNow; q.ModifiedAt = DateTime.UtcNow;; q.Order = question.Order; q.Title = question.Title; q.PollId = poll.Id; await _uow.QuestionRepository.AddAsync(q); await _uow.CommitAsync(); return(q); }
public async Task <ActionResult> Create(QuestionCreateViewModel model, FormCollection formCollection) { List <AddAnswerRequest> answers = new List <AddAnswerRequest>(); for (int i = 4; i < formCollection.Count; i += 2) { AddAnswerRequest addAnswerRequest = new AddAnswerRequest() { Title = formCollection[i], IsCorrectAnswer = Convert.ToBoolean(formCollection[i + 1]) }; answers.Add(addAnswerRequest); } CreateQuestionRequest createQuestionRequest = new CreateQuestionRequest() { Title = model.Title, Explanation = model.Explanation, ThemeId = model.ThemeId, Answers = answers }; var question = await _questionAdminService.CreateQuestionAsync(createQuestionRequest); if (model.Image != null && model.Image.ContentLength > 0) { var extension = AttachmentsUtil.GetExtentionFromMimeType(model.Image.ContentType); var content = GetAttachmentContent(model.Image); await _questionAdminService.UploadAttachmentAsync(new UploadQuestionAttachmentRequest(question.Id, content, extension)); } return(RedirectToAction("Index", new { themeId = model.ThemeId })); }
public async Task <QuestionResponse> CreateQuestionAsync(CreateQuestionRequest model) { Question question = new Question() { Id = Guid.NewGuid(), Title = model.Title, Explanation = model.Explanation, Created = DateTime.UtcNow }; QuestionTheme questionTheme = new QuestionTheme() { QuestionId = question.Id, ThemeId = model.ThemeId, Created = DateTime.UtcNow }; UnitOfWork.QuestionRepository.Add(question); UnitOfWork.QuestionThemeRepository.Add(questionTheme); await UnitOfWork.SaveChangesAsync(); foreach (var answer in model.Answers) { answer.QuestionId = question.Id; await _answerAdminService.AddAnswerAsync(answer); } var newQuestion = await GetQuestionByIdAsync(question.Id); return(newQuestion); }
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 async Task <IActionResult> AddQuestion([FromBody] CreateQuestionRequest question) { var loggedUser = User.GetUserIdFromToken(); var result = await _questionService.CreateQuestionAsync(loggedUser, question); var mapped = _mapper.Map <QuestionResponse>(result); return(Created("", new ApiOkResponse(mapped))); }
public async Task <HttpResponseMessage> Create([FromBody] QuestionDto question) { var request = new CreateQuestionRequest { Question = question }; await _mediator.ExecuteAsync(request).ConfigureAwait(false); return(Request.CreateResponse(HttpStatusCode.Created)); }
/// <summary>Snippet for CreateQuestion</summary> public void CreateQuestionRequestObject() { // Snippet: CreateQuestion(CreateQuestionRequest, CallSettings) // Create client QuestionServiceClient questionServiceClient = QuestionServiceClient.Create(); // Initialize request argument(s) CreateQuestionRequest request = new CreateQuestionRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Question = new Question(), }; // Make the request Question response = questionServiceClient.CreateQuestion(request); // End snippet }
/// <summary>Snippet for CreateQuestionAsync</summary> public async Task CreateQuestionRequestObjectAsync() { // Snippet: CreateQuestionAsync(CreateQuestionRequest, CallSettings) // Additional: CreateQuestionAsync(CreateQuestionRequest, CancellationToken) // Create client QuestionServiceClient questionServiceClient = await QuestionServiceClient.CreateAsync(); // Initialize request argument(s) CreateQuestionRequest request = new CreateQuestionRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Question = new Question(), }; // Make the request Question response = await questionServiceClient.CreateQuestionAsync(request); // End snippet }
public async stt::Task CreateQuestionRequestObjectAsync() { moq::Mock <QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock <QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); CreateQuestionRequest request = new CreateQuestionRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Question = new Question(), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.CreateQuestionAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <Question>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question responseCallSettings = await client.CreateQuestionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Question responseCancellationToken = await client.CreateQuestionAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); }
public async Task <IActionResult> CreateQuestionAsync([FromBody] CreateQuestionRequest model, [FromServices] IHubContext <SbHub> hubContext, CancellationToken token) { var userId = _userManager.GetLongUserId(User); var toasterMessage = _localizer["PostedQuestionToasterOk"]; try { var command = new CreateQuestionCommand(model.Text, userId, model.Course); await _commandBus.DispatchAsync(command, token); } catch (DuplicateRowException) { toasterMessage = _localizer["PostedQuestionToasterDuplicate"]; } catch (SqlConstraintViolationException) { toasterMessage = _localizer["PostedQuestionToasterCourseNotExists"]; //Console.WriteLine(e); //throw; } await hubContext.Clients.User(userId.ToString()).SendCoreAsync("Message", new object[] { new SignalRTransportType(SignalRType.System, SignalREventAction.Toaster, new { text = toasterMessage.Value } ) }, token); return(Ok()); }
public Task <Guid> Create(CreateQuestionRequest request, [FromRoute] Guid gameId) { return(questionsService.CreateQuestion(request, gameId)); }
public CreateQuestionResponse CreateQuestion(CreateQuestionRequest request) { CreateQuestionResponse response = new CreateQuestionResponse(); AuthToken authToken = null; try { Common.Helpers.ValidationHelper.ValidateRequiredField(request.AuthToken, "Auth Token"); Common.Helpers.ValidationHelper.ValidateRequiredField(request.AntiForgeryToken, "Anti Forgery Token"); Common.Helpers.ValidationHelper.ValidateRequiredField(request.Name, "Name"); Common.Helpers.ValidationHelper.ValidateStringLength(request.Name, "Name", Constants.MaxNameLength); Common.Helpers.ValidationHelper.ValidateStringLength(request.QuestionBody, "Hidden Code", Constants.MaxBlobLength); foreach (QuestionTest test in request.Tests) { Common.Helpers.ValidationHelper.ValidateRequiredField(test.Name, "Test Name"); Common.Helpers.ValidationHelper.ValidateRequiredField(test.Input, "Test Input"); Common.Helpers.ValidationHelper.ValidateRequiredField(test.ExpectedOutput, "Test Output"); Common.Helpers.ValidationHelper.ValidateStringLength(test.Name, "Test Name", Constants.MaxNameLength); Common.Helpers.ValidationHelper.ValidateStringLength(test.Input, "Test Input", Constants.MaxBlobLength); Common.Helpers.ValidationHelper.ValidateStringLength(test.ExpectedOutput, "Test Expected Output", Constants.MaxBlobLength); } if (!UserController.ValidateSession(request.AuthToken, out authToken)) { throw new AuthenticationException("Authentication failed."); } UserController.ValidateAntiForgeryToken(request.AntiForgeryToken, authToken); DbContext context = DataController.CreateDbContext(); E::Question newQuestion = new E::Question(); newQuestion.ID = Guid.NewGuid(); newQuestion.Name = request.Name; newQuestion.QuestionTypeID = (short)QuestionType.Standard; newQuestion.QuestionBody = Guid.NewGuid(); newQuestion.Tests = Guid.NewGuid(); newQuestion.CreatedBy = authToken.Username; newQuestion.CreatedDate = DateTime.UtcNow; newQuestion.LastUpdatedBy = authToken.Username; newQuestion.LastUpdatedDate = DateTime.UtcNow; DataController.UploadBlob(newQuestion.QuestionBody.ToString(), request.QuestionBody); IList <TestsController.Test> tests = new List <TestsController.Test>(); foreach (QuestionTest test in request.Tests) { TestsController.Test newTest = new TestsController.Test(); newTest.ID = Guid.NewGuid(); newTest.Name = test.Name; newTest.Input = test.Input; newTest.ExpectedOutput = test.ExpectedOutput; newTest.ID = Guid.NewGuid(); tests.Add(newTest); } response.TestIDs = tests.Select(t => t.ID).ToArray(); DataController.UploadBlob(newQuestion.Tests.Value.ToString(), TestsController.ToJson(tests.ToArray())); context.Questions.Add(newQuestion); context.SaveChanges(); response.QuestionID = newQuestion.ID; } catch (AuthenticationException ex) { throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest); } catch (Common.Exceptions.ValidationException ex) { throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest); } catch (Exception ex) { ExceptionHelper.Log(ex, authToken == null ? null : authToken.Username); throw new WebFaultException <string>("An unknown error has occurred.", System.Net.HttpStatusCode.InternalServerError); } return(response); }
public ActionResult AddQuestion(CreateQuestionRequest createRequest) { var newQuestion = _questionRepository.AddQuestion(createRequest.QuestionText, createRequest.QuestionDate); return(Created($"/api/student/{newQuestion.Id}", newQuestion)); }