public void MappingTest()
        {
            //Arrange
            var dataStorage = new Mock<IDataStorage>();
            var entity = new Question {
                Id = 1,
                DataType = QuestionDataType.Integer,
                Value = "2",
                File = null
            };
            var updatedEntity = new Question {
                Id = 1,
                DataType = QuestionDataType.Integer,
                Value = "3",
                File = new Attachment()
            };
            var repository = new QuestionRepository(dataStorage.Object);

            dataStorage.Setup(ds => ds.GetData<Question>()).Returns(new List<Question> {entity});
            //Act
            repository.Edit(updatedEntity);
            //Assert
            //Values are equal
            Assert.That(entity.DataType, Is.EqualTo(updatedEntity.DataType));
            Assert.That(entity.Value, Is.EqualTo(updatedEntity.Value));
            Assert.That(entity.File, Is.EqualTo(updatedEntity.File));
        }
Exemplo n.º 2
0
        public ReportViewModel(int questionID, IDictionary<String, int> demoResponses, IDictionary<String, int> compareResponses)
        {
            this.questionID = questionID;

            this.demoResponses = demoResponses;
            this.compareResponses = compareResponses;
            var questionRepository = new QuestionRepository(NHibernateHelper.GetCurrentSession());
            Question question = questionRepository.GetQuestionByID<Question>(questionID);
            this.text = question.question;

            QuestionChart chart = question.comparisonChart;
            this.chartType = chart.GetQuestionChartType();

            this.valueType = chart.valueType;

            String[] coloursArray = chart.colours.Split(new char[] { ',', ' ' });

            String chartColours = "";
            int i = 0;
            foreach (String colour in coloursArray)
            {
                if (colour != "")
                {
                    chartColours += "'" + colour + "'";
                    if (i < coloursArray.Length - 1)
                    {
                        chartColours += ", ";
                    }
                    i++;
                }
            }
            this.chartColours = chartColours;
        }
        public void SetUp()
        {
            _fixture = new Fixture().Customize(new AutoMoqCustomization());
            _dataContext = new Mock<IDataContext>();

            _sut = new QuestionRepository(_dataContext.Object);
        }
 public void Start(UpdateClient update, QuestionRepository repository)
 {
     IPHostEntry ipHost = Dns.GetHostEntry("localhost");
     IPAddress ipAddr = ipHost.AddressList[0];
     IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, Properties.Settings.Default.Port);
     _sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         _sListener.Bind(ipEndPoint);
         _sListener.Listen(_clientCount);
         do
         {
             Socket handler = _sListener.Accept();
             _clientList.Add(new FakeClient(handler, update, _students, repository));
             update?.DynamicInvoke(_clientList[_clientList.Count - 1]);
             new Thread(()=>
             {
                 var client = _clientList[_clientList.Count - 1];
                 client.ReceiveMessage();
                 if (client.Mark == 0)
                 {
                     _clientList.Remove(client);
                     _connectedClient--;
                 }
             }) { IsBackground = true }.Start();
             _connectedClient++;
         } while (_connectedClient < _clientCount);
     }
     catch { throw; }
 }
Exemplo n.º 5
0
 public DataApi()
 {
     var dbContext = new InterviewQContext();
     Tests = new TestRepository(dbContext);
     Questions = new QuestionRepository(dbContext);
     DifficultyLevels = new DifficultyLevelRepository(dbContext);
     Catagories = new CatagoryRepository(dbContext);
 }
Exemplo n.º 6
0
 public QuestionBusiness(QuestionRepository questionRepo,
     ChoiceBusiness choiceBus,
     SysUserBusiness sysUserBus,
     SubjectBusiness subjectBus)
 {
     _questionRepo = questionRepo;
     _choiceBus = choiceBus;
     _sysUserBus = sysUserBus;
     _subjectBus = subjectBus;
 }
Exemplo n.º 7
0
 public DataAccess()
 {
     PollAppDBContext context = new PollAppDBContext();
     UserRepository = new UserRepository(context);
     CategoryRepository = new CategoryRepository(context);
     TokenRepository = new TokenRepository(context);
     QuestionRepository = new QuestionRepository(context);
     AnswerRepository = new AnswerRepository(context);
     FormRepository = new FormRepository(context);
     VotedFormsRepository = new VotedFormsRepository(context);
 }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            ThemeRepository themeRep = new ThemeRepository();
            QuestionRepository questRep = new QuestionRepository();

            Question q = new Question()
            {
                Text = "question qqq",
                ThemeId=11,
            };
            questRep.Add(q);

            Console.ReadKey();
        }
        public void InstantiateTheContext()
        {
            var dbCtxt = new InfoDigestContext("InfoDigestTests");

            try
            {
                QuestionRepository repo = new QuestionRepository(dbCtxt);
                repo.Add(new Question {QuestionText = "Yabba"});
                dbCtxt.SaveChanges();
            }
            catch (DbUpdateException e)
            {
                throw e;
            }
        }
 public ApplicationController(ISession session)
 {
     this.session = session;
     this.transaction = session.BeginTransaction();
     this.clientCodeRepository = new ClientCodeRepository(session);
     this.entityRepository = new EntityRepository(session);
     this.fieldsTemplateRepository = new FieldsTemplateRepository(session);
     this.messageRepository = new MessageRepository(session);
     this.participantRepository = new ParticipantRepository(session);
     this.pollRepository = new PollRepository(session);
     this.questionRepository = new QuestionRepository(session);
     this.reportRepository = new ReportRepository(session);
     this.responseRepository = new ResponseRepository(session);
     this.roleRepository = new RoleRepository(session);
     this.templateRepository = new TemplateRepository(session);
     this.userRepository = new UserRepository(session);
 }
