示例#1
0
        public string insertquiz(QuizDTO quizDTO)
        {
            try
            {
                quizDTO.quiz.available = true;
                quiz quizInserted   = context.quiz.Add(quizDTO.quiz);
                int  quizIdInserted = quizInserted.id;

                quizDTO.athleteQuizzes.ForEach(a => {
                    a.quizId    = quizIdInserted;
                    a.available = true;
                    context.athleteQuiz.Add(a);
                });

                quizDTO.quizQuestions.ForEach(q => {
                    q.quizId    = quizIdInserted;
                    q.available = true;
                    context.quizQuestion.Add(q);
                });

                context.SaveChanges();
                return(CONSTANTES.CONSTANTES.ServiceResponse.ok);
            }
            catch (Exception)
            {
                return(CONSTANTES.CONSTANTES.ServiceResponse.error);
            }
        }
示例#2
0
        public ActionResult Index(Quiz quiz)
        {
            var     allUsers  = _quizService.GetQuizs();
            QuizDTO userCheck = allUsers.Where(e => e.Email == quiz.Email).FirstOrDefault();

            try
            {
                Mapper.Initialize(ctg => ctg.CreateMap <Quiz, QuizDTO>());
                var quizDto = Mapper.Map <QuizDTO>(quiz);
                if (userCheck != null)
                {
                    _quizService.UpdateQuiz(quizDto);
                }
                else
                {
                    _quizService.CreateQuiz(quizDto);
                }
                if (quiz.SendEmail)
                {
                    _quizService.SendMailResult(quizDto);
                }
                return(View("Result", quiz));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }
            return(View(quiz));
        }
        public void AddQuizCorrect()
        {
            var quizDTO = new QuizDTO
            {
                Id   = 1,
                Naam = "Quiz 1"
            };

            var response = new Response <QuizDTO> {
                DTO = quizDTO
            };

            //Arrange
            quizService.Setup(x => x.AddQuiz(It.IsAny <QuizDTO>())).Returns(response);

            //Act
            var quizViewModel = new QuizViewModelRequest
            {
                Naam = "Quiz 1"
            };

            var addQuiz = controller.Create(quizViewModel) as ObjectResult;
            var entity  = addQuiz.Value as QuizViewModelResponse;

            //Assert
            Assert.DoesNotThrow(() => controller.Create(quizViewModel));
            Assert.That(entity.Id, Is.EqualTo(quizDTO.Id));
            Assert.That(entity.Naam, Is.EqualTo(quizDTO.Naam));
        }
示例#4
0
        public void SendMailResult(QuizDTO quizDto)
        {
            string server   = "smtp.gmail.com";
            string port     = "587";
            string login    = "******";
            string password = "******";

            MailMessage mail = new MailMessage();

            mail.Subject = "Result";
            mail.From    = new MailAddress(login);
            mail.Body    = quizDto.ToString();
            mail.To.Add(new MailAddress(quizDto.Email));
            mail.BodyEncoding = Encoding.UTF8;
            mail.IsBodyHtml   = true;

            SmtpClient client = new SmtpClient();

            client.Host        = server;
            client.Port        = Convert.ToInt32(port);
            client.EnableSsl   = true;
            client.Credentials = new NetworkCredential(login, password);

            try
            {
                client.Send(mail);
            }
            catch { }
        }
        public void AddQuizCorrect()
        {
            var quiz = new Quiz
            {
                Id           = 1,
                Naam         = "Quiz 1",
                EmailCreator = "*****@*****.**"
            };

            //Arange
            var unitOfWork = new Mock <ITeamQuizRondeUnitOfWork>();

            unitOfWork.Setup(x => x.QuizRepository.Add(It.IsAny <Quiz>())).Returns(quiz);
            var quizService = new QuizService(unitOfWork.Object);

            //Act
            var quizDTO = new QuizDTO
            {
                Id           = 1,
                Naam         = "Quiz 1",
                EmailCreator = "*****@*****.**"
            };

            //Assert
            Assert.IsFalse(quizService.AddQuiz(quizDTO).DidError);
            Assert.That(quizService.AddQuiz(quizDTO).DTO.EmailCreator, Is.EqualTo(quizDTO.EmailCreator));
            Assert.That(quizService.AddQuiz(quizDTO).DTO.Id, Is.EqualTo(quizDTO.Id));
            Assert.That(quizService.AddQuiz(quizDTO).DTO.Naam, Is.EqualTo(quizDTO.Naam));
        }
        public void DeleteQuizCorrect()
        {
            var quiz = new Quiz
            {
                Id   = 1,
                Naam = "Quiz 1"
            };

            //Arange
            var unitOfWork = new Mock <ITeamQuizRondeUnitOfWork>();

            unitOfWork.Setup(x => x.QuizRepository.Remove(1)).Returns(true);
            var quizService = new QuizService(unitOfWork.Object);

            //Act
            var quizDTO = new QuizDTO
            {
                Id   = 1,
                Naam = "Quiz 1"
            };

            //Assert
            Assert.IsFalse(quizService.Delete(1).DidError);

            Assert.IsTrue(quizService.FindQuiz(quiz.Id).DidError);
            Assert.IsNull(quizService.FindQuiz(quiz.Id).DTO);
        }
        public void DeleteQuizCorrect()
        {
            var quizDTO = new QuizDTO
            {
                Id   = 1,
                Naam = "Quiz 1"
            };

            var response = new Response <int> {
                DTO = 1
            };

            //Arrange
            quizService.Setup(x => x.Delete(1)).Returns(response);

            //Act
            var quizViewModel = new QuizViewModelResponse
            {
                Id   = 1,
                Naam = "Quiz 1"
            };

            var deleteQuiz = controller.Delete(quizViewModel.Id) as ObjectResult;

            //var entity = deleteQuiz.Value as QuizViewModelResponse;

            //Assert
            Assert.DoesNotThrow(() => controller.Delete(quizViewModel.Id));
        }
