Beispiel #1
0
        public async Task <ApiResult <QuestionRequest> > GetById(int questionId)
        {
            var question = await _context.Questions.FindAsync(questionId);

            var answer = await _context.Answers.FirstOrDefaultAsync(a => a.QuestionId == questionId);

            if (question == null || answer == null)
            {
                return(new ApiResultErrors <QuestionRequest>("not found"));
            }
            var questionViewModel = new QuestionRequest()
            {
                QuestionContent = question.QuestionContent,
                ModuleId        = question.ModuleId,
                QuestionType    = question.QuestionType,
                A = answer.A,
                B = answer.B,
                C = answer.C,
                D = answer.D,
                CorrectAnswers = answer.CorrectAnswers,
                AnswerExplain  = answer.AnswerExplain,
            };

            return(new ApiResultSuccess <QuestionRequest>(questionViewModel));
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            CancellationTokenSource tokenSource = new CancellationTokenSource();
            string address = "https://localhost:5111";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
                address = "http://localhost:5001";
            }

            var           channel   = GrpcChannel.ForAddress(address);
            var           client    = new Maths.MathsClient(channel);
            List <string> questions = new List <string>()
            {
                { "22+54" }, { "1-1" }, { "435-36" }, { "6+2*(98*2)" }, { "10/2" }, { "5-32" }, { "4*2" },
                { "1-5*(-10+2)" }, { "5+1" }, { "15-3" }, { "6*2/(9-2)" }, { "10/2" }, { "5-2" }, { "4*2" }
            };

            var questionRequest = new QuestionRequest();

            questionRequest.Texts.AddRange(questions);

            using (var call = client.AskQuestion(questionRequest))
            {
                while (call.ResponseStream.MoveNext(tokenSource.Token).Result)
                {
                    Console.WriteLine($"{call.ResponseStream.Current.Question} = {call.ResponseStream.Current.Answer.ToString()}");
                }
            }
        }
Beispiel #3
0
        public async Task PostQuestion_Success()
        {
            var question = new QuestionRequest
            {
                Content   = "This is ... car?",
                AnswerA   = "a",
                AnswerB   = "an",
                AnswerC   = "that",
                AnswerD   = "this",
                CorectAns = "a"
            };

            var questionService = new QuestionService(_questionRepository);

            var controller = new QuestionsController(questionService);

            //action
            var result = await controller.AddQuestion(question);

            //course

            result.Should().NotBeNull();

            var createdAtActionResult = Assert.IsType <OkObjectResult>(result.Result);
            var returnValue           = Assert.IsType <Question>(createdAtActionResult.Value);

            Assert.Equal("This is ... car?", returnValue.Content);
            Assert.Equal("a", returnValue.AnswerA);
            Assert.Equal("an", returnValue.AnswerB);
            Assert.Equal("that", returnValue.AnswerC);
            Assert.Equal("this", returnValue.AnswerD);
            Assert.Equal("a", returnValue.CorectAns);
        }
Beispiel #4
0
        public async Task <ApiResult <bool> > Update(QuestionRequest request, int questionId)
        {
            var question = await _context.Questions.FindAsync(questionId);

            var answer = await _context.Answers.FirstOrDefaultAsync(a => a.QuestionId == questionId);

            if (question == null || answer == null)
            {
                return(new ApiResultErrors <bool>("not found"));
            }
            question.QuestionContent = request.QuestionContent;
            question.ModuleId        = request.ModuleId;
            question.QuestionType    = request.QuestionType;

            answer.A = request.A;
            answer.B = request.B;
            answer.C = request.C;
            answer.D = request.D;
            answer.CorrectAnswers = request.CorrectAnswers;
            answer.AnswerExplain  = request.AnswerExplain;

            await _context.SaveChangesAsync();

            return(new ApiResultSuccess <bool>());
        }
Beispiel #5
0
        public async Task <IActionResult> Post([FromBody] QuestionRequest model)
        {
            Question newRecord = null;

            if (ModelState.IsValid)
            {
                InitUserCredentials();

                newRecord = new Question
                {
                    Guid             = Guid.NewGuid(),
                    UserGuid         = UserGuid,
                    CompanyGuid      = CompanyGuid,
                    CreationTime     = DateTime.UtcNow,
                    CreationUserGuid = UserGuid
                };

                newRecord = _mapper.Map(model, newRecord);

                try
                {
                    await _questionService.Save(newRecord);
                }
                catch (Exception e)
                {
                    Log.Error(e.StackTrace);
                    throw;
                }
            }

            return(CreatedAtAction(nameof(Post), _mapper.Map(newRecord, new QuestionResponse())));
        }