Exemplo n.º 11
0
        public void ModifyAnswer_Successful()
        {
            var options = new DbContextOptionsBuilder <AskContext>()
                          .UseInMemoryDatabase(databaseName: MethodBase.GetCurrentMethod().Name)
                          .Options;

            using var context = new AskContext(options);
            IQuestionRepository questionRepository = new QuestionRepository(context);
            IAnswerRepository   answerRepository   = new AnswerRepository(context);

            //ACT
            DateTime date     = DateTime.Now;
            var      question = new QuestionTO {
                IsResolved = false, Message = "Je n'arrive pas à faire un test", Title = "Problème avec Tests", Date = date, AuthorId = 1
            };
            var question2 = new QuestionTO {
                IsResolved = false, Message = "Comment créer un projet MVC 6", Title = "MVC6", Date = date, AuthorId = 2
            };
            var question3 = new QuestionTO {
                IsResolved = false, Message = "Comment faire boucle foreach", Title = "foreach", Date = date, AuthorId = 2
            };
            var addedQuestion  = questionRepository.Create(question);
            var addedQuestion2 = questionRepository.Create(question2);
            var addedQuestion3 = questionRepository.Create(question3);

            context.SaveChanges();
            var answer = new AnswerTO {
                Message = "En fait, c'est facile il faut toujorus faire des tests", AuthorId = 2, AssociatedQuestion = addedQuestion,
            };
            var result = answerRepository.Create(answer);

            context.SaveChanges();
            //ACT
            result.Message = "Message modifié";
            var test = answerRepository.Modify(result);

            context.SaveChanges();

            //ASSERT
            Assert.AreEqual("Message modifié", test.Message);
        }
Exemplo n.º 12
0
        private async void SubmitQuestion()
        {
            Task task = Task.Run(async() =>
            {
                var _question = await SweetAlertMessage.InputDialog(type: "textarea", PlaceholderText: "Type your survey question here....");
                if (!string.IsNullOrEmpty(_question))
                {
                    var question = await QuestionRepository.AddQuestionAsync(new Coronassist.Web.Shared.Models.Question
                    {
                        SurveyQuestion = _question,
                        IsActive       = true,
                        SurveyId       = SurveyId
                    });

                    this.Survey.Questions.Add(question);
                    await SweetAlertMessage.SuccessMessage();
                    Open = false;
                    StateHasChanged();
                }
            });
        }
Exemplo n.º 13
0
        public async Task Test_Get_Question()
        {
            var questionToGet = new Question
            {
                Title  = "Unit Test Question",
                UserId = 1,
                Text   = "Question Text"
            };

            var mockBaseRepo = new Mock <IBaseRepository <Question> >();

            mockBaseRepo.Setup(m => m.GetAsync(It.IsAny <int>()))
            .ReturnsAsync(questionToGet);


            var questionRepo = new QuestionRepository(mockBaseRepo.Object);
            var dbQuestion   = await questionRepo.GetQuestionAsync(questionToGet.Id);

            Assert.NotNull(dbQuestion);
            Assert.Equal(questionToGet.Id, dbQuestion.Id);
        }
Exemplo n.º 14
0
        public async Task Test_Create_Question()
        {
            var newQuestion = new Question
            {
                Id     = 1,
                Title  = "Unit Test Question",
                UserId = 1,
                Text   = "Question Text"
            };

            var mockBaseRepo = new Mock <IBaseRepository <Question> >();

            mockBaseRepo.Setup(m => m.CreateAsync(It.IsAny <Question>()))
            .ReturnsAsync(newQuestion);

            var questionRepo = new QuestionRepository(mockBaseRepo.Object);
            var dbQuestion   = await questionRepo.CreateQuestionAsync(newQuestion);

            Assert.NotNull(dbQuestion);
            Assert.Equal(1, dbQuestion.Id);
        }
Exemplo n.º 15
0
        /// <summary>
        /// 回复学生疑问信息
        /// </summary>
        /// <param name="webModel">回复信息页视图Model</param>
        /// <param name="context">数据库上下文对象</param>
        /// <returns></returns>
        public async Task <bool> ReplyQuestionAsync(QuestionReplyViewModel webModel, ApplicationDbContext context)
        {
            try
            {
                //Update Question Data
                QuestionRepository.ReplyQuestionAsync(webModel, context);

                //Add Operate Information
                var operate = string.Format("回复学生疑问信息,学生疑问编号:{0}", webModel.Id);
                PSURepository.InsertRecordAsync("Question", "QuestionDomain", "ReplyQuestionAsync", operate, (short)PSURepository.OperateCode.Update, Convert.ToInt64(webModel.Id), context);

                var index = await context.SaveChangesAsync();

                return(index == 2);
            }
            catch (Exception ex)
            {
                _logger.LogError("回复学生疑问失败:{0},\r\n内部错误信息:{1}", ex.Message, ex.InnerException.Message);
                return(false);
            }
        }