示例#8
0
        private Quiz CreateQuiz(QuizDTO quizDTO)
        {
            Quiz quiz = GetQuizEntity(quizDTO);

            quiz.AssignedUsers = new List <AssignedUser>();
            var type = Data.Entities.AssignType.Favourite;

            CreateQuizEntityAssignList(quizDTO, quiz, type, quizDTO.FavouritesUsers);
            type = Data.Entities.AssignType.AssignedToPrivate;
            CreateQuizEntityAssignList(quizDTO, quiz, type, quizDTO.PrivateAssignedUsers);
            quiz.Scores = new List <Score>();
            foreach (var s in quizDTO.AllScore)
            {
                Score score = new Score
                {
                    ApplicationUserId = s.ApplicationUserId,
                    QuizId            = s.QuizId,
                    Result            = s.Result
                };
                quiz.Scores.Add(score);
            }
            //quiz.CreationDate = DateTime.ParseExact(quizDTO.CreationDate, QuizDTO.CreationDateFormat, null);
            quiz.CreationDate = quizDTO.CreationDate;
            return(quiz);
        }
示例#9
0
        public async Task <IActionResult> GenerateQuiz(int questionsCount)
        {
            if (ModelState.IsValid)
            {
                var quiz    = new Quiz();
                var created = await _quizRepo.AddEntity(quiz);

                var quizGenerated = _quizRepo.GenerateQuiz(created, questionsCount);

                var quizDTO = new QuizDTO {
                    Name = quiz.Name, Id = quiz.Id
                };
                quizDTO.QuestionDTOs = new List <QuestionDTO>();
                var t = quizGenerated.Questions.Count(a => a.Answers.Count() > 0);
                foreach (var question in quizGenerated.Questions)
                {
                    var answerList = question.Answers.Select(a => new AnswerDTO {
                        Id = a.Id, QuestionId = a.QuestionId, Text = a.Text
                    });
                    var questionDTO = new QuestionDTO {
                        Id = question.Id, SnippetUrl = question.SnippetUrl, Text = question.Text, AnswerDTOs = answerList
                    };
                    quizDTO.QuestionDTOs.Add(questionDTO);
                }

                return(Ok(quizDTO));
            }

            else
            {
                return(BadRequest("ModelState is not valid."));
            }
        }
示例#10
0
        public CreateQuizViewModel CreateQuizViewModelFromQuizDTO(QuizDTO quiz)
        {
            CreateQuizViewModel viewModel = new CreateQuizViewModel();

            viewModel.Id          = quiz.Id;
            viewModel.Description = quiz.Description;
            viewModel.Title       = quiz.Title;
            viewModel.Path        = quiz.FilePath;
            int i = 0;

            foreach (var q in quiz.Questions)
            {
                CreateQuestionViewModel questionViewModel = new CreateQuestionViewModel();
                questionViewModel.Question = q.Question;
                int j = 0;
                foreach (var a in quiz.Questions[i].Answers)
                {
                    CreateAnswerViewModel answerViewModel = new CreateAnswerViewModel();
                    questionViewModel.Answers.Add(answerViewModel);
                    questionViewModel.Answers[j].Answer    = a.Answer;
                    questionViewModel.Answers[j].isCorrect = a.isCorrect;
                    j++;
                }
                i++;
            }


            return(viewModel);
        }
