Esempio n. 1
0
        public async Task <IActionResult> Put(int id, [FromBody] PollView <TUserView> pollView)
        {
            using (var transaction = session.BeginTransaction())
            {
                // Update poll
                var poll = await session.LoadAsync <Poll <TUser> >(id);

                poll.Question = pollView.Question;

                var newAnswers = pollView.PossibleAnswers.Where(a => a.Text != null).ToList();

                // Update or add modified possible answers
                foreach (var possibleAnswerDto in newAnswers)
                {
                    var possibleAnswer = poll.PossibleAnswers.SingleOrDefault(p => p.Id == possibleAnswerDto.Id);

                    if (possibleAnswer != null)
                    {
                        possibleAnswer.Text = possibleAnswerDto.Text.Trim();

                        if (possibleAnswer.Text.Length >= 1)
                        {
                            possibleAnswer.Text = possibleAnswerDto.Text;
                            await session.UpdateAsync(possibleAnswer);
                        }
                    }
                    else
                    {
                        await session.SaveAsync(new PollPossibleAnswer <TUser>
                        {
                            Text = possibleAnswerDto.Text,
                            Poll = poll
                        });
                    }
                }

                // Delete from db possible answers no longer in the Dto (removed by user)
                foreach (var answer in poll.PossibleAnswers.Where(p => newAnswers.All(u => u.Id != p.Id)))
                {
                    await session.DeleteAsync(answer);
                }
                await session.UpdateAsync(poll);

                transaction.Commit();
            }
            return(Ok());
        }
Esempio n. 2
0
        public JsonResult CreatePoll(PollView pollView)
        {
            using (var repository = _repositoryProvider.GetRepository())
            {
                var poll = Mapper.Map<PollView, Poll>(pollView);
                poll.AddedBy = HttpContext.User.Identity.Name;
                poll.DateAdded = DateTime.Now;
                poll.Path = poll.PollQuestion.ToUrlFormat();
                poll.Options.Each(p =>
                {
                    p.DateAdded = DateTime.Now;
                    p.ForPoll = poll;
                });
                repository.Save(poll);

                return Json(Url.Action("ManagePolls"));
            }
        }
Esempio n. 3
0
        public async Task <PollView?> GetPollViewAsync(Guid id, OptionSorting sort = OptionSorting.Votes)
        {
            var poll = await GetPollAsync(id);

            var view = PollView.Of(poll);

            if (view is not null)
            {
                view.Options = sort switch
                {
                    OptionSorting.Name => view.Options.OrderBy(option => option.Description),
                    OptionSorting.Votes => view.Options.OrderBy(option => option.Votes),
                    _ => throw new NotImplementedException(),
                };
                view.Options = view.Options.ToList();
                MathUtils.NormalizePercentages(view.Options);
                view.Voters = pollRepository.GetVotersCount(id);
            }
            return(view);
        }
Esempio n. 4
0
        public async Task <IHttpActionResult <PollView <TUserView> > > Post([FromBody] PollView <TUserView> pollView)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest <PollView <TUserView> >(ModelState));
            }

            using (var transaction = session.BeginTransaction())
            {
                var account = await accountService.GetCurrentUserAsync();

                // First we create and save the poll
                // then we create the possible answers
                // attached to that poll.
                var poll = new Poll <TUser>()
                {
                    Author   = account,
                    Question = pollView.Question,
                    // For now open and close date are hard coded
                    // TODO: Add date picker
                    OpenDate  = DateTime.Now,
                    CloseDate = DateTime.Now.AddDays(7)
                };
                await session.SaveAsync(poll);

                var newAnswers = pollView.PossibleAnswers.Where(a => a.Text != null).ToList();

                foreach (var answerDto in newAnswers)
                {
                    answerDto.Text = answerDto.Text.Trim();
                    if (answerDto.Text.Length >= 1)
                    {
                        var possibleAnwer = pollDataMapping.FromPollDto(answerDto, poll);
                        await session.SaveAsync(possibleAnwer);
                    }
                }

                transaction.Commit();
                return(Created("GetPoll", poll.Id, pollDataMapping.ToPollDto(poll)));
            }
        }