Exemplo n.º 16
0
        public HttpResponseMessage DeleteQuestion(int id)
        {
            Question question = QuestionRepository.Get(t => t.QuestionId == id);

            if (question == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            QuestionRepository.Delete(question);

            try
            {
                unitOfWork.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
            }
            return(Request.CreateResponse(HttpStatusCode.OK, question));
        }
Exemplo n.º 17
0
        public void GetResponse_AddNewResponseThenRetrieveAddedResponse_ReturnAddedResponseNotNull()
        {
            //ARRANGE
            var options       = new DbContextOptionsBuilder().UseInMemoryDatabase(MethodBase.GetCurrentMethod().Name).Options;
            var context       = new ApplicationContext(options);
            var repository    = new ResponseRepository(context);
            var repositoryQst = new QuestionRepository(context);
            //Question
            var question = new Question
            {
                Message   = "Test question",
                PostDate  = DateTime.Now,
                State     = QuestionState.Waiting,
                IsDeleted = false
            };
            var addedQuestion = repositoryQst.Insert(question);

            context.SaveChanges();
            //Responses
            var response = new Response
            {
                Question       = addedQuestion,
                DateOfResponse = DateTime.Now,
                IsDeleted      = false,
                Responder      = new ApplicationUser {
                    Id = "aaaaabbbbbcccccdddd", Email = "*****@*****.**"
                }
            };
            var addedResponse = repository.Insert(response);

            context.SaveChanges();
            //ACT
            var result = repository.Get(addedResponse.Id);

            //ASSERT
            Assert.IsNotNull(addedResponse);
            Assert.AreNotEqual(0, addedResponse.Id);
            Assert.IsNotNull(result);
            Assert.AreEqual("aaaaabbbbbcccccdddd", result.Responder.Id);
        }
Exemplo n.º 18
0
        public void InsertAnswer_CorrectFormat()
        {
            var options = new DbContextOptionsBuilder <QAndAContext>().UseInMemoryDatabase(MethodBase.GetCurrentMethod().Name).Options;
            var context = new QAndAContext(options);
            IAnswerRepository   ARepo = new AnswerRepository(context);
            IQuestionRepository QRepo = new QuestionRepository(context);

            var question = new QuestionTO
            {
                Questioning  = "Maybe it's working",
                CreationDate = DateTime.Now,
                State        = State.Pending,
                IsArchived   = false,
                LostSoul     = new UserTO {
                    FirstName = "Call me", LastName = "Kevin"
                }
            };

            var addedQuestion = QRepo.Insert(question);

            QRepo.Save();

            var answer = new AnswerTO
            {
                Answering  = "No shit Sherlock",
                AnswerTime = DateTime.Now.AddHours(1),
                QuestionId = addedQuestion.Id,
                Savior     = new UserTO {
                    FirstName = "Dr", LastName = "Watson"
                }
            };

            var addedAnswer = ARepo.Insert(answer);

            ARepo.Save();

            Assert.AreEqual(1, addedAnswer.QuestionId);
            Assert.AreEqual(1, QRepo.Get(addedAnswer.QuestionId).Answers.Count());
            Assert.AreEqual("No shit Sherlock", addedAnswer.Answering);
        }
Exemplo n.º 19
0
        public void UpdateResponse_CorrectResponseSubmitted_ReturnUpdatedResponse()
        {
            //ARRANGE
            var options       = new DbContextOptionsBuilder().UseInMemoryDatabase(MethodBase.GetCurrentMethod().Name).Options;
            var context       = new ApplicationContext(options);
            var repository    = new ResponseRepository(context);
            var repositoryQst = new QuestionRepository(context);
            //Question
            var question = new Question
            {
                Message   = "Test question",
                PostDate  = DateTime.Now,
                State     = QuestionState.Waiting,
                IsDeleted = false
            };
            var addedQuestion = repositoryQst.Insert(question);

            context.SaveChanges();
            //Responses
            var response = new Response
            {
                Question       = addedQuestion,
                DateOfResponse = DateTime.Now,
                IsDeleted      = false,
                Responder      = new ApplicationUser {
                    Id = "aaaaabbbbbcccccdddd", Email = "*****@*****.**"
                }
            };
            var addedResponse = repository.Insert(response);

            context.SaveChanges();
            //ACT
            addedResponse.IsDeleted = true;
            var result = repository.Update(addedResponse);

            repository.Save();
            //ASSERT
            Assert.IsNotNull(result);
            Assert.IsTrue(result.IsDeleted);
        }
Exemplo n.º 20
0
        private async void DeleteQuestion(int QuestionId)
        {
            var confirm = await SweetAlertMessage.ConfirmDialogAsync(Text : "Delete selected question");

            if (confirm == "Yes")
            {
                var deleted = await QuestionRepository.DeleteQuestion(QuestionId);

                if (deleted)
                {
                    var deleteItem = Survey.Questions.FirstOrDefault(p => p.QuestionId == QuestionId);
                    Survey.Questions.Remove(deleteItem);
                    await SweetAlertMessage.SuccessMessage();

                    StateHasChanged();
                }
                else
                {
                    await SweetAlertMessage.ErrorMessage();
                }
            }
        }
Exemplo n.º 21
0
        public HttpResponseMessage PostQuestion(object questionobj)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var      json           = questionobj;
            Question question       = js.Deserialize <Question>(json.ToString());

            question.Active    = true;
            question.CreatedOn = DateTime.Now;
            if (ModelState.IsValid)
            {
                QuestionRepository.Add(question);
                unitOfWork.SaveChanges();
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, question);
                response.Content = new StringContent(question.QuestionId.ToString());
                return(response);
            }
            else
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors);
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
Exemplo n.º 22
0
        //private readonly IQuestionAppService _questionAppService;

        //public RespondentUiService(IQuestionAppService questionAppService)
        //{
        //    _questionAppService = questionAppService;
        //}

        public async Task <QuestionViewModel> AddAsync(QuestionViewModel obj)
        {
            try
            {
                var optionsBuilder = new DbContextOptionsBuilder <EvaluationContext>();
                using (var evaluationContext = new EvaluationContext(optionsBuilder.Options))
                {
                    var unitOfWork         = new UnitOfWork(evaluationContext);
                    var questionRepository = new QuestionRepository(evaluationContext);
                    var questionService    = new QuestionService(questionRepository);
                    var questionAppService = new QuestionAppService(questionService, unitOfWork);

                    return(await questionAppService.AddAsync(obj));
                }
            }
            catch (Exception e)
            {
                throw new FaultException(e.Message);
            }

            //return await _questionAppService.AddAsync(obj);
        }
        protected void btnA3_Click(object sender, EventArgs e)
        {
            AnswerRepository   aRep = new AnswerRepository();
            QuestionRepository qRep = new QuestionRepository();

            if (isAnswerCorrect(btnA3, aRep))
            {
                Question   q = qRep.getQuestionById(Convert.ToInt32(hiddenQId.Value));
                List <int> playedQuestions = getPlayedQuestions();
                playedQuestions.Add(q.Id);
                Session["PlayedQuestions"]   = playedQuestions;
                Session["QuestionsAnswered"] = getQuestionsAnswered() + 1;
                btnA3.BackColor = System.Drawing.Color.Green;
                refreshAfterSeconds();
            }
            else
            {
                btnA3.BackColor = System.Drawing.Color.Red;
                getRightAnswerButton().BackColor = System.Drawing.Color.Green;
                refreshAfterSecondsWhenLost();
            }
        }
        //=======================================================================================

        public IActionResult Detail(Guid?id)
        {
            using (var client = new QuestionRepository())
            {
                QuestionEntity entity = client.FindById(id);

                if (entity == null)
                {
                    return(View("NotFoundPageView", new NotFoundPageView
                    {
                        Action = "Detail",
                        Controller = "Question",
                        Title = "Выберите один из вопросов",
                        Message = "Не удалось найти выбранный вопрос",
                        EntitySelectList = new SelectList(client.TakeAll(), "QuestionId", "QuestionMessage"),
                        ReturnUrl = "Question/ViewQuestions"
                    }));
                }

                return(View(entity.AsDetailView()));
            }
        }