Beispiel #6
0
        public void Fact_description(string[] readLineResponses, string expectedAnswer)
        {
            // Arrange

            var request = new QuestionRequest
            {
                Answers = new[] { "[Y]es", "[n]o" }
            };

            var consoleServiceMock = new Mock <IConsoleService>();

            foreach (var readLineResponse in readLineResponses)
            {
                consoleServiceMock.Setup(mock => mock.ReadLine()).Returns(readLineResponse);
            }

            var sut = new QuestionHandler(consoleServiceMock.Object);

            // Act

            var response = sut.Handle(request, CancellationToken.None).GetAwaiter().GetResult();

            // Assert

            Assert.Equal(expectedAnswer, response.Answer);
        }
Beispiel #7
0
        public async Task <ActionResult <IPagedResult <Questions> > > GetPagedAsync([FromBody] QuestionRequest questionRequest)
        {
            try
            {
                var requestPaged = new PagedRequestDTO(questionRequest.PageIndex, questionRequest.PageSize);

                var fieldsValues = new Dictionary <string, string>();
                if (questionRequest.Filters.Any())
                {
                    foreach (var filter in questionRequest.Filters)
                    {
                        fieldsValues.Add(filter.PropertyName, filter.PropertyValue);
                    }
                }

                var sortData = new SortDTO();
                if (questionRequest?.SortData != null)
                {
                    sortData.SortDirection = questionRequest.SortData.SortDirection;
                    sortData.SortField     = questionRequest.SortData.SortField;
                }

                var result = await _questionsService.GetPagedAsync(requestPaged, fieldsValues, sortData);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #8
0
 public dynamic GetQuestionList([FromUri] QuestionRequest request)
 {
     if (!string.IsNullOrEmpty(request.Title))
     {
         request.Title = request.Title.Trim();
     }
     return(Success(mapper.GetQuestionList(request, this.System_Station_ID), request.PageIndex == 1 ? mapper.GetQuestionTotalCount(request, this.System_Station_ID) : 0));
 }
        public async Task Create_Answers(IStateService stateService, QuestionRequest request)
        {
            var context = TestSetup.SetupContext();
            var service = new QuestionService(context, TestSetup.SetupHttpContext(), stateService);

            var result = await service.Create(request);

            result.Answers.Should().NotBeNull().And.BeEquivalentTo(request.Answers);
            context.Answers.AsEnumerable().Should().BeEquivalentTo(result.Answers);
        }
        public async Task <IActionResult> Update([FromForm] QuestionRequest request, int questionId)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var result = await _questionService.Update(request, questionId);

            return(Ok(result));
        }
        public async Task <IActionResult> Update(int questionId, QuestionRequest questionRequest)
        {
            bool updated = await _questionService.UpdateAsync(questionId, questionRequest);

            if (updated)
            {
                return(Ok(await _questionService.GetByIdAsync(questionId)));
            }
            return(NotFound());
        }
Beispiel #12
0
        public override async Task <AnswerReply> SolveOperation(QuestionRequest request, ServerCallContext context)
        {
            var dt     = new DataTable();
            var answer = Convert.ToDouble(dt.Compute(request.Texts[0], string.Empty));

            return(new AnswerReply()
            {
                Question = request.Texts[0].Trim(),
                Answer = answer
            });
        }
Beispiel #13
0
        public async Task <ActionResult <Question> > Create(QuestionRequest question)
        {
            var result = await _questions.Create(question, HttpContext.RequestAborted);

            if (result == null)
            {
                return(Conflict());
            }

            return(result);
        }
Beispiel #14
0
        public IHttpActionResult GetAnswerFromQuestion(QuestionRequest questionData)
        {
            var result = Service.QuestionAnswerService.GetAnswersFromQuestion(questionData.QuestionId);

            if (result.Length == 0)
            {
                return(NotFound());
            }

            return(Ok(result));
        }
        public async Task <QuestionResponse.QnAMakerResult> GetQnAMakerResponse(string query)
        {
            string responseString;
            var    qnamakerBaseUri     = this.BaseUri;
            var    knowledgebaseId     = this.KnowledgeBaseId; // Use knowledge base id created.
            var    qnamakerEndpointKey = this.EndpointKey;     //Use endpoint key assigned to you.

            //Build the URI
            var qnamakerUriBase = new Uri(qnamakerBaseUri);
            var builder         = new UriBuilder($"{qnamakerUriBase}/knowledgebases/{knowledgebaseId}/generateAnswer");

            //Add the question as part of the body
            var request = new QuestionRequest()
            {
                Question = query,
                Top      = MaxAnswers,
                UserId   = "QnAMakerDialog"
            };

            request.MetadataBoost = MetadataBoost?.ToArray() ?? new Models.Metadata[] { };
            request.StrictFilters = MetadataFilter?.ToArray() ?? new Models.Metadata[] { };

            var postBody = JsonConvert.SerializeObject(request);

            //Send the POST request
            using (WebClient client = new WebClient())
            {
                //Set the encoding to UTF8
                client.Encoding = System.Text.Encoding.UTF8;

                //Add the subscription key header
                client.Headers.Add("Authorization", $"EndpointKey {qnamakerEndpointKey}");
                client.Headers.Add("Content-Type", "application/json");
                try
                {
                    responseString = client.UploadString(builder.Uri, postBody);
                }
                catch (WebException err)
                {
                    throw new Exception(err.Message);
                }
            }

            //De-serialize the response
            try
            {
                var response = JsonConvert.DeserializeObject <QuestionResponse.QnAMakerResult>(responseString);
                return(response);
            }
            catch
            {
                throw new Exception("Unable to deserialize QnA Maker response string.");
            }
        }
        // POST: api/Questions/request-questions-for-exam
        public HttpResponseMessage RetrieveQuestionsForExam([FromBody] QuestionRequest request, int?id)
        {
            List <int>         query        = request.values;
            List <Question>    result       = db.Questions.Where(question => query.Contains(question.ID)).ToList();
            List <QuestionDTO> questionList = new List <QuestionDTO>();

            foreach (var question in result)
            {
                questionList.Add(new QuestionDTO(question));
            }
            return(Request.CreateResponse(HttpStatusCode.OK, questionList));
        }
        public HttpResponseMessage Create(QuestionRequest req)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            int id = questionsService.Create(req);
            ItemResponse <int> response = new ItemResponse <int>();

            response.Item = id;
            return(Request.CreateResponse(HttpStatusCode.Created, response));
        }