示例#11
0
        private async Task <QuizDTO> GetQuizAsDTO(Database.Models.Quiz quiz)
        {
            List <string> incorrectAnswers = await _unitOfWork.IncorrectAnswerRepository.GetIncorrectAnswers(quiz.IncorrectAnswers.Select(ia => ia.IncorrectAnswerId).ToList());

            List <IncorrectAnswerDTO> options = new List <IncorrectAnswerDTO>();

            foreach (var item in incorrectAnswers)
            {
                options.Add(new IncorrectAnswerDTO {
                    Option = item
                });
            }

            QuizDTO output = new QuizDTO
            {
                QuizId     = quiz.Id,
                Category   = quiz.Category,
                Difficulty = quiz.Difficulty,
                Question   = quiz.Question,
                Answer     = quiz.CorrectAnswer,
            };

            output.IncorrectAnswers.AddRange(options);
            return(output);
        }
示例#12
0
        ///<summary>
        ///Busca os questionários de questionários de uma firma
        /// </summary>
        public List <QuizDTO> GetAllFromFirmDTO(int firmId, string search, int pageIndex, int pageSize)
        {
            QuizRepository repository = new QuizRepository();

            List <QuizEntity> list = this.GetAllFromFirm(firmId, search, pageIndex, pageSize);

            List <QuizDTO> listTO = new List <QuizDTO>();

            foreach (var item in list)
            {
                QuizDTO to = new QuizDTO()
                {
                    CreatedBy      = item.CreatedBy,
                    Description    = item.Description,
                    FirmId         = item.FirmId,
                    Id             = item.Id,
                    IdQuizQuestion = item.IdQuizQuestion,
                    InitialDate    = item.InitialDate,
                    IsMultiple     = item.IsMultiple,
                    LastUpdate     = item.LastUpdate,
                    Name           = item.Name,
                    Required       = item.Required,
                    Score          = item.Score,
                    UpdatedBy      = item.UpdatedBy,
                    DateLimit      = item.DateLimit,
                    status         = item.status,
                };
                QuizQuestionRepository questionRepository = new QuizQuestionRepository();

                to.QtdPerguntas = questionRepository.Get(x => x.IdQuiz == item.Id).Count();
                listTO.Add(to);
            }

            return(listTO);
        }
示例#13
0
 public ActionResult InsertQuizzes([FromBody] QuizDTO quiz)
 {
     if (_quizzesRepository.InsertQuiz(quiz))
     {
         return(Ok(_mapper.Map <QuizDTO>(quiz)));
     }
     return(BadRequest());
 }
示例#14
0
        public void Update(QuizDTO quizDTO)
        {
            var quiz = CreateQuiz(quizDTO);

            //var kolekcja pytan json lub xml = json mapper
            quizRepository.Update(quiz);
            this.jsonRepository.SaveWithAbsolutePath(quizDTO.FilePath, quizDTO.JSON);
        }
示例#15
0
        private QuizDTO CreateQuiz(Quiz quiz)
        {
            if (quiz == null)
            {
                return(null);
            }
            string userId = quiz.ApplicationUserId;

            DateTime creationDate = quiz.CreationDate;

            ApplicationUserDTO user = userDTOMapper.CreateUserWithId(userId);

            DTOs.QuizType?              type        = quiz.QuizType.ToDTOQuizType();
            DTOs.QuizAccessLevel?       accessLevel = quiz.QuizAccessLevel.ToDTOQuizAccessLevel();
            ICollection <DTOs.ScoreDTO> scoreDTO    = quiz.Scores.ToDTOQuizScore();
            int attemps = 0;

            for (int i = 0; i < scoreDTO.Count(); i++)
            {
                if (quiz.ApplicationUserId == scoreDTO.ElementAt(i).ApplicationUserId)
                {
                    attemps++;
                }
            }
            QuizDTO quizDTO = new QuizDTO(quizEntityMapper.Update)
            {
                Id                = quiz.Id,
                Title             = quiz.Title,
                Description       = quiz.Description,
                ApplicationUserId = user.Id,
                //QuizSettingsId = "1",
                QuizType        = type,
                QuizAccessLevel = accessLevel,
                FilePath        = quiz.FilePath,
                ApplicationUser = user,
                AllScore        = scoreDTO,
                CreationDate    = creationDate
            };

            List <string> idsList = new List <string>();

            foreach (var ass in quiz.AssignedUsers.
                     Where(a => a.AssignType == Data.Entities.AssignType.Favourite))
            {
                idsList.Add(ass.ApplicationUserId);
            }
            FillList(quizDTO.FavouritesUsers, idsList);
            idsList = new List <string>();
            foreach (var ass in quiz.AssignedUsers.
                     Where(a => a.AssignType == Data.Entities.AssignType.AssignedToPrivate))
            {
                idsList.Add(ass.ApplicationUserId);
            }
            FillList(quizDTO.PrivateAssignedUsers, idsList);
            quizDTO.Questions = this.LoadQuestions(quizDTO);
            return(quizDTO);
        }
