public void Update(QuizModel model)
        {
            var entity = _quizRepository.FindIncluding(q => q.Id == model.Id, q => q.Course, q => q.QuizPages);

            if (entity == null) return;

            entity.Title = model.Title;

            entity.CourseId = model.CourseId;

            #region Manage QuizPages

            foreach (var m in model.QuizPages.Where(m => m.Id <= 0))
            {
                m.QuizId = model.Id;
            }
            foreach (var quizPage in model.QuizPages)
            {
                _quizPagesRepository.InsertOrUpdate(_modelFactory.MapToDomain<QuizPageCreateModel, QuizPage>(quizPage, null));
            }

            foreach (var m in entity.QuizPages.Where(y => model.QuizPages.FirstOrDefault(x => x.Id == y.Id) == null))
            {
                _quizPagesRepository.Delete(m.Id);
            }

            _quizPagesRepository.Save();

            #endregion

            _quizRepository.Update(entity);

            _quizRepository.Save();
        }
Пример #2
0
        public IActionResult Quiz(QuizModel model)
        {
            if (ModelState.IsValid)
            {
                var dogs   = _repository.GetToBeAdpoted();
                var result = new QuizResultModel();
                if (dogs.Count == 0)
                {
                    return(View("QuizResult", result));
                }
                var dict = new Dictionary <Dog, int>();
                foreach (var dog in dogs)
                {
                    dict[dog] = 0;
                }

                foreach (var dog in dogs)
                {
                    if (dog.Size == model.Size)
                    {
                        dict[dog] += 3;
                    }
                    else if (dog.Size == model.Size + 1 || dog.Size == model.Size - 1)
                    {
                        dict[dog] += 1;
                    }
                    if (dog.HairLenght == model.HairLenght)
                    {
                        dict[dog] += 3;
                    }
                    else if (dog.HairLenght == model.HairLenght + 1 || dog.HairLenght == model.HairLenght - 1)
                    {
                        dict[dog] += 1;
                    }
                    if (dog.Gender == model.Gender)
                    {
                        dict[dog] += 3;
                    }
                    if (dog.GetAge().Equals(model.Age))
                    {
                        dict[dog] += 2;
                    }
                }

                var max = dict.Values.Max();

                foreach (var key in dict.Keys)
                {
                    if (dict[key].Equals(max))
                    {
                        result.Doggies.Add(new PartialDogInfoModel(key));
                    }
                }
                return(View("QuizResult", result));
            }
            return(View(model));
        }
        public IActionResult CreateQuiz([FromBody] QuizModel quizModel)
        {
            try
            {
                if (this.User.Identity.IsAuthenticated)
                {
                    if (quizModel != null && !String.IsNullOrEmpty(quizModel.QuizName))
                    {
                        int maxNumer = _context.Quiz.Select(q => q.QuizNumber).Max();

                        using (SqlConnection connection = new SqlConnection(connectionString))
                        {
                            connection.Open();
                            SqlTransaction transaction = connection.BeginTransaction("UpdateQuestion");
                            SqlCommand     command     = new SqlCommand();
                            try
                            {
                                command             = connection.CreateCommand();
                                command.CommandText = "INSERT INTO Quiz (QuizName,CategoryId,QuizNumber) VALUES (@v1,@v2,@v3)";
                                command.Parameters.AddWithValue("@v1", quizModel.QuizName);
                                command.Parameters.AddWithValue("@v2", quizModel.CategoryId);
                                command.Parameters.AddWithValue("@v3", maxNumer + 1);
                                command.Transaction = transaction;
                                command.Connection  = connection;

                                command.ExecuteNonQuery();
                                transaction.Commit();
                                connection.Close();
                                return(Json(new { Result = true, Message = "Quiz został utworzony." }));
                            }
                            catch (Exception)
                            {
                                try
                                {
                                    transaction.Rollback();
                                }
                                catch (Exception ex2)
                                {
                                    Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                                    Console.WriteLine("  Message: {0}", ex2.Message);
                                }
                            }
                        }
                    }
                }
                else
                {
                    return(Unauthorized());
                }
            }
            catch (Exception e)
            {
                Console.Write("Create Quiz Error_" + e.Message);
            }
            return(Json(new { Result = false, Message = "Nie udało się utworzyć quizu." }));
        }
Пример #4
0
        //
        // GET: /Quiz/Details/5

        public ActionResult Details(int id = 0)
        {
            QuizModel quizmodel = db.Quiz.Find(id);

            if (quizmodel == null)
            {
                return(HttpNotFound());
            }
            return(View(quizmodel));
        }