Exemplo n.º 25
0
        public void Init()
        {
            _repository           = new QuestionRepository();
            _userRepository       = new UserRepository();
            _missionSetRepository = new MissionSetRepository();
            _missionRepository    = new MissionRepository();
            _service = new QuestionService(
                _repository,
                _userRepository,
                _missionRepository,
                new AssignmentService(_missionSetRepository, _missionRepository));

            var principal = new ClaimsPrincipal();

            principal.AddIdentity(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Sid, "User1Id") }));
            _controller = new QuestionController(_service, new AppCountersService(new AppCountersRepository()))
            {
                User
                    =
                        principal
            };
        }
 public IActionResult Index()
 {
     using (var client = new ApplicationDbContext())
     {
         using (var disciplineRepository = new DisciplineRepository(client))
         {
             using (var threadRepository = new ThreadRepository(client))
             {
                 using (var questionRepository = new QuestionRepository(client))
                 {
                     return(View(new RepositoryView
                     {
                         QuestionViews = questionRepository.TakeAllView(),
                         ThreadViews = threadRepository.TakeAllView(),
                         DisciplineViews = disciplineRepository.TakeAllView(),
                         /*TestViews = client.T.Take(10).ToList().Select(q => new QuestionView()).ToList(),*/
                     }));
                 }
             }
         }
     }
 }
        public void Add_Question_Success()
        {
            BitcoinShowDBContext context = DbContextFactory.GetContext();

            var options = RandomOptions(4).ToList();

            options.ForEach(o =>
            {
                context.Options.Add(o);
            });
            context.SaveChanges();

            QuestionRepository repository = new QuestionRepository(context);
            Question           question   = new Question();

            question.Answer = context.Options.First();
            question.Title  = "Test question";
            question.Level  = LevelEnum.Hard;

            repository.Add(question);
            Assert.True(question.Id > 0);
        }
        public void Get_Question_Not_Found_Error()
        {
            BitcoinShowDBContext context = DbContextFactory.GetContext();

            for (int i = 0; i < 10; i++)
            {
                context.Questions.Add(new Question
                {
                    Title  = $"Random Question {i + 1}",
                    Answer = new Option {
                        Id = i, Text = $"Random Option {i}"
                    }
                });
            }
            context.SaveChanges();

            QuestionRepository repository = new QuestionRepository(context);

            Question actual = repository.Get(50);

            Assert.Null(actual);
        }
