Esempio n. 1
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;

            if (ModelState.IsValid)
            {
                #region Check if IdentityRoles Exists

                var user = new User {
                    UserName = model.Email, Email = model.Email
                };

                if (_userManager.Users.Any())
                {
                    var role = new IdentityUserRole <string> {
                        UserId = user.Id, RoleId = _context.Roles.Where(r => r.Name == "Member").First().Id
                    };
                    _context.Add(role);
                }
                else
                {
                    var role = new IdentityUserRole <string> {
                        UserId = user.Id, RoleId = _context.Roles.Where(r => r.Name == "Admin").First().Id
                    };
                    _context.Add(role);
                }

                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await _context.SaveChangesAsync();

                    _logger.LogInformation("User created a new account with password.");

                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    //await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation("User created a new account with password.");
                    return(RedirectToLocal(returnUrl));
                }

                #endregion

                AddErrors(result);
            }
            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 2
0
        public static void UseSampleQuestions(this IApplicationBuilder app, string path)
        {
            // load a sample JSON file of questions
            string json = File.ReadAllText(Path.Combine(path, "samplequestions.json"));

            var settings = new JsonSerializerSettings
            {
                PreserveReferencesHandling = PreserveReferencesHandling.All
            };

            List <Quiz> quizzes = JsonConvert.DeserializeObject <List <Quiz> >(json, settings);

            // Configure the in-memory database option
            var optionsBuilder = new DbContextOptionsBuilder <QuizContext>();

            optionsBuilder.UseInMemoryDatabase();

            using (var context = new QuizContext(optionsBuilder.Options))
            {
                foreach (Quiz quiz in quizzes)
                {
                    // mark each quiz and its question entities as Added
                    context.Add(quiz, GraphBehavior.IncludeDependents);
                }
                // Save the entities to the data store
                context.SaveChanges();
            }
        }
Esempio n. 3
0
        public static void UseSampleQuestions(this IApplicationBuilder builder, string path)
        {
            //加载json文件
            string json    = File.ReadAllText(Path.Combine(path, "SampleQuestions.json"));
            var    setting = new JsonSerializerSettings {
                PreserveReferencesHandling = PreserveReferencesHandling.All
            };

            List <Quiz> quizzes = JsonConvert.DeserializeObject <List <Quiz> >(json, setting);

            //配置内存数据库选项
            var optionBuilder = new DbContextOptionsBuilder <QuizContext>();

            optionBuilder.UseInMemoryDatabase();

            using (var context = new QuizContext(optionBuilder.Options))
            {
                //将每个quiz和他的question实体标记为添加状态
                foreach (var quiz in quizzes)
                {
                    context.Add(quiz);
                }
                //将实体保存到数据存储
                context.SaveChanges();
            }
        }
Esempio n. 4
0
        public async Task <IActionResult> Create([Bind("Id,Name")] Category category)
        {
            if (ModelState.IsValid)
            {
                _context.Add(category);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(category));
        }
        public async Task <IActionResult> Create([Bind("Id,Pergunta,Opcao_a,Opcao_b,Opcao_c,Opcao_d,Resposta_certa")] Questao questao)
        {
            if (ModelState.IsValid)
            {
                _context.Add(questao);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(questao));
        }
        public async Task <IActionResult> Create([Bind("Id,Nome,Email,Senha,Foto")] Jogador jogador)
        {
            if (ModelState.IsValid)
            {
                _context.Add(jogador);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(jogador));
        }