示例#16
0
 private QuizDTO ConvertQuizAndGetServiceResponse(
     QuizDTO appletResultDTO,
     Quiz quiz,
     QuizModel quizModel)
 {
     quiz = ConvertDto(appletResultDTO, quiz);
     quizModel.RegisterSave(quiz, true);
     return(new QuizDTO(quiz));
 }
示例#17
0
        public void CreateQuiz(QuizDTO quizDto)
        {
            ValidatorBlogModels.ValidateQuizModel(quizDto);
            var mapper  = MapperConfig.GetConfigFromDTO().CreateMapper();
            var quizNew = mapper.Map <Quiz>(quizDto);

            DataBase.Quizes.Create(quizNew);
            DataBase.Save();
        }
        public async Task <IActionResult> Add(QuizDTO quiz)
        {
            var entity = Mapper.Map(quiz);
            await _quizRepository.AddQuizAsync(quiz.ParentId, entity);

            await _unitOfWork.CompleteAsync();

            return(Accepted());
        }
示例#19
0
        public void AddNewQuiz(QuizDTO quizDTO)
        {
            var quiz = CreateQuiz(quizDTO);

            //var kolekcja pytan json lub xml = json save = / quiz.jsonFile pewnie bd trzeba cos dodac do tego jsona.
            quizRepository.Add(quiz);
            quizDTO.Id       = quiz.Id;
            quizDTO.FilePath = this.jsonRepository.BuildAbsolutePath(quizDTO.Id);
            this.jsonRepository.SaveWithAbsolutePath(quizDTO.FilePath, quizDTO.JSON);
            this.Update(quizDTO);
        }
示例#20
0
 public static CourseContentToken QuizToken2ContentToken(this QuizDTO token)
 {
     return(new CourseContentToken
     {
         Name = token.Title
         , CourseId = token.CourseId
         , ContentId = token.Sid
         , Uid = Guid.NewGuid()
         , Kind = CourseEnums.eCourseContentKind.Quiz
         , Quiz = token
     });
 }
示例#21
0
        private static void AddStaticMockData(List <QuizDTO> quizesDTO)
        {
            var x = new QuizDTO
            {
                Id                = "3",
                Title             = "Quiz1",
                Description       = "1 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mollis justo orci, eget vulputate orci malesuada nec...",
                CreationDate      = "1996.01.11",
                ApplicationUserId = "8ded9b6f-e8a8-425b-a115-c280885e92c1"
            };
            var y = new QuizDTO
            {
                Id           = "4",
                Title        = "Quiz2",
                Description  = "2 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mollis justo orci, eget vulputate orci malesuada nec...",
                CreationDate = "2000.01.11"
            };
            var z = new QuizDTO
            {
                Id           = "5",
                Title        = "Quiz3",
                Description  = "3 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mollis justo orci, eget vulputate orci malesuada nec...",
                CreationDate = "2011.01.11"
            };
            var o = new QuizDTO
            {
                Id           = "6",
                Title        = "Quiz4",
                Description  = "4 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mollis justo orci, eget vulputate orci malesuada nec...",
                CreationDate = "2016.01.11"
            };
            var a = new QuizDTO
            {
                Id           = "7",
                Title        = "Quiz5",
                Description  = "5 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mollis justo orci, eget vulputate orci malesuada nec...",
                CreationDate = "1990.01.11"
            };
            var b = new QuizDTO
            {
                Id           = "8",
                Title        = "Quiz6",
                Description  = "6 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mollis justo orci, eget vulputate orci malesuada nec...",
                CreationDate = "2006.01.11"
            };

            quizesDTO.Add(x);
            quizesDTO.Add(y);
            quizesDTO.Add(z);
            quizesDTO.Add(o);
            quizesDTO.Add(a);
            quizesDTO.Add(b);
        }