Exemplo n.º 29
0
        private VitalsFormData AddVitalsFormData(Form form)
        {
            var formData = new VitalsFormData()
            {
                Form       = form,
                ActualTime = new Question {
                    Caption = "Actual Time", DataType = QuestionDataType.Date, Form = form
                },
                Height = new Question {
                    Caption = "Height", DataType = QuestionDataType.Number, Form = form
                },
                Weight = new Question {
                    Caption = "Weight", DataType = QuestionDataType.Number, Form = form
                },
                Temperature = new Question {
                    Caption = "Temperature", DataType = QuestionDataType.Number, Form = form
                },
                HeartRate = new Question {
                    Caption = "Heart Rate", DataType = QuestionDataType.Integer, Form = form
                },
                BloodPressureSystolic = new Question {
                    Caption = "Systolic Blood Pressure, mmHg", DataType = QuestionDataType.String, Form = form
                },
                BloodPressureDiastolic = new Question {
                    Caption = "Diastolic Blood Pressure, mmHg", DataType = QuestionDataType.String, Form = form
                }
            };

            VitalsFormDataRepository.Add(formData);
            QuestionRepository.Add(formData.ActualTime);
            QuestionRepository.Add(formData.Height);
            QuestionRepository.Add(formData.Weight);
            QuestionRepository.Add(formData.Temperature);
            QuestionRepository.Add(formData.HeartRate);
            QuestionRepository.Add(formData.BloodPressureSystolic);
            QuestionRepository.Add(formData.BloodPressureDiastolic);
            return(formData);
        }
Exemplo n.º 30
0
        public ReportViewModel(int questionID, IDictionary<String, int> responses, IList<String> correct)
        {
            this.questionID = questionID;
            this.responses = responses;
            var questionRepository = new QuestionRepository(NHibernateHelper.GetCurrentSession());
            Question question = questionRepository.GetQuestionByID<Question>(questionID);
            if (question.correctAnswerIndicator.active)
            {
                this.correct = correct;
            }
            else
            {
                this.correct = null;
            }
            this.text = question.question;

            QuestionChart chart = question.resultsChart;
            this.chartType = chart.GetQuestionChartType();

            this.valueType = chart.valueType;

            String[] coloursArray = chart.colours.Split(new char[] {',', ' '});

            String chartColours = "";
            int i = 0;
            foreach (String colour in coloursArray) {
                if (colour != "")
                {
                    chartColours += "'" + colour + "'";
                    if (i < coloursArray.Length - 1)
                    {
                        chartColours += ", ";
                    }
                    i++;
                }
            }
            this.chartColours = chartColours;
        }
Exemplo n.º 31
0
        public void GetAnswer_Correct()
        {
            var options = new DbContextOptionsBuilder <QAndAContext>().UseInMemoryDatabase(MethodBase.GetCurrentMethod().Name).Options;
            var context = new QAndAContext(options);
            IAnswerRepository   ARepo = new AnswerRepository(context);
            IQuestionRepository QRepo = new QuestionRepository(context);

            var question = new QuestionTO
            {
                Questioning  = "Not hungry",
                CreationDate = DateTime.Now,
                State        = State.Pending,
                IsArchived   = false,
                LostSoul     = new UserTO {
                    FirstName = "Don't wanna", LastName = "Eat"
                }
            };

            var addedQuestion = QRepo.Insert(question);

            QRepo.Save();

            var answer = new AnswerTO
            {
                Answering  = "must be the donuts",
                AnswerTime = DateTime.Now.AddHours(1),
                QuestionId = addedQuestion.Id,
                Savior     = new UserTO {
                    FirstName = "Any", LastName = "Officer"
                }
            };

            var addedAnswer = ARepo.Insert(answer);

            ARepo.Save();

            Assert.AreEqual("must be the donuts", ARepo.Get(addedAnswer.Id).Answering);
        }