Esempio n. 7
0
        public async Task <IActionResult> Create([Bind("Id,Statement,CategoryId")] Question question)
        {
            if (ModelState.IsValid)
            {
                _context.Add(question);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CategoryId"] = new SelectList(_context.Categories, "Id", "Id", question.CategoryId);
            return(View(question));
        }
Esempio n. 8
0
        public async Task <IActionResult> Create([Bind("Id,JogadorId,QuestaoId,Resposta")] RespostaJogador respostaJogador)
        {
            if (ModelState.IsValid)
            {
                _context.Add(respostaJogador);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["JogadorId"] = new SelectList(_context.Jogador, "Id", "Id", respostaJogador.JogadorId);
            ViewData["QuestaoId"] = new SelectList(_context.Questao, "Id", "Id", respostaJogador.QuestaoId);
            return(View(respostaJogador));
        }
Esempio n. 9
0
        public async Task <IActionResult> Post([FromBody] Models.Question question)
        {
            var quiz = context.Quiz.SingleOrDefault(q => q.ID == question.QuizId);

            if (quiz == null)
            {
                return(NotFound());
            }
            context.Add(question);
            await context.SaveChangesAsync();

            return(Ok(question));
        }
Esempio n. 10
0
            public async Task <Quiz> Handle(Command request, CancellationToken cancellationToken)
            {
                var quiz = new Quiz(request.Name);

                context.Add(quiz);
                var success = await context.SaveChangesAsync() > 0;

                if (success)
                {
                    return(quiz);
                }

                throw new Exception("There was a problem saving changes.");
            }
        public async Task <IActionResult> Post([FromBody] Question question)
        {
            //Check if quiz exists prior to adding
            Quiz quiz = context.Quiz.SingleOrDefault(q => q.ID == question.QuizId);

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

            context.Add(question);
            await context.SaveChangesAsync();

            return(Ok(question));
        }
        public async Task <ActionResult> Post([FromBody] Quizzes quiz)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var userId = HttpContext.User.Claims.First().Value;

            quiz.OwnerId = userId;
            _context.Add(quiz);
            await _context.SaveChangesAsync();

            // return CreatedAtAction("Get", new { id = quiz.Id }, quiz);
            return(Ok(quiz));
        }
Esempio n. 13
0
        public async Task <IActionResult> PostQuizResponse([FromBody] Models.QuizResponse quizResponse)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userIdClaim = HttpContext.User.Claims.FirstOrDefault();
            var userId      = quizResponse.UserSub;

            if (userIdClaim == null)
            {
                userId = quizResponse.UserSub;
            }
            else
            {
                userId = userIdClaim.ToString();
            }

            context.QuizResponses.Add(quizResponse);
            Archetype archetype = context.Archetypes
                                  .Where(a =>
                                         (a.CombatRating == quizResponse.RatioCombat) &&
                                         (a.MagicRating == quizResponse.RatioMagic) &&
                                         (a.StealthRating == quizResponse.RatioStealth)
                                         ).FirstOrDefault();

            if (archetype == null)
            {
                archetype = context.Archetypes.First();
            }

            CharacterSheet character = new CharacterSheet {
                Strength     = archetype.BaseStrength,
                Dexterity    = archetype.BaseDexterity,
                Intelligence = archetype.BaseIntelligence,
                Health       = archetype.BaseHealth,
                Archetype    = archetype,
                UserSub      = userId
            };

            context.Add(character);
            await context.SaveChangesAsync();

            return(CreatedAtAction("Get", new { id = character.ID }, character));
        }
Esempio n. 14
0
        public async Task <IActionResult> Create(Question question)
        {
            if (UnknownQuiz(question))
            {
                return(BadRequest("Quiz unknown"));
            }

            if (string.IsNullOrWhiteSpace(question.Text))
            {
                return(BadRequest("Question has no content."));
            }

            _quizContext.Add(question);
            await _quizContext.SaveChangesAsync(true);

            Inspect(_quizContext);

            return(Ok(question));
        }
      public async Task <ActionResult> Post([FromBody] Model.Questions question)

      {
          var quiz = _context.quizes.SingleOrDefault(q => q.Id == question.quizId);

          /*
           * var quiz = _context.quizes.SingleOrDefault(q => q.Id == question.quizId);
           * if(quiz==null){
           *  return NotFound();
           * }
           * if(! ModelState.IsValid){
           *  return BadRequest();
           * }
           */
          if (quiz == null)
          {
              return(NotFound());
          }
          _context.Add(question);
          await _context.SaveChangesAsync();

          return(Ok(question));
      }