Пример #5
0
        public async Task <IEnumerable <QuizModel> > GetAllQuizzes(bool includePrivateQuizzes = false)
        {
            var expr = QuizModel.BuildModel(false);


            return(await _context.Quizzes.AsExpandable()
                   .Where(x => (x.Private == false || x.Private == includePrivateQuizzes) && x.ArchivedOn == null && x.DraftMode == false)
                   .Select(x => expr.Invoke(x))
                   .ToListAsync());
        }
Пример #6
0
        private void ValidateCounter(QuizModel model)
        {
            var expectedCount = model.CurrentCount;
            var actualCount   = model.Questions.Count;

            if (expectedCount != actualCount)
            {
                this.ModelState.AddModelError("", "Counter state is invalid");
            }
        }
Пример #7
0
        public ActionResult Edit(int id)
        {
            var quiz = _quizService.GetQuizById(id);

            var model = new QuizModel();

            PrepareQuizModel(model, quiz);

            return(View(model));
        }
Пример #8
0
 public ActionResult CreateQuiz(QuizModel model)
 {
     if (ModelState.IsValid)
     {
         db1.QuizModels.Add(model);
         db1.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(model));
 }
Пример #9
0
        public QuizIngameViewModel(QuizModel _Data)
        {
            Data          = _Data;
            QuestionIndex = 0;

            IsGameInProgress = true;
            IsGameOver       = false;
            IsGamePaused     = false;

            // Back to games command
            BackToGamesCommand = new Command(() =>
            {
                ReturnToGamesEvent?.Invoke(this, EventArgs.Empty);
            });
            // Question answer command
            AnswerCommand = new Command <string>((answer) =>
            {
                if (!IsGamePaused && Int32.TryParse(answer, out int AnswerId))
                {
                    IsGamePaused = true;
                    OnPropertyChanged(nameof(IsGamePaused));

                    if (AnswerId == Question.CorrectAnswer)
                    {
                        Points++;
                    }
                }
            });
            // Next quetion command
            NextQuestionCommand = new Command(() =>
            {
                if (QuestionIndex + 1 == Data.Questions.Count)
                {
                    IsGameInProgress = false;
                    IsGameOver       = true;

                    VerifyResult();

                    OnPropertyChanged(nameof(IsGameInProgress));
                    OnPropertyChanged(nameof(IsGameOver));

                    EndGameSessionEvent?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    QuestionIndex++;
                    OnPropertyChanged(nameof(Question));
                }

                IsGamePaused = false;
                OnPropertyChanged(nameof(IsGamePaused));
                RefreshGameboardEvent?.Invoke(this, EventArgs.Empty);
            });
        }
Пример #10
0
        public async Task <IHttpActionResult> GetQuizModel(int id)
        {
            QuizModel quizModel = await _quizRepository.GetQuestionById(id);

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

            return(Ok(quizModel));
        }
Пример #11
0
        //
        // GET: /Quiz/Edit/5

        public ActionResult Edit(int id = 0)
        {
            QuizModel quizmodel = db.Quiz.Find(id);

            if (quizmodel == null)
            {
                return(HttpNotFound());
            }
            ViewBag.CourseID = new SelectList(db.Course, "CourseID", "CourseName", quizmodel.CourseID);
            return(View(quizmodel));
        }
Пример #12
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            QuizModel     model     = new QuizModel();
            IQuizView     view      = new Form1();
            QuizPresenter presenter = new QuizPresenter(view, model);

            Application.Run((Form)view);
        }
Пример #13
0
        public IActionResult QuizQuestion()
        {
            var model = new QuizModel
            {
                FirstInt           = this._randomService.RandInt(),
                ArithmeticOperator = this._randomService.RandOperator(),
                SecondInt          = this._randomService.RandInt()
            };

            return(this.View(model));
        }
Пример #14
0
        public QuizResultDTO GetResult(Quiz quiz, QuizModel userAnswers)
        {
            Init(quiz, userAnswers);

            return(new QuizResultDTO
            {
                Points = CountPoints(),
                Name = Quiz.Name,
                Questions = CheckAnswers()
            });
        }
        public async Task <IActionResult> GetQuizById(int quizId)
        {
            QuizModel quiz = await _quizAppRepository.GetQuizAsync(quizId);

            if (quiz == null)
            {
                return(NotFound($"Quiz '{quizId}' not found"));
            }

            return(Ok(quiz));
        }
Пример #16
0
 public ActionResult Edit(QuizModel quizmodel)
 {
     quizmodel.CreatedBy = User.Identity.Name;
     if (ModelState.IsValid)
     {
         db.Entry(quizmodel).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.CourseID = new SelectList(db.Course, "CourseID", "CourseName", quizmodel.CourseID);
     return(View(quizmodel));
 }
Пример #17
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            Database.SetInitializer(new DbInitializer());
            var context = new QuizModel();

            context.Database.Initialize(true);
            context.Question.Count();
        }
        public ActionResult Create(QuizModel model)
        {
            if (!ModelState.IsValid)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return new EnhancedJsonResult(ModelState.Values.SelectMany(v => v.Errors));
            }

            var quizId = _quizService.CreateQuiz(model);

            return new EnhancedJsonResult(quizId);
        }