Esempio n. 5
0
        public async Task ProcessAsync(Update update)
        {
            _logger.LogInformation($"[ {DateTime.Now.ToLocalTime().ToString(CultureInfo.InvariantCulture)} ] Processing . message... , chatId: {update.Message.Chat.Id.ToString()}, {update.Message.From.Username}");

            Pin pin = new Pin(update.Message.ReplyToMessage);

            if (pin.IsActual())
            {
                Poll poll;

                if (PollsHelper.HasPoll(update.Message.Chat.Id))
                {
                    poll = PollsHelper.GetPoll(update.Message.Chat.Id);
                    await _botService.Client.DeleteMessageAsync(
                        chatId : poll.ChatId,
                        messageId : poll.MessageId);

                    PollsHelper.UpdatePoll(poll.ChatId, pin);
                }
                else
                {
                    poll = PollsHelper.CreatePoll(update.Message.Chat.Id, pin);
                }

                PollView pollView = poll.AsView();

                var message = await _botService.Client.SendTextMessageAsync(
                    chatId : update.Message.Chat.Id,
                    text : pollView.Text,
                    parseMode : ParseMode.Html,
                    replyMarkup : pollView.ReplyMarkup);

                poll.ChatId    = message.Chat.Id;
                poll.MessageId = message.MessageId;
            }

            await _botService.Client.DeleteMessageAsync(
                chatId : update.Message.Chat.Id,
                messageId : update.Message.MessageId);
        }
        public async Task Do()
        {
            var polls = PollsHelper.Polls;

            foreach (var poll in polls.Values)
            {
                _logger.LogInformation($"Battle Notification, chatId: {poll.ChatId.ToString()}");

                PollView pollView = poll.AsView();
                await _botService.Client.DeleteMessageAsync(
                    chatId : poll.ChatId,
                    messageId : poll.MessageId);

                var message = await _botService.Client.SendTextMessageAsync(
                    chatId : poll.ChatId,
                    text : pollView.Text,
                    parseMode : ParseMode.Html,
                    replyMarkup : pollView.ReplyMarkup);

                poll.ChatId    = message.Chat.Id;
                poll.MessageId = message.MessageId;
            }
        }
Esempio n. 7
0
        public async Task ProcessAsync(Update update)
        {
            _logger.LogInformation($"[ {DateTime.Now.ToLocalTime().ToString(CultureInfo.InvariantCulture)} ] Processing sleep callback... {update.CallbackQuery.From.Username}, chatId: {update.CallbackQuery.Message.Chat.Id.ToString()}");

            Poll     poll            = PollsHelper.GetPoll(update.CallbackQuery.Message.Chat.Id);
            bool     userListUpdated = poll.AddSleepVote(update.CallbackQuery.From);
            PollView pollView        = poll.AsView();

            if (userListUpdated)
            {
                await PollVoteThrottle.Acquire();

                await _botService.Client.EditMessageTextAsync(
                    chatId : poll.ChatId,
                    messageId : poll.MessageId,
                    text : pollView.Text,
                    parseMode : ParseMode.Html,
                    replyMarkup : pollView.ReplyMarkup);
            }

            await _botService.Client.AnswerCallbackQueryAsync(
                callbackQueryId : update.CallbackQuery.Id,
                text : pollView.SleepCallbackQueryAnswer);
        }