Esempio n. 16
0
 public void Add(Test newTest)
 {
     _context.Add(newTest);
     _context.SaveChanges();
 }
Esempio n. 17
0
        public static void AddSampleQuizzes()
        {
            // Configure the in-memory database option
            var optionsBuilder = new DbContextOptionsBuilder <QuizContext>();

            optionsBuilder.UseInMemoryDatabase();
            // Note: in future we could change the statement above to use
            // a different database such as SQL Database in Azure without
            // needing to change any other code.

            using (var context = new QuizContext(optionsBuilder.Options))
            {
                // define a sample C# and OOP quiz
                var csharpQuiz = new Quiz
                {
                    QuizID      = "CSHARP",
                    Title       = "C# and OOP",
                    Description = "Questions about the C# language and object-oriented programming."
                };
                csharpQuiz.Questions.Add(new Question
                {
                    Quiz          = csharpQuiz,
                    QuestionText  = "Which modifier would you apply to a type's member to allow only code within that type access to it?",
                    AnswerA       = "internal",
                    AnswerB       = "protected",
                    AnswerC       = "private",
                    AnswerD       = "public",
                    CorrectAnswer = "C"
                });
                csharpQuiz.Questions.Add(new Question
                {
                    Quiz          = csharpQuiz,
                    QuestionText  = "Which keyword would you apply to a type's field to prevent its value from changing after an instance of the type has been created?",
                    AnswerA       = "const",
                    AnswerB       = "readonly",
                    AnswerC       = "static",
                    AnswerD       = "protected",
                    CorrectAnswer = "B"
                });

                var fileioQuiz = new Quiz
                {
                    QuizID      = "FILEIO",
                    Title       = "File I/O",
                    Description = "Questions about the file input/output features of the .NET Framework including serialization."
                };
                fileioQuiz.Questions.Add(new Question
                {
                    Quiz          = fileioQuiz,
                    QuestionText  = "Which are the requirements for a type to be serialized by using the BinaryFormatter?",
                    AnswerA       = "Apply [Serializable] to the type.",
                    AnswerB       = "Apply [Serializable] to the type and make all fields public.",
                    AnswerC       = "Ensure the type has a public parameterless contructor.",
                    AnswerD       = "Ensure the type has a public parameterless contructor and make all fields public.",
                    CorrectAnswer = "A"
                });

                var aspnetQuiz = new Quiz
                {
                    QuizID      = "ASPNET",
                    Title       = "ASP.NET Web Applications and Services",
                    Description = "Questions about building MVC web applications and Web API services by using ASP.NET."
                };
                aspnetQuiz.Questions.Add(new Question
                {
                    Quiz          = aspnetQuiz,
                    QuestionText  = "Which of the following is NOT a requirement for an MVC controller?",
                    AnswerA       = "The class must implement the IController interface.",
                    AnswerB       = "The class must inherit from the Controller class.",
                    AnswerC       = "The class must be public.",
                    AnswerD       = "The class's action methods must NOT use generic types.",
                    CorrectAnswer = "B"
                });

                // mark the three quiz and question entities as Added and then save them to the data store
                context.Add(csharpQuiz, GraphBehavior.IncludeDependents);
                context.Add(fileioQuiz, GraphBehavior.IncludeDependents);
                context.Add(aspnetQuiz, GraphBehavior.IncludeDependents);
                context.SaveChanges();
            }
        }
Esempio n. 18
0
 public Quiz CreateQuiz(Quiz quiz)
 {
     _context.Add(quiz);
     _context.SaveChanges();
     return(quiz);
 }
Esempio n. 19
0
 public void Add(Field newField)
 {
     _context.Add(newField);
     _context.SaveChanges();
 }
 public Quiz PostQuiz(Quiz quiz)
 {
     _quizContext.Add(quiz);
     _quizContext.SaveChanges();
     return(quiz);
 }
Esempio n. 21
0
 public async Task Post([FromBody] Model.Quiz quiz)
 {
     _quizContext.Add(quiz);
     await _quizContext.SaveChangesAsync();
 }