public ActionResult EmailPollInvitation(MeetingPoll poll) { try { if (ModelState.IsValid) { var damn = poll.Participants; var ctx = new ApplicationDbContext(); var user = new ApplicationUser(); foreach (var p in poll.Participants) { string email = ctx.Users.Where(s => s.Id == p.Id).Select(x => x.Email).SingleOrDefault(); var senderEmail = new MailAddress("*****@*****.**", "Infoblog"); var receiverEmail = new MailAddress(email); var password = "******"; var subject = "Ny inbjudan till omröstning"; var body = "Du har blivit inbjuden till en omröstning. Gå in på dina sidor för att se omröstningen."; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(senderEmail.Address, password) }; using (var mess = new MailMessage(senderEmail, receiverEmail) { Subject = subject, Body = body }) { smtp.Send(mess); } } } return(View()); } catch (Exception) { ViewBag.Error = "Some Error"; } return(View()); }
public void Poll_ParsingResultDataWorks() { var poll = new MeetingPoll() { ClosedAt = DateTime.UtcNow, PollResults = @"{""Results"":[{""Item1"":1,""Item2"":5},{""Item1"":2,""Item2"":1}],""TotalVotes"":6,""TiebreakInFavourOf"":null}", }; var results = poll.ParsedResults; Assert.NotNull(results); Assert.Equal(2, results.Results.Count); var dto = poll.GetDTO(); results = dto.ParsedResults; Assert.NotNull(results); Assert.Equal(2, results.Results.Count); }
public ActionResult CreateMeetingPoll([FromBody]MeetingData meetingData) { var ctx = new ApplicationDbContext(); var userId = User.Identity.GetUserId(); var author = ctx.Users.First(u => u.Id.Equals(userId)); var mp = new MeetingPoll(); mp.Title = meetingData.Title; mp.Content = meetingData.Content; mp.Author = author; mp.Participants = new List<ApplicationUser>(); List<ApplicationUser> userList = new List<ApplicationUser>(); foreach (var email in meetingData.Participants) { var user = ctx.Users.First(u => u.Email.Equals(email)); mp.Participants.Add(user); } var pollOptions = new List<PollOption>(); var notification = new SendEmailController(); foreach(var time in meetingData.MeetingTimes) { var option = new PollOption() { MeetingTime = time, Votes = 0, MeetingPoll = mp }; pollOptions.Add(option); } mp.PollOptions = pollOptions; ctx.MeetingPolls.Add(mp); ctx.SaveChanges(); notification.EmailPollInvitation(mp); return RedirectToAction("Index"); }
public void Poll_MultipleChoiceResultsAreRight() { var poll = new MeetingPoll() { ClosedAt = DateTime.UtcNow, ParsedData = new PollData() { Choices = new Dictionary <int, PollData.PollChoice>() { { 1, new PollData.PollChoice(1, "Name1") }, { 2, new PollData.PollChoice(2, "Name2") }, { 3, new PollData.PollChoice(3, "Name3") }, }, MultipleChoiceOption = new PollData.MultipleChoice(), }, }; var votes = new List <MeetingPollVote>() { new() { IsTiebreaker = true, VotingPower = 2, ParsedVoteContent = new PollVoteData() { SelectedOptions = new List <int>() { 1, 2 }, }, }, new() { ParsedVoteContent = new PollVoteData() { SelectedOptions = new List <int>() { 2 }, }, }, new() { ParsedVoteContent = new PollVoteData() { SelectedOptions = new List <int>() { 3, 2, 1 }, }, }, new() { VotingPower = 2, ParsedVoteContent = new PollVoteData() { SelectedOptions = new List <int>() { 3 }, }, }, }; poll.CalculateResults(votes); Assert.NotNull(poll.PollResults); var resultData = poll.ParsedResults; Assert.NotNull(resultData); Assert.NotNull(resultData.Results); Assert.Null(resultData.TiebreakInFavourOf); Assert.Equal(10, resultData.TotalVotes); Assert.Equal(3, resultData.Results.Count); // Results check Assert.Equal(2, resultData.Results[0].Item1); Assert.Equal(4, resultData.Results[0].Item2); Assert.Equal(1, resultData.Results[1].Item1); Assert.Equal(3, resultData.Results[1].Item2); Assert.Equal(3, resultData.Results[2].Item1); Assert.Equal(3, resultData.Results[2].Item2); }
public async Task <IActionResult> CreatePoll([Required] long id, [Required][FromBody] MeetingPollDTO request) { PollData parsedData; try { parsedData = request.ParsedData; } catch (Exception e) { logger.LogWarning("Exception when parsing new meeting poll data: {@E}", e); return(BadRequest("Invalid poll data")); } var errors = new List <ValidationResult>(); if (!Validator.TryValidateObject(parsedData, new ValidationContext(parsedData), errors)) { logger.LogError("New poll data didn't pass validation:"); foreach (var error in errors) { logger.LogError("Failure: {Error}", error); } // TODO: send errors to client? return(BadRequest("Invalid poll JSON data")); } // Check poll choice ids foreach (var pair in parsedData.Choices) { if (pair.Key != pair.Value.Id) { return(BadRequest("Mismatch in option ID and Dictionary key")); } } // Detect duplicate names if (parsedData.Choices.GroupBy(p => p.Value.Name).Any(x => x.Count() > 1)) { return(BadRequest("Duplicate option name in poll")); } if (parsedData.WeightedChoices != null) { if (parsedData.MultipleChoiceOption != null || parsedData.SingleChoiceOption != null) { return(BadRequest("Bad poll with multiple types set")); } } else if (parsedData.MultipleChoiceOption != null) { if (parsedData.WeightedChoices != null || parsedData.SingleChoiceOption != null) { return(BadRequest("Bad poll with multiple types set")); } if (parsedData.MultipleChoiceOption.MinimumSelections > parsedData.MultipleChoiceOption.MaximumSelections) { return(BadRequest("Minimum selections can't be higher than max selections")); } } else if (parsedData.SingleChoiceOption != null) { if (parsedData.MultipleChoiceOption != null || parsedData.WeightedChoices != null) { return(BadRequest("Bad poll with multiple types set")); } } var access = GetCurrentUserAccess(); var meeting = await GetMeetingWithReadAccess(id, access); if (meeting == null) { return(NotFound()); } var user = HttpContext.AuthenticatedUser() !; var member = await GetMeetingMember(meeting.Id, user.Id); if (member == null) { return(this.WorkingForbid("You need to join a meeting before creating polls in it")); } if (meeting.OwnerId != user.Id && !user.HasAccessLevel(UserAccessLevel.Admin)) { return(this.WorkingForbid("You don't have permission to create polls in this meeting")); } if (request.AutoCloseAt < DateTime.UtcNow + TimeSpan.FromSeconds(100)) { return(BadRequest("Poll can't auto-close in less than 100 seconds")); } if (await database.MeetingPolls.FirstOrDefaultAsync(p => p.Title == request.Title) != null) { return(BadRequest("A poll with that title already exists")); } var previousPollId = await database.MeetingPolls.Where(p => p.MeetingId == meeting.Id) .MaxAsync(p => (long?)p.PollId) ?? 0; var poll = new MeetingPoll { MeetingId = meeting.Id, PollId = ++previousPollId, Title = request.Title, TiebreakType = request.TiebreakType, AutoCloseAt = request.AutoCloseAt, ParsedData = parsedData, }; await database.MeetingPolls.AddAsync(poll); await database.ActionLogEntries.AddAsync(new ActionLogEntry() { Message = $"Poll added to meeting ({meeting.Id}) with title: {poll.Title}", PerformedById = user.Id, }); await database.SaveChangesAsync(); logger.LogInformation("New poll {Id1} ({Title}) added to meeting ({Id2}) by {Email}", poll.PollId, poll.Title, meeting.Id, user.Email); if (poll.AutoCloseAt != null) { // Queue job to close the poll jobClient.Schedule <CloseAutoClosePollJob>( x => x.Execute(meeting.Id, poll.PollId, CancellationToken.None), poll.AutoCloseAt.Value); } return(Ok()); }