Esempio n. 8
0
 /// <summary>
 /// Creates a new instance of the <see cref="PollViewTemplateContainer"/> class.
 /// </summary>
 public PollViewTemplateContainer(PollView parent)
 {
     this.parentPollView = parent;
 }
    /// <summary>
    /// Displays appropriate controls regarding set properties.
    /// </summary>
    private void DisplayControls(string selectedPage, bool forceReload)
    {
        PollProperties.Visible      = false;
        AnswerList.Visible          = false;
        PollSecurity.Visible        = false;
        PollView.Visible            = false;
        PollView.StopProcessing     = true;
        headerLinks.Visible         = false;
        pnlPollsBreadcrumbs.Visible = false;
        pnlPollsLinks.Visible       = false;
        AnswerEdit.Visible          = false;
        btnResetAnswers.Visible     = true;
        imgResetAnswers.Visible     = true;

        if (forceReload)
        {
            selectedPage        = "0";
            tabMenu.SelectedTab = 0;
        }

        // Display appropriate tab
        switch (selectedPage)
        {
        // Answer list
        case "1":
            AnswerList.Visible = true;
            AnswerList.PollId  = ItemID;
            AnswerList.ReloadData(true);
            headerLinks.Visible   = true;
            pnlPollsLinks.Visible = true;
            break;

        // Answer edit
        case "answersedit":
            headerLinks.Visible         = true;
            pnlPollsBreadcrumbs.Visible = true;
            pnlPollsLinks.Visible       = true;
            AnswerEdit.Visible          = true;
            AnswerEdit.PollId           = ItemID;
            AnswerEdit.ReloadData();
            btnResetAnswers.Visible = false;
            imgResetAnswers.Visible = false;
            AnswerEditSelected      = true;

            // Initialize breadcrumbs
            InitializeBreadcrumbs();
            break;

        // Poll security
        case "2":
            PollSecurity.Visible = true;
            PollSecurity.ItemID  = ItemID;
            PollSecurity.ReloadData();
            break;

        // Poll view
        case "3":
            PollView.Visible = true;
            InitPollView(ItemID);
            PollView.StopProcessing = false;
            PollView.ReloadData(false);
            break;

        // Poll properties
        default:
            PollProperties.Visible = true;
            PollProperties.ItemID  = ItemID;

            PollProperties.ReloadData();
            break;
        }
    }
Esempio n. 10
0
        /// <summary>
        /// Overrides <see cref="WebControl.RenderContents"/>.
        /// </summary>
        protected override void RenderContents(HtmlTextWriter writer)
        {
            Table outerTable = new Table();

            outerTable.ControlStyle.CopyFrom(this.ControlStyle);
            if (outerTable.Font.Size == FontUnit.Empty)
            {
                outerTable.Font.Size = FontUnit.Parse("1em", System.Globalization.CultureInfo.InvariantCulture);
            }
            outerTable.Width = Unit.Percentage(100);


            Double totalVotes    = 0;
            Double barDisplayMax = 0;

            // First I need to get totals and percentages information
            foreach (ListItem item in Items)
            {
                Int32 itemVoteCount = Int32.Parse(item.Value, System.Globalization.CultureInfo.InvariantCulture);
                totalVotes += itemVoteCount;
                switch (this.BarDisplay)
                {
                case ResultDisplayType.Percentage:
                    barDisplayMax = totalVotes;
                    break;

                case ResultDisplayType.Count:
                    if (itemVoteCount > barDisplayMax)
                    {
                        barDisplayMax = itemVoteCount;
                    }
                    break;
                }
            }

            // Then I cycle thru the items and display the bar and vote count
            foreach (ListItem item in Items)
            {
                TableRow rRow = new TableRow();
                outerTable.Rows.Add(rRow);

                TableCell barHolder = new TableCell();
                barHolder.Width = Unit.Percentage(100);
                rRow.Cells.Add(barHolder);

                Label answerName = new Label();
                answerName.Text = item.Text + "<br>";
                barHolder.Controls.Add(answerName);

                HorizontalBar bar = new HorizontalBar();
                bar.EnableViewState = false;
                bar.Percentage      = (barDisplayMax != 0) ? (Double.Parse(item.Value, System.Globalization.CultureInfo.InvariantCulture) / barDisplayMax) * 100 : 0;
                ;
                bar.ControlStyle.CopyFrom(this.BarStyle);
                if (bar.Height == Unit.Empty)
                {
                    bar.Height = Unit.Pixel(10);
                }
                if (bar.BorderWidth == Unit.Empty)
                {
                    bar.BorderWidth = Unit.Pixel(1);
                }
                if (bar.ForeColor.Equals(bar.BackColor))
                {
                    PollView parent = this.NamingContainer as PollView;
                    if (parent != null && !parent.ForeColor.Equals(bar.BackColor))
                    {
                        bar.ForeColor = parent.ForeColor;
                    }
                    else
                    {
                        if (bar.BackColor.Equals(System.Drawing.Color.Black))
                        {
                            bar.ForeColor = System.Drawing.Color.White;
                        }
                        else
                        {
                            bar.ForeColor = System.Drawing.Color.Black;
                        }
                    }
                }
                barHolder.Controls.Add(bar);

                TableCell numericDisplay = new TableCell();
                switch (this.VoteCountDisplay)
                {
                case ResultDisplayType.Percentage:
                    Double votePercentage = (totalVotes != 0) ? (Double.Parse(item.Value, System.Globalization.CultureInfo.InvariantCulture) / totalVotes) * 100 : 0;
                    numericDisplay.Text = votePercentage.ToString("##0.0", System.Globalization.CultureInfo.InvariantCulture) + "%";
                    break;

                case ResultDisplayType.Count:
                    numericDisplay.Text = item.Value;
                    break;
                }
                numericDisplay.VerticalAlign = VerticalAlign.Bottom;
                rRow.Cells.Add(numericDisplay);
            }

            outerTable.RenderControl(writer);
        }