Beispiel #18
0
        public async Task <bool> UpdateAsync(int questionId, QuestionRequest questionRequest)
        {
            Question existingQuestion = await _questionRepository.GetByIdAsync(questionId);

            if (existingQuestion == null)
            {
                return(false);
            }

            existingQuestion.Body = questionRequest.Body;
            existingQuestion.Type = questionRequest.Type;

            return(await _questionRepository.UpdateAsync(existingQuestion));
        }
Beispiel #19
0
        public QuestionForm FillQuestionForm(QuestionForm questionForm, QuestionRequest request)
        {
            questionForm.FillInTextField(request.TextInput);

            questionForm.FillInNameField(request.NameInput);

            questionForm.FillInEmailField(request.EmailInput);

            questionForm.FillInAgeField(request.AgeInput);

            questionForm.FillInPostCodeField(request.PostCodeInput);

            return(questionForm);
        }
        public async Task <IActionResult> UploadFileExcel(int examId, IFormFile myfile)
        {
            var file     = HttpContext.Request.Form.Files[0];
            var filePath = Path.GetFileName(file.FileName);

            using (var stream = System.IO.File.Create(filePath))
            {
                await file.CopyToAsync(stream);

                // If you are a commercial business and have
                // purchased commercial licenses use the static property
                // LicenseContext of the ExcelPackage class:
                ExcelPackage.LicenseContext = LicenseContext.Commercial;

                // If you use EPPlus in a noncommercial context
                // according to the Polyform Noncommercial license:
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                using (var package = new ExcelPackage(stream))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[0];

                    // get number of rows and columns in the sheet
                    int rows    = worksheet.Dimension.End.Row;    // 20
                    int columns = worksheet.Dimension.End.Column; // 7

                    // loop through the worksheet rows and columns
                    for (int i = 3; i <= rows; i++)
                    {
                        if (worksheet.Cells[i, 1].Value == null)
                        {
                            break;
                        }
                        QuestionRequest question = new QuestionRequest()
                        {
                            ExamId          = examId,
                            QuestionContent = ((worksheet.Cells[i, 2].Value) ?? "").ToString(),
                            QuestionType    = int.Parse((worksheet.Cells[i, 3].Value ?? "0").ToString()),
                            CorrectAnswers  = ((worksheet.Cells[i, 4].Value) ?? "").ToString(),
                            AnswerExplain   = ((worksheet.Cells[i, 5].Value) ?? "").ToString(),
                            A = ((worksheet.Cells[i, 6].Value) ?? "").ToString(),
                            B = ((worksheet.Cells[i, 7].Value) ?? "").ToString(),
                            C = ((worksheet.Cells[i, 8].Value) ?? "").ToString(),
                            D = ((worksheet.Cells[i, 9].Value) ?? "").ToString(),
                        };
                        await _questionService.Create(question);
                    }
                }
            }
            return(Ok(new ApiResult <String>().Message = "OK"));
        }
        public async Task <Question> Add(QuestionRequest questionRequest)
        {
            var question = new Question
            {
                Content   = questionRequest.Content,
                AnswerA   = questionRequest.AnswerA,
                AnswerB   = questionRequest.AnswerB,
                AnswerC   = questionRequest.AnswerC,
                AnswerD   = questionRequest.AnswerD,
                CorectAns = questionRequest.CorectAns
            };

            return(await _baseRepository.Add(question));
        }
        public IActionResult Update([FromBody] QuestionRequest request)
        {
            var question = Mapper.Map <Question>(request);

            var result = _questionManager.UpdateQuestion(question);

            if (result == null)
            {
                return(BadRequest());
            }

            var response = Mapper.Map <QuestionResponse>(result);

            return(Ok(response));
        }
        public async Task <Question> Update(int id, QuestionRequest questionRequest)
        {
            var question = await _baseRepository.GetById(id);

            if (question == null)
            {
                throw new Exception("Not Found");
            }

            question.AnswerA   = questionRequest.AnswerA;
            question.AnswerB   = questionRequest.AnswerB;
            question.AnswerC   = questionRequest.AnswerC;
            question.AnswerD   = questionRequest.AnswerD;
            question.CorectAns = questionRequest.CorectAns;

            return(await _baseRepository.Update(question));
        }
        public async Task <IActionResult> SubmitNewQuestion([FromBody] QuestionRequest request)
        {
            if (request == null)
            {
                return(BadRequest(new
                {
                    success = false,
                    message = "Body cannot contain null"
                }));
            }

            var answers = new List <Answer>();

            foreach (var answer in request.AnswerOptions)
            {
                answers.Add(answer);
            }

            var question = new Question
            {
                QuestionString = request.QuestionString,
                AnswerOptions  = answers
            };

            try
            {
                await _context.Questions.AddAsync(question);

                await _context.SaveChangesAsync();

                int newQuestionId = question.Id;
                var questions     = new List <Question>()
                {
                    question
                };

                var response = GenerateQuestionResponse(questions);

                return(Created("/questions", response));
            }
            catch (Exception exception)
            {
                return(BadRequest(exception.ToString()));
            }
        }