Exemplo n.º 32
0
        public void ModifyAnswer_ProvidingNonExistingId_ThrowException()
        {
            var options = new DbContextOptionsBuilder <AskContext>()
                          .UseInMemoryDatabase(databaseName: MethodBase.GetCurrentMethod().Name)
                          .Options;

            using var context = new AskContext(options);
            IQuestionRepository questionRepository = new QuestionRepository(context);
            IAnswerRepository   answerRepository   = new AnswerRepository(context);

            DateTime date     = DateTime.Now;
            var      question = new QuestionTO {
                IsResolved = false, Message = "Je n'arrive pas à faire un test", Title = "Problème avec Tests", Date = date, AuthorId = 1
            };
            var addedQuestion = questionRepository.Create(question);

            context.SaveChanges();
            var answer = new AnswerTO {
                Id = 16783, Message = "En fait, c'est facile il faut toujorus faire des tests", AuthorId = 2, AssociatedQuestion = addedQuestion,
            };

            Assert.ThrowsException <KeyNotFoundException>(() => answerRepository.Modify(answer));
        }
        public void Update_Question_With_Title_Greater_Than_Max_Error()
        {
            var option = new Option {
                Text = "Update_Question_With_Title_Greater_Than_Max_Error Option"
            };
            var question = new Question
            {
                Title  = "Update_Question_With_Title_Greater_Than_Max_Error",
                Answer = option
            };
            BitcoinShowDBContext context = DbContextFactory.GetContext();

            context.Questions.Add(question);
            context.SaveChanges();

            QuestionRepository repository = new QuestionRepository(context);

            question.Title = new String('a', 201);
            ArgumentOutOfRangeException ex = Assert.Throws <ArgumentOutOfRangeException>(() => repository.Update(question));

            Assert.NotNull(ex);
            Assert.Equal(nameof(question.Title), ex.ParamName);
        }
Exemplo n.º 34
0
        public void InsertQuestion_CorrectFormat()
        {
            var options = new DbContextOptionsBuilder <QAndAContext>().UseInMemoryDatabase(MethodBase.GetCurrentMethod().Name).Options;
            var context = new QAndAContext(options);
            IQuestionRepository QRepo = new QuestionRepository(context);

            var question = new QuestionTO
            {
                Questioning  = "Maybe it's working",
                CreationDate = DateTime.Now,
                State        = State.Pending,
                IsArchived   = false,
                LostSoul     = new UserTO {
                    FirstName = "Call me", LastName = "Kevin"
                }
            };

            var result = QRepo.Insert(question);

            QRepo.Save();

            Assert.AreEqual("Maybe it's working", result.Questioning);
        }
        public void Update_Question_Without_Answer_Error()
        {
            var option = new Option {
                Text = "Update_Question_Without_Answer_Error Option"
            };
            var question = new Question
            {
                Title  = "Update_Question_Without_Answer_Error",
                Answer = option
            };
            BitcoinShowDBContext context = DbContextFactory.GetContext();

            context.Questions.Add(question);
            context.SaveChanges();

            QuestionRepository repository = new QuestionRepository(context);

            question.Answer = null;
            ArgumentNullException ex = Assert.Throws <ArgumentNullException>(() => repository.Update(question));

            Assert.NotNull(ex);
            Assert.Equal(nameof(question.Answer), ex.ParamName);
        }
Exemplo n.º 36
0
 public QuestionService(
     UnitOfWork unitOfWork,
     IMapper mapper,
     TagRepository tagRepository,
     QuestionRepository questionRepository,
     QuestionTagRepository questionTagRepository,
     UserRepository userRepository,
     AnswerRepository answerRepository,
     UserQuestionRepository userQuestionRepository,
     UserAnswerRepository userAnswerRepository,
     CommentRepository commentRepository)
 {
     _commentRepository      = commentRepository;
     _userAnswerRepository   = userAnswerRepository;
     _userQuestionRepository = userQuestionRepository;
     _answerRepository       = answerRepository;
     _userRepository         = userRepository;
     _questionTagRepository  = questionTagRepository;
     _questionRepository     = questionRepository;
     _tagRepository          = tagRepository;
     _mapper     = mapper;
     _unitOfWork = unitOfWork;
 }
        public void Question_ArchiveAlreadyArchived()
        {
            var options = new DbContextOptionsBuilder <QAndAContext>().UseInMemoryDatabase(MethodBase.GetCurrentMethod().Name).Options;
            var context = new QAndAContext(options);
            IQuestionRepository QRepo = new QuestionRepository(context);

            var question = new QuestionTO
            {
                Questioning  = "Crèpes sucré ou salé ?",
                CreationDate = DateTime.Now,
                State        = State.Pending,
                IsArchived   = true,
                LostSoul     = new UserTO {
                    FirstName = "Top", LastName = "Chef"
                }
            };

            var test = QRepo.Insert(question);

            QRepo.Save();

            Assert.ThrowsException <ArgumentException>(() => QRepo.Archive(test));
        }
        public async Task <CreateQuestionResult> CreateQuestionAsync(CreateQuestionCommand command)
        {
            ThrowIfDisposed();

            string         questionToken  = GenerateToken();
            QuestionEntity questionEntity = new QuestionEntity()
            {
                Description       = command.Description,
                Name              = command.Name,
                EmailAddress      = command.Email,
                IsClosed          = false,
                IsVerified        = false,
                CreateDateTimeUTC = DateTime.UtcNow,
                Token             = questionToken
            };

            using (var transaction = QuestionRepository.Context.Database.BeginTransaction())
            {
                try
                {
                    await QuestionRepository.CreateAsync(questionEntity, CancellationToken);

                    var emailEntity = EmailGeneratorService.GenerateVerifyQuestionEmail(questionEntity);
                    questionEntity.Email = emailEntity;
                    await QuestionRepository.UpdateAsync(questionEntity, CancellationToken);

                    transaction.Commit();
                }
                catch (Exception exception)
                {
                    string errorMesssage = "Error while saving question";
                    Logger.LogError(exception, errorMesssage);
                    return(new CreateQuestionResult(new Error(errorMesssage, errorMesssage)));
                }
            }
            return(new CreateQuestionResult(questionEntity.QuestionId));
        }