Пример #19
0
        //[ValidateAntiForgeryToken]
        public ActionResult Create(QuizModel model)
        {
            if (!ModelState.IsValid)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(new EnhancedJsonResult(ModelState.Values.SelectMany(v => v.Errors)));
            }

            var quizId = _quizService.CreateQuiz(model);

            return(new EnhancedJsonResult(quizId));
        }
Пример #20
0
        public async Task <IActionResult> Create([Bind("Id,Title,Description,TotalQuestions,PassingPercentage,CategoryId")] QuizModel quizModel)
        {
            if (ModelState.IsValid)
            {
                _context.Quizzes.Include(c => c.Category);
                _context.Add(quizModel);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index", "Admin"));
            }
            return(View(quizModel));
        }
Пример #21
0
        public void AddQuizMocking(QuizEntity quizEntity, QuizModel quizModel)
        {
            _mockMapper.Setup(x => x.Map <QuizEntity>(It.IsAny <CreateQuizModel>()))
            .Returns(quizEntity);
            _mockMapper.Setup(x => x.Map <QuizModel>(It.IsAny <QuizEntity>()))
            .Returns(quizModel);

            _mockQuizService.Setup(x => x.GetQuizAsync(It.IsAny <Guid>()))
            .Returns(Task.FromResult(quizEntity));
            _mockQuizService.Setup(x => x.CreateAsync(It.IsAny <QuizEntity>()))
            .Returns(Task.CompletedTask);
        }
Пример #22
0
        public IHttpActionResult PostQuizModel(QuizModel quizModel)
        {
            if (quizModel == null)
            {
                return(BadRequest(ModelState));
            }

            _quizRepository.AddQuiz(quizModel);
            _quizRepository.Save();

            return(CreatedAtRoute("DefaultApi", new { id = quizModel.Id }, quizModel));
        }
Пример #23
0
        public IActionResult Quiz(CounterAction action, QuizModel model)
        {
            this.ValidateCounter(model);
            if (!this.ModelState.IsValid)
            {
                return(this.View(model));
            }

            switch (action)
            {
            case CounterAction.Submit:
                model.CurrentCount++;
                model.Questions.Add(model.NewQuestion);
                model.NewQuestion = MakeNewQuestion();
                this.ModelState.Remove("CurrentCount");
                this.ModelState.Remove("NewQuestion.FirstNumber");
                this.ModelState.Remove("NewQuestion.SecondNumber");
                this.ModelState.Remove("NewQuestion.Operator");

                return(this.View(model));

            case CounterAction.Finish:

                model.Questions.Add(model.NewQuestion);
                var i = 0;
                foreach (var question in model.Questions)
                {
                    if (
                        this.calculateService.Calculate(
                            question.FirstNumber,
                            question.SecondNumber,
                            question.Operator) == question.Answer
                        )
                    {
                        question.isCorrect = true;
                    }
                    else
                    {
                        question.isCorrect = false;
                    }
                    if (question.isCorrect)
                    {
                        i++;
                    }
                }
                model.RightAnswCount = i;
                return(this.View("QuizResult", model));

            default:
                throw new ArgumentOutOfRangeException(nameof(action), action, null);
            }
        }
Пример #24
0
        public ActionResult Index(int?id, QuizModel model)
        {
            if (!ModelState.IsValid)
            {
                var freshModel = GetModel(id);
                return(View(freshModel));
            }
            // TODO: save selected answer in database
            // TODO: get next question based on selected answer (hard coded to 999 for now)
            var nextQuestionId = 999;

            return(RedirectToAction("Index", "Home", new { id = nextQuestionId }));
        }
Пример #25
0
 public ActionResult Create(QuizModel quizmodel)
 {
     quizmodel.CreatedBy = User.Identity.Name;
     if (ModelState.IsValid)
     {
         db.Quiz.Add(quizmodel);
         db.SaveChanges();
         //return RedirectToAction("Create", "QuestionPool", new { id = quizmodel.QuizID });
         return(RedirectToAction("Index"));
     }
     ViewBag.CourseID = new SelectList(db.Course, "CourseID", "CourseName", quizmodel.CourseID);
     return(View(quizmodel));
 }