Beispiel #25
0
        public async Task Update_Success()
        {
            var question = new Question
            {
                QuestionId = 1,
                Content    = "This is ... car?",
                AnswerA    = "a",
                AnswerB    = "an",
                AnswerC    = "that",
                AnswerD    = "this",
                CorectAns  = "a"
            };

            var questionUpdate = new QuestionRequest
            {
                Content   = "This is ... car?",
                AnswerA   = "my",
                AnswerB   = "an",
                AnswerC   = "that",
                AnswerD   = "this",
                CorectAns = "my"
            };
            await _questionRepository.Add(question);

            var questionService = new QuestionService(_questionRepository);

            var controller = new QuestionsController(questionService);

            //action
            var result = await controller.UpdateQuestion(1, questionUpdate);

            //course

            result.Should().NotBeNull();

            var response    = Assert.IsType <OkObjectResult>(result.Result);
            var returnValue = Assert.IsType <Question>(response.Value);

            Assert.Equal("This is ... car?", returnValue.Content);
            Assert.Equal("my", returnValue.AnswerA);
            Assert.Equal("an", returnValue.AnswerB);
            Assert.Equal("that", returnValue.AnswerC);
            Assert.Equal("this", returnValue.AnswerD);
            Assert.Equal("my", returnValue.CorectAns);
        }
        public void RequestFormTest_correctinfo()
        {
            BBC_HomePage HomePage = new BBC_HomePage(driver);

            var newsQuestionsPage = _bbcService.GetInTouchBBC(HomePage);

            var formRequest = new QuestionRequest
            {
                TextInput     = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc congue sapien non risus consequat luctus. Donec vulputate interdum massa amket.",
                NameInput     = "Vasia Pupkin",
                EmailInput    = "*****@*****.**",
                AgeInput      = "20",
                PostCodeInput = "04567",
            };

            _bbcService.FillQuestionForm(newsQuestionsPage.QuestionAskingForm, formRequest);

            Assert.AreEqual(newsQuestionsPage.NewsQuestionSiteAdress, driver.Url);
        }