Exemplo n.º 39
0
        public IHttpActionResult Get(int id)
        {
            try
            {
                // get questions
                var questionRepository = new QuestionRepository();
                var surveyQuestions    = questionRepository.GetQuestions(id);

                // get options
                var questionOptionsRepository  = new QuestionOptionRepository();
                var surveyQuestionsWithOptions = questionOptionsRepository.GetQuestionOptions(surveyQuestions);

                if (surveyQuestionsWithOptions == null)
                {
                    return(NotFound());
                }

                return(Ok(surveyQuestionsWithOptions));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        public void Get_Question_Success()
        {
            BitcoinShowDBContext context = DbContextFactory.GetContext();

            for (int i = 0; i < 98; i++)
            {
                context.Questions.Add(new Question
                {
                    Title  = $"Random Question {i + 1}",
                    Answer = new Option {
                        Id = i, Text = $"Random Option {i}"
                    },
                    Level = LevelEnum.VeryHard
                });
            }
            context.SaveChanges();

            QuestionRepository repository = new QuestionRepository(context);

            Question actual = repository.Get(50);

            Assert.NotNull(actual);
            Assert.NotNull(actual.Answer);
        }
Exemplo n.º 41
0
        private static void Main(string[] args)
        {
            var repository       = new QuestionRepository();
            var questionComposer = new QuestionComposer(repository);

            PrintAppInformation();

            while (true)
            {
                Console.Write("INPUT QUESTION TYPE:");

                var line = Console.ReadLine();

                if (line == "end")
                {
                    Console.WriteLine("THANKS FOR PLAYING!");
                    break;
                }

                var questionType = (QuestionType)Enum.Parse(typeof(QuestionType), line);
                var result       = questionComposer.ReturnQuestion(questionType);
                Console.WriteLine(result);
            }
        }
 public QuestionOption GetOptionByResponse(int responseID, int questionID)
 {
     var questionRepository = new QuestionRepository(session);
     IList<QuestionOption> options = questionRepository.GetQuestionByID<MultipleChoiceQuestion>(questionID).options;
     return (from item in options where item.responses.Any(r => r.responseID == responseID) select item).FirstOrDefault();
 }
Exemplo n.º 43
0
        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
            //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
            log4net.Config.XmlConfigurator.Configure();

            IQuestionRepository questionRepository = new QuestionRepository();
            ISearchEngineService searchEngine = new SearchEngineService(questionRepository);

            //ThreadStart ts = new ThreadStart(searchEngine.BuildIndex);

            Thread thread = new Thread(searchEngine.BuildIndex);
            thread.Start();
        }
Exemplo n.º 44
0
        // Only call this on MCQ questions
        public virtual IList<String> getCorrect()
        {
            var questionRepository = new QuestionRepository(NHibernateHelper.GetCurrentSession());
            MultipleChoiceQuestion multipleQuestion = questionRepository.GetQuestionByID<MultipleChoiceQuestion>(this.questionID);
            IList<String> correctOptions = new List<String>();

            if (multipleQuestion != null)
            {
                foreach (var option in multipleQuestion.options)
                {
                    // If the answer is correct, store it
                    if (option.correctCurrent)
                    {
                        correctOptions.Add(option.answer);
                    }
                }
            }
            return correctOptions;
        }
Exemplo n.º 45
0
 public QuestionController()
 {
     this._questionRepository = new QuestionRepository();
 }
 public double onlytotal()
 {
     var questionRepository = new QuestionRepository(NHibernateHelper.GetCurrentSession());
     double total = 0;
     IList<Question> multip = poll.questions.Where(m => m.type != QuestionType.Alphanumeric && m.type != QuestionType.Numeric).ToList();
     IList<MultipleChoiceQuestion> multi = new List<MultipleChoiceQuestion>();
     foreach (Question multipl in multip) multi.Add(questionRepository.GetQuestionByID<MultipleChoiceQuestion>(multipl.questionID));
     foreach (MultipleChoiceQuestion ques in multi)
     {
         foreach (QuestionOption option in ques.options)
         {
             total += option.pointsCurrent;
         }
     }
     return total;
 }
 public int participating(Participant participant)
 {
     var questionRepository = new QuestionRepository(NHibernateHelper.GetCurrentSession());
     IList<Question> shortre = poll.questions.Where(m => m.type == QuestionType.Alphanumeric || m.type == QuestionType.Numeric).ToList();
     IList<Question> multip = poll.questions.Where(m => m.type != QuestionType.Alphanumeric && m.type != QuestionType.Numeric).ToList();
     IList<ShortResponseQuestion> shortr = new List<ShortResponseQuestion>();
     IList<MultipleChoiceQuestion> multi = new List<MultipleChoiceQuestion>();
     foreach (Question shorty in shortre) shortr.Add(questionRepository.GetQuestionByID<ShortResponseQuestion>(shorty.questionID));
     foreach (Question multipl in multip) multi.Add(questionRepository.GetQuestionByID<MultipleChoiceQuestion>(multipl.questionID));
     int total = shortr.Count() + multi.Count();
     int answered = 0;
     foreach (ShortResponseQuestion ques in shortr)
         foreach (ShortResponse res in ques.responses) if (res.participant == participant) answered++;
     foreach (MultipleChoiceQuestion ques in multi)
     {
         bool breaking = false;
         foreach (QuestionOption option in ques.options)
         {
             foreach (OptionResponse res in option.responses) if (res.participant == participant) { answered++; breaking = true; break; }
             if (breaking) break;
         }
     }
     return answered;
 }
Exemplo n.º 48
0
        public int[] GetQuestionResults(int questionID)
        {
            var pollRepository = new PollRepository(session);
            var questionRepository = new QuestionRepository(session);
            var question = questionRepository.GetQuestionByID<Question>(questionID);
            IDictionary<String, int> responses = new Dictionary<String, int>();
            IList<String> correctOptions = new List<String>();
            int[] responseStatistics = new int[2];
            var poll = pollRepository.GetPollContainingQuestion(question);

            if (question.type == QuestionType.Numeric)
            {
                // If the question is numeric
                var numericQuestion = questionRepository.GetQuestionByID<NumericQuestion>(questionID);

                int numCorrect = 0;
                int numIncorrect = 0;

                foreach (var response in numericQuestion.responses)
                {

                    // Check if the answer is correct
                    if ((Convert.ToInt32(response.response) < numericQuestion.lessThan) &&
                        (Convert.ToInt32(response.response) > numericQuestion.greaterThan))
                    {
                        numCorrect++;
                    }
                    else
                    {
                        numIncorrect++;
                    }
                }

                responses.Add("Correct [" + numericQuestion.greaterThan.ToString() +
                            " - " + numericQuestion.lessThan.ToString() + "]", numCorrect);
                responses.Add("Incorrect", numIncorrect);
                responseStatistics[0] = numCorrect + numIncorrect;
                responseStatistics[1] = numCorrect;
            }
            else if (question.type == QuestionType.Alphanumeric)
            {
                // If the question is alphanumeric
                var alphaQuestion = questionRepository.GetQuestionByID<AlphanumericQuestion>(questionID);

                //  Get correct responses
                int numCorrect = 0;
                int numIncorrect = 0;
                int total = 0;

                foreach (var response in alphaQuestion.responses)
                {

                    foreach (var answer in alphaQuestion.answers)
                    {
                        if (response.response.Equals(answer.answer))
                        {
                            numCorrect++;
                        }
                    }
                    total++;
                }

                // Build a string of correct answers
                String correctAnswers = "";
                foreach (var answer in alphaQuestion.answers)
                {
                    if (correctAnswers != "")
                    {
                        correctAnswers += ", ";
                    }
                    correctAnswers += answer.answer;
                }

                responses.Add("Correct [" + correctAnswers + "]", numCorrect);
                numIncorrect = total - numCorrect;
                responses.Add("Incorrect", numIncorrect);
                responseStatistics[0] = total;
                responseStatistics[1] = numCorrect;
            }
            else
            {
                var multipleQuestion = questionRepository.GetQuestionByID<MultipleChoiceQuestion>(questionID);
                int numCorrect = 0;
                int total = 0;

                foreach (var option in multipleQuestion.options)
                {
                    total += option.responses.Count;
                    if (option.correctCurrent)
                    {
                        numCorrect += option.responses.Count;
                    }
                }
                total = total / multipleQuestion.allowedAnswers;
                numCorrect = numCorrect / multipleQuestion.allowedAnswers;
                responseStatistics[0] = total;
                responseStatistics[1] = numCorrect;
            }
            return responseStatistics;
        }
 public String points(Participant participant)
 {
     var questionRepository = new QuestionRepository(NHibernateHelper.GetCurrentSession());
     double points=0;
     double total = 0;
     IList<Question> multip = poll.questions.Where(m => m.type != QuestionType.Alphanumeric && m.type != QuestionType.Numeric).ToList();
     IList<MultipleChoiceQuestion> multi = new List<MultipleChoiceQuestion>();
     foreach (Question multipl in multip) multi.Add(questionRepository.GetQuestionByID<MultipleChoiceQuestion>(multipl.questionID));
     foreach (MultipleChoiceQuestion ques in multi)
     {
         foreach (QuestionOption option in ques.options)
         {
             total += option.pointsCurrent;
             foreach (OptionResponse res in option.responses) if (res.participant == participant) points += option.pointsCurrent;
         }
     }
     return points + "/" + total;
 }