示例#22
0
 public static QuizViewModelRequest MapQuizDTOToQuizViewModelRequest(QuizDTO quizDTO)
 {
     if (quizDTO == null)
     {
         throw new NullReferenceException("quiz object is null");
     }
     return(new QuizViewModelRequest
     {
         //Id = quizDTO.Id,
         Naam = quizDTO.Naam
     });
 }
示例#23
0
 private static void CreateQuizEntityAssignList(QuizDTO quizDTO, Quiz quiz, Data.Entities.AssignType type, IEnumerable <ApplicationUserDTO> listOfusersDTO)
 {
     foreach (var user in listOfusersDTO)
     {
         var ass = new AssignedUser()
         {
             ApplicationUserId = user.Id,
             AssignType        = type,
             QuizId            = quizDTO.Id
         };
         quiz.AssignedUsers.Add(ass);
     }
 }
示例#24
0
        private List <QuestionDTO> LoadQuestions(QuizDTO quizDTO)
        {
            string json = this.jsonRepository.LoadWithAbsolutePath(quizDTO.FilePath);

            if (json != null)
            {
                var deserialized = JsonConvert.DeserializeObject <QuizDTO.JSONScheme>(json);
                return(deserialized.Questions);
            }
            else
            {
                throw new NullReferenceException("Failed to load quiz questions from json file");
            }
        }
 // POST: api/Quizzes
 public IHttpActionResult Post([FromBody] QuizDTO value)
 {
     try
     {
         return(ResponseMessage(Request.CreateResponse(new
         {
             response = quizService.insertquiz(value)
         })));
     }
     catch (Exception e)
     {
         return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.ToString())));
     }
 }
示例#26
0
        public QuizDTO Save(QuizDTO appletResultDTO)
        {
            if (this.IsValid(appletResultDTO, out ValidationResult validationResult))
            {
                var quizModel   = QuizModel;
                var isTransient = appletResultDTO.quizId == 0;
                var quiz        = isTransient ? null : quizModel.GetOneById(appletResultDTO.quizId).Value;
                return(ConvertQuizAndGetServiceResponse(appletResultDTO, quiz, quizModel));
            }

            var error = GenerateValidationError(validationResult);

            LogError("Quiz.Save", error);
            throw new FaultException <Error>(error, error.errorMessage);
        }
示例#27
0
 public static Quiz MapQuizDTOToQuizModel(QuizDTO quizDTO)
 {
     if (quizDTO == null)
     {
         throw new NullReferenceException("QuizDTO is null");
     }
     return(new Quiz
     {
         Id = quizDTO.Id,
         Naam = quizDTO.Naam,
         EmailCreator = quizDTO.EmailCreator,
         FreeQuiz = quizDTO.FreeQuiz,
         EntryFee = Int32.Parse(quizDTO.EntryFee)
     });
 }
示例#28
0
        public ActionResult SaveQuiz(QuizDTO token)
        {
            string error;
            var    isNew = token.Sid < 0;
            var    saved = _quizAdminServices.SaveQuiz(token, out error);

            if (isNew && saved)
            {
                SaveUserEvent(CommonEnums.eUserEvents.QUIZ_CREATED);
            }

            return(Json(new JsonResponseToken {
                success = saved, result = new{ isNew }, error = error
            }, JsonRequestBehavior.AllowGet));
        }
示例#29
0
        public ActionResult Edit([FromBody] CreateQuizViewModel quizViewModel)
        {
            TempData.Remove("QuizInCreation");
            var     userId  = this.User.FindFirstValue(ClaimTypes.NameIdentifier);//
            var     user    = this.userMapper.CreateUserWithId(userId);
            QuizDTO quizDTO = this.quizDTOMapperFromViewModel.Map(quizViewModel, user);

            if (quizDTO.ApplicationUserId == null)  //
            {
                quizDTO.ApplicationUserId = userId; //TE LINIE MOGA BYC DO WYWALENIA
            }
            quizDTO.FilePath = quizDTO.FilePath;
            quizService.SaveQuiz(quizDTO);
            return(Json(new { status = "OK" }));
        }
示例#30
0
        public void UpdateQuiz(QuizDTO quizDto)
        {
            if (DataBase.Quizes.Get(quizDto.Id) == null)
            {
                throw new ValidationException("Quiz wasn't found", "");
            }

            var config   = new MapperConfiguration(cfg => cfg.CreateMap <QuizDTO, Quiz>());
            var mapper   = config.CreateMapper();
            var quizTemp = mapper.Map <Answer>(quizDto);

            DataBase.Answers.Update(quizTemp);

            DataBase.Save();
        }