Beispiel #27
0
        public async Task <ApiResult <string> > Create(QuestionRequest request)
        {
            var questions = new Questions()
            {
                QuestionContent = request.QuestionContent,
                ModuleId        = request.ModuleId,
                QuestionType    = request.QuestionType,
                DateCreated     = DateTime.Now,
            };
            var answer = new Answers()
            {
                A = request.A,
                B = request.B,
                C = request.C,
                D = request.D,
                CorrectAnswers = request.CorrectAnswers,
                AnswerExplain  = request.AnswerExplain,
                Question       = questions
            };

            _context.Questions.Add(questions);
            _context.Answers.Add(answer);
            var numRowChange = await _context.SaveChangesAsync();

            if (request.ExamId != 0)
            {
                var questionDetail = new Questiondetails()
                {
                    ExamId     = request.ExamId,
                    QuestionId = questions.Id,
                };
                _context.Questiondetails.Add(questionDetail);
                await _context.SaveChangesAsync();
            }
            if (numRowChange > 0)
            {
                return(new ApiResultSuccess <string>("inserted"));
            }
            else
            {
                return(new ApiResultErrors <string>("Faild"));
            }
        }
Beispiel #28
0
        public async Task <IActionResult> AddQuestionAsync([FromBody] QuestionRequest questionRequest)
        {
            QuestionResponse questionResponse = new QuestionResponse();

            try
            {
                await questionRequest.GetRequestedUserAsync(_dbContext);

                Question question = questionRequest?.Question;

                if (question == null)
                {
                    throw new Exception("Question is empty");
                }

                await _dbContext.Questions.AddAsync(question);

                await _dbContext.SaveChangesAsync();

                Question addedQuestion = await _dbContext.Questions
                                         .Include(q => q.Answers)
                                         .FirstAsync(q => q.Id == question.Id);

                Exam exam = await _dbContext.Exams.FindAsync(addedQuestion.ExamId);

                exam.Marks += addedQuestion.Marks;
                await _dbContext.SaveChangesAsync();

                questionResponse.Questions = new List <Question>()
                {
                    addedQuestion
                };

                questionResponse.IsSuccess = true;
            }
            catch (Exception ex)
            {
                questionResponse.Message = ex.Message;
            }

            return(StatusCode(questionResponse.Status, questionResponse));
        }
Beispiel #29
0
        public async Task PostListQuestion_Success()
        {
            var question1 = new QuestionRequest
            {
                Content   = "This is ... car?",
                AnswerA   = "a",
                AnswerB   = "an",
                AnswerC   = "that",
                AnswerD   = "this",
                CorectAns = "a"
            };

            var question2 = new QuestionRequest
            {
                Content   = "What your name?",
                AnswerA   = "Mr Nam",
                AnswerB   = "a",
                AnswerC   = "an",
                AnswerD   = "her",
                CorectAns = "Mr Nam"
            };

            var list = new List <QuestionRequest>();

            list.Add(question1);
            list.Add(question2);

            var questionService = new QuestionService(_questionRepository);

            var controller = new QuestionsController(questionService);

            //action
            var result = await controller.PostListQuestions(list);

            //course

            result.Should().NotBeNull();

            var total = await _questionRepository.GetAll();

            total.Should().HaveCount(2);
        }
Beispiel #30
0
        private static bool Question(IRequest message, ParticipatingInfo user, out IResponce handle)
        {
            var qHandler =
                Configure.Container.ResolveAll <IQuestionHandler>().SingleOrDefault(it => it.Accept(user));

            if (qHandler == null)
            {
                {
                    if (user.Completed())
                    {
                        handle = new QuestionRequest()
                        {
                            Message  = user.ToString() + @"
                    /new - ورود مجدد

                    /start    - شروع
                    ",
                            UserName = message.UserName
                        }
                    }
                    ;
                    else
                    {
                        handle = new QuestionRequest()
                        {
                            Message  = @"
                    /new - ورود مجدد

                    /start    - شروع
                    ",
                            UserName = message.UserName
                        }
                    };
                    return(true);
                }
            }
            handle = qHandler.Handle(user);
            return(true);

            return(false);
        }
    }