// Calculation for when a visitor answers the survey. This will take into account weighted a question. public async Task <(string redirectUrl, UserType visitorType)> CalculateWeightToUrlAsync(IFormCollection passedForm) { // Retrieve the array of questions to see which ones are weighed for querying the DB for the related branch // URL. var weightArray = passedForm["weight"].ToArray(); var hasWeight = weightArray.Contains("yes", StringComparer.OrdinalIgnoreCase); var weightedQuestionIndex = 0; var weightvalue = 0; if (hasWeight) { // +1 to ignore the weightArray that is created at the top of the submissions weightedQuestionIndex = Array.FindIndex(weightArray, v => v.Equals("Yes")) + 1; var userChoiceId = Guid.Parse(passedForm.ElementAt(weightedQuestionIndex).Value); var userChoiceText = _dbContext.SurveyChoices.Where(c => c.Id == userChoiceId).First().Text; weightvalue = userChoiceText.Equals("Yes", StringComparison.OrdinalIgnoreCase) ? 1 : 0; } var branch = (SurveyBranch)Enum.Parse(typeof(SurveyBranch), passedForm["page"]); var allUrls = await _dbContext.UrlToVisitors.ToListAsync(); var calculatedUrl = allUrls.Where(w => w.Weight == weightvalue).Where(b => b.Category == branch).First(); var url = calculatedUrl.Url; var visitorType = calculatedUrl.UserType; if (string.IsNullOrEmpty(url)) { url = "N/A"; visitorType = UserType.NotFound; } return(url, visitorType); }
/// <summary>Sends the email with informations associated with results of exams for each students.</summary> /// <param name="ExamIDList">The exam identifier list.</param> /// <param name="context">The context.</param> public ActionResult SendEmail(IFormCollection StudentData) { using (var context = new ExamPlatformDbContext()) { try { String getGrade = StudentData.ElementAt(5).Value; String withoutZero = getGrade.Substring(0, 1); double grade = Convert.ToDouble(withoutZero); String getScore = StudentData.ElementAt(6).Value; double score = Convert.ToDouble(getScore); String getDate = StudentData.ElementAt(3).Value; DateTime date = Convert.ToDateTime(getDate); String maxExamScore = StudentData.ElementAt(7).Value; double maxScore = Convert.ToDouble(maxExamScore); UserEmailInfoModel user = new UserEmailInfoModel ( StudentData.ElementAt(0).Value, StudentData.ElementAt(1).Value, StudentData.ElementAt(2).Value, StudentData.ElementAt(4).Value, grade, date, score, maxScore ); JObject messageTemplate = RenderMessageTemplateFromFile(); Dictionary <string, string> emailAccount = GetEmailAccountFromDB(); var purveyed = sendMessage(emailAccount, user, messageTemplate); var studentResult = context.Exam .Include(e => e.ExamResult) .Include(a => a.Account) .Where(e => e.DateOfExam.Date == user.ExamDate.Date && e.DateOfExam.Hour == user.ExamDate.Hour && e.DateOfExam.Minute == user.ExamDate.Minute) .Select(z => z.ExamResult).ToList(); studentResult.First().ifResultSent = purveyed; context.Results.Update(studentResult.First()); context.SaveChanges(); } catch (Exception ex) { logger.Error("StudentExamsController - SendEmail " + ex.Message); } return(RedirectToAction("ShowAllCheckedExams")); } }
public async Task <IActionResult> GetQuiz(IFormCollection results) { try { if (results.Count == 18) { List <int> answerIds = new List <int>(); for (int i = 0; i < results.Count; i++) { if (results.ElementAt(i).Key.Contains("question_")) { string value = results.ElementAt(i).Value; int answerId = Int32.Parse(value); answerIds.Add(answerId); } } string username = this.User.Identity.Name; var currentUser = await userManager.FindByNameAsync(username); if (!AddUserAnswers(currentUser, answerIds)) { throw new Exception("Failed to save answers!"); } return(RedirectToAction("Matches", "Recommendation")); } else { ModelState.AddModelError("", "Please answer all the questions!"); } } catch (Exception ex) { logger.LogError($"Failed to save the answers: {ex}"); ModelState.AddModelError("", "Failed to save answers!"); } return(View(GetQuestionViewModels())); }
public async Task <ActionResult> CatchForm(IFormCollection form) { var quizid = Convert.ToString(form["QuizID"]); var QuizID = quizid.Split(",").ToList()[0]; var stringvragen = Convert.ToString(form["QuestionID"]); List <string> vragen = stringvragen.Split(",").ToList(); if (form.Count() != (vragen.Count() + 7)) { throw new Exception("Please fill in all the questions"); // return RedirectToAction("Play", "QuestionsAnswers", new { id = QuizID }); } else { var stringvragentext = Convert.ToString(form["QuestionText"]); List <string> StringQuestion = stringvragentext.Split(",").ToList(); List <string> Iscorrect = new List <string>(); List <History> Histories = new List <History>(); for (int i = 0; i < vragen.Count(); i++) { var correct = Convert.ToString(form.ElementAt(i + 6)); string pattern = @"^(\[){1}(.*?)(\]){1}$"; correct = Regex.Replace(correct, pattern, "$2"); correct = correct.Trim(); var DefCorrect = correct.Split(","); Iscorrect.Add(DefCorrect[1].Trim()); History history = new History { QuestionID = Guid.Parse(vragen[i]), Correct = Convert.ToByte(Iscorrect[i]), UserId = User.FindFirstValue(ClaimTypes.NameIdentifier), HistoryID = Guid.NewGuid(), QuestionText = StringQuestion[i], QuizID = Guid.Parse(QuizID) }; Histories.Add(history); TempData["Histories"] = JsonConvert.SerializeObject(Histories); var created = await historyRepo.Add(history); if (created == null) { throw new Exception("Invalid Entry"); } } return(RedirectToAction("Index", "History", new { length = Histories.Count() })); } }
public IActionResult DeleteReminder(IFormCollection form) { _reminders.RemoveAll(x => x.Name == form.ElementAt(1).Value); return(View(new ReminderViewModel(_reminders))); }
public async Task <IActionResult> Create([Bind("strength", "agility", "intellect", "will")] IFormCollection collection) { //get current user ApplicationUser user = await GetCurrentUserAsync(); //get last character for current user var characters = _context.Characters .Where(character => character.ApplicationUserId == user.Id) .Last(); //Assign form values to variables var strenghtValue = collection.ElementAt(0).Value; var agilityValue = collection.ElementAt(1).Value; var intellectValue = collection.ElementAt(2).Value; var WillValue = collection.ElementAt(3).Value; //Method for validation using form variables int TotalValue() { //Parse from string to int int numVal = Int32.Parse(strenghtValue) + Int32.Parse(agilityValue) + Int32.Parse(intellectValue) + Int32.Parse(WillValue); return(numVal); } if (ModelState.IsValid && TotalValue() == 42) { //build new row in CharTrait table CharTrait humanTraitStrength = new CharTrait { CharacterId = characters.CharacterId, TraitId = 1, CharTraitValue = collection.ElementAt(0).Value }; //add to hold in db context _context.Add(humanTraitStrength); CharTrait humanTraitAgility = new CharTrait { CharacterId = characters.CharacterId, TraitId = 2, CharTraitValue = collection.ElementAt(1).Value }; //add to hold in db context _context.Add(humanTraitAgility); CharTrait humanTraitIntellect = new CharTrait { CharacterId = characters.CharacterId, TraitId = 3, CharTraitValue = collection.ElementAt(2).Value }; //add to hold in db context _context.Add(humanTraitIntellect); CharTrait humanTraitWill = new CharTrait { CharacterId = characters.CharacterId, TraitId = 4, CharTraitValue = collection.ElementAt(3).Value }; //add to hold in db context and save context to db _context.Add(humanTraitWill); await _context.SaveChangesAsync(); return(RedirectToAction("UserHome", "ApplicationUser")); } else { //if failed vaildation, return to form return(View("HumanAbilitiesForm")); } }