Esempio n. 11
0
    /// <summary>
    /// Displays appropriate controls regarding set properties.
    /// </summary>
    private void DisplayControls(string selectedPage, bool forceReload)
    {
        PollProperties.Visible      = false;
        AnswerList.Visible          = false;
        PollSecurity.Visible        = false;
        PollView.Visible            = false;
        PollView.StopProcessing     = true;
        headerLinks.Visible         = false;
        pnlPollsBreadcrumbs.Visible = false;
        pnlPollsLinks.Visible       = false;
        AnswerEdit.Visible          = false;
        btnResetAnswers.Visible     = true;
        imgResetAnswers.Visible     = true;

        if (forceReload)
        {
            selectedPage        = "0";
            tabMenu.SelectedTab = 0;
        }

        // Display appropriate tab
        switch (selectedPage)
        {
        // Poll properties
        case "0":
        default:
            PollProperties.Visible = true;
            PollProperties.ItemID  = ItemID;

            PollProperties.ReloadData();
            break;

        // Answer list
        case "1":
            AnswerList.Visible = true;
            AnswerList.PollId  = ItemID;
            AnswerList.ReloadData(true);
            headerLinks.Visible   = true;
            pnlPollsLinks.Visible = true;
            break;

        // Answer edit
        case "answersedit":
            headerLinks.Visible         = true;
            pnlPollsBreadcrumbs.Visible = true;
            pnlPollsLinks.Visible       = true;
            AnswerEdit.Visible          = true;
            AnswerEdit.PollId           = ItemID;
            AnswerEdit.ReloadData();
            btnResetAnswers.Visible = false;
            imgResetAnswers.Visible = false;
            AnswerEditSelected      = true;

            // Initialize breadcrumbs
            string currentPollAnswer = GetString("Polls_Answer_Edit.NewItemCaption");
            if (AnswerEdit.ItemID > 0)
            {
                PollAnswerInfo pollAnswerObj = PollAnswerInfoProvider.GetPollAnswerInfo(AnswerEdit.ItemID);
                if (pollAnswerObj != null)
                {
                    currentPollAnswer = GetString("Polls_Answer_Edit.AnswerLabel") + " " + pollAnswerObj.AnswerOrder.ToString();
                }
            }
            lblAnswer.Text = currentPollAnswer;
            break;

        // Poll security
        case "2":
            PollSecurity.Visible = true;
            PollSecurity.ItemID  = ItemID;
            PollSecurity.ReloadData();
            break;

        // Poll view
        case "3":
            PollView.Visible = true;
            InitPollView(ItemID);
            PollView.StopProcessing = false;
            PollView.ReloadData(false);
            break;
        }
    }
Esempio n. 12
0
 public ActionResult UpdatePoll(PollView pollView)
 {
     using (var repository=_repositoryProvider.GetRepository())
     {
         var poll = repository.Get<Poll>().Where(p => p.Id == pollView.Id).FirstOrDefault();
         if (poll == null)
             throw new ArgumentException(string.Format("Poll with Id {0} not found", pollView.Id));
         var deleteList = new List<PollOptions>();
         poll.Options.Each(p=>
         {
             var option = pollView.Options.Where(o => o.Id == p.Id).FirstOrDefault();
             if (option == null)
                 deleteList.Add(p);
             else
                 p.OptionText = option.OptionText;
         });
         deleteList.Each(d=>
         {
             var deletedOption = poll.Options.Where(p => p.Id == d.Id).FirstOrDefault();
             poll.Options.Remove(deletedOption);
         });
         repository.Update(poll);
         return PartialView("ManagePollItem", pollView);
     }
 }