Пример #26
0
        public async Task <IActionResult> PostQuestion([FromBody] QuestionModel question)
        {
            QuizModel quiz = await _quizAppRepository.GetQuizAsync(question.QuizId);

            if (quiz == null)
            {
                return(NotFound($"QuizId {question.QuizId} not found"));
            }

            await _questionRepository.CreateQuestionsAsync(question);

            return(Accepted(question));
        }
Пример #27
0
        private void BtnIniciarQuiz_Clicked(object sender, EventArgs e)
        {
            QuizModel respostasQuiz = new QuizModel();

            Device.BeginInvokeOnMainThread(async() =>
            {
                await App.CreateWaitPage(Color.White, "Carregando jogo");
                await Navigation.PushAsync(new Pergunta1(respostasQuiz)
                {
                });
                await App.DestroiWaitPage();
            });
        }
Пример #28
0
        /// <summary>
        /// Выполняет преобразование <see cref="QuizDto"/> в <see cref="QuizModel"/>.
        /// </summary>
        /// <param name="dto">Исходный объект.</param>
        /// <returns>Преобразованный объект.</returns>
        public static QuizModel Translate(QuizDto dto)
        {
            var model = new QuizModel
            {
                Id            = dto.Id,
                Title         = dto.Title,
                TotalTimeSecs = dto.TotalTimeSecs,
                MaxQuizBlocks = dto.MaxQuizBlocksCount,
                QuizBlocks    = dto.QuizBlocks.Select(Translate).ToList(),
            };

            return(model);
        }
Пример #29
0
        public void AddQuiz(QuizModel quiz)
        {
            var customers = _context.Set <QuizModel>();

            if (quiz == null)
            {
                return;
            }
            customers.Add(new QuizModel {
                Question = quiz.Question, Answer = quiz.Answer, MaxPoints = quiz.MaxPoints
            });

            _context.SaveChanges();
        }
Пример #30
0
        public IActionResult toTakeQuiz(QuizModel model)
        {
            var QQ =
                (from q in db.Quizs
                 join qq in db.QuizQuestions on q.QuizId equals qq.QuizId
                 where qq.QuizId == model.QuizId
                 select qq).ToList();

            TempData["CourseId"]    = model.CourseId;
            TempData["qid"]         = model.QuizId;
            TempData["title"]       = model.Title;
            TempData["Description"] = model.Description;

            return(PartialView("TakeQuiz", QQ));
        }
Пример #31
0
        public QuizStatisticsModel GetQuizStatistics(string quizId)
        {
            var model      = new QuizStatisticsModel();
            var quizExp    = QuizModel.BuildModel();
            var expression = QuizResultsModel.BuildModel();

            model.Quiz = _context.Quizzes.AsExpandable().Where(z => z.Id == quizId).Select(x => quizExp.Invoke(x)).FirstOrDefault();

            model.QuizResults = _context.QuizSubmissions
                                .AsExpandable()
                                .Where(x => x.QuizId == quizId && x.QuizzardUserId != null)
                                .Select(x => expression.Invoke(x)).ToList();

            return(model);
        }
        public async Task <IActionResult> PostQuiz([FromBody] QuizModel quiz)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //Find Current User Id
            string currentUserId = User.FindFirst(ClaimTypes.NameIdentifier).Value;

            quiz.OwnerId = currentUserId;
            var createdQuiz = await _quizAppRepository.CreateQuizAsync(quiz);

            return(Accepted(createdQuiz));
        }
        public int CreateQuiz(QuizModel model)
        {
            var entity = _modelFactory.MapToDomain<QuizModel, Quiz>(model, null);
            entity.QuizPages = new List<QuizPage>();

            foreach (var quizPageCreateModel in model.QuizPages)
            {
                var page = _modelFactory.MapToDomain<QuizPageCreateModel, QuizPage>(quizPageCreateModel, null);
                page.QuizQuestions = _modelFactory.MapToDomain<QuizQuestionCreateModel, QuizQuestion>(quizPageCreateModel.QuizQuestions);

                entity.QuizPages.Add(page);
            }

            _quizRepository.Insert(entity);
            _quizRepository.Save();
            return entity.Id;
        }
        public ActionResult Edit(QuizModel model)
        {
            var entity = _quizRepository.Find(model.Id);

            if (entity == null)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                ModelState.AddModelError("", "Question not found.");
                return new EnhancedJsonResult(ModelState.Values.SelectMany(v => v.Errors));
            }

            if (!ModelState.IsValid)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return new EnhancedJsonResult(ModelState.Values.SelectMany(v => v.Errors));
            }

            _quizService.Update(model);

            return Json(null);
        }
Пример #35
0
		public QuizBlockData(QuizModel model, int index, QuizState quizState)
		{
			QuizModel = model;
			BlockIndex = index;
			QuizState = quizState;
		}