Exemplo n.º 1
0
        public async Task <ActionResult <PollOption> > AddVote(int id, PollOption pollOption)
        {
            if (id != pollOption.Option_ID)
            {
                return(BadRequest());
            }

            var updatePollOption = await _context.PollOption.FirstOrDefaultAsync(s => s.Option_ID == pollOption.Option_ID);

            _context.Entry(updatePollOption).State = EntityState.Modified;

            updatePollOption.Vote = pollOption.Vote;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PollOptionExist(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(updatePollOption);
        }
Exemplo n.º 2
0
        public void ConstructorSortsPollOptions()
        {
            //arrange
            var opt1        = new PollOption(Guid.NewGuid(), false, new DateTime(1970, 01, 01, 03, 00, 00), new DateTime(1970, 01, 01, 03, 10, 00), "");
            var opt2        = new PollOption(Guid.NewGuid(), false, new DateTime(1970, 01, 01, 03, 00, 00), new DateTime(1970, 01, 01, 03, 05, 00), "");
            var opt3        = new PollOption(Guid.NewGuid(), false, new DateTime(1970, 01, 01, 02, 00, 00), new DateTime(1970, 01, 01, 04, 00, 00), "");
            var pollOptions = new List <PollOption> {
                opt1, opt2, opt3
            };

            //act
            Poll poll = new Poll(
                id: Guid.NewGuid(),
                subject: "",
                description: "",
                creationDateTime: DateTime.Now,
                dueDate: null,
                creator: new SchedUser(Guid.NewGuid(), ""),
                pollOptions: pollOptions);

            // assert
            Assert.Collection(poll.PollOptions,
                              x => Assert.Equal(opt3, x),
                              x => Assert.Equal(opt2, x),
                              x => Assert.Equal(opt1, x)
                              );
        }
Exemplo n.º 3
0
        public async Task <Poll> Post(CreateNewPollRequest req)
        {
            try
            {
                var newPoll = new Poll()
                {
                    ClientId    = req.ClientId,
                    Description = req.Description,
                };

                var autoId = await Db.InsertAsync(newPoll, selectIdentity : true);

                var newPollFromDb = await Db.SingleByIdAsync <Poll>(autoId);


                foreach (var option in req.Options)
                {
                    var o = new PollOption()
                    {
                        OptionText = option,
                        PollId     = newPollFromDb.Id,
                    };

                    await Db.SaveAsync <PollOption>(o);
                }

                return(newPollFromDb);
            }
            catch (System.Exception e)
            {
                throw new System.Exception(e.Message);
            }
        }
Exemplo n.º 4
0
        public void UpdatePollOption(Poll poll, PollOption option)
        {
            var results = poll.IsClosed || poll.Options.Any(x => x.IsChosen);

            this.IsChecked = results;
            this.Tag       = option;

            Ellipse.Opacity = results || option.IsBeingChosen ? 0 : 1;

            Percentage.Visibility = results ? Visibility.Visible : Visibility.Collapsed;
            Percentage.Text       = $"{option.VotePercentage}%";

            ToolTipService.SetToolTip(Percentage, results ? Locale.Declension("Vote", option.VoterCount) : null);

            Text.Text = option.Text;

            Zero.Visibility = results ? Visibility.Visible : Visibility.Collapsed;

            Votes.Maximum = results ? poll.Options.Max(x => x.VoterCount) : 1;
            Votes.Value   = results ? option.VoterCount : 0;

            Loading.IsActive = option.IsBeingChosen;



            AutomationProperties.SetName(this, option.Text);
        }
Exemplo n.º 5
0
        private void ShowResult()
        {
            //LoadPoll();
            poll = new Poll(ModuleId);

            if (currentUser != null)
            {
                userHasVoted = poll.UserHasVoted(currentUser);
            }
            else
            {
                userHasVoted = CookieHelper.CookieExists(poll.PollGuid.ToString());
            }

            if (userHasVoted)
            {
                lblVotingStatus.Text = PollResources.AlreadyVotedMessage;
            }

            rblOptions.Visible     = false;
            dlResults.Visible      = true;
            btnBackToVote.Visible  = !userHasVoted;
            btnShowResults.Visible = false;

            lblMessage.Text = PollResources.PollTotalVotesLabel + poll.TotalVotes;
            //IDataReader reader = PollOption.GetOptionsByPollGuid(poll.PollGuid);
            List <PollOption> pollOptions = PollOption.GetOptionsByPollGuid(poll.PollGuid);

            dlResults.DataSource = pollOptions;
            dlResults.DataBind();
            //reader.Close();

            //rptResults.DataSource = PollOption.GetOptionsByPollGuid(poll.PollGuid);
            //rptResults.DataBind();
        }
Exemplo n.º 6
0
        private void rblOptions_SelectedIndexChanged(object sender, EventArgs e)
        {
            // this is where the actual voting happens

            if (String.IsNullOrEmpty(rblOptions.SelectedValue))
            {
                return;
            }

            LoadPoll();
            userHasVoted = true;
            Guid       selectedOptionGuid = new Guid(rblOptions.SelectedValue);
            PollOption selectedOption     = new PollOption(selectedOptionGuid);

            Guid userGuid = Guid.Empty;

            if (currentUser != null)
            {
                userGuid = currentUser.UserGuid;
            }
            else
            {
                // Set a cookie and use it to keep anonymous polls from being too easy
                // to skew. Of course they can still do it
                if (poll.AnonymousVoting)
                {
                    CookieHelper.SetCookie(poll.PollGuid.ToString(), poll.PollGuid.ToString(), true);
                }
            }

            selectedOption.IncrementVotes(userGuid);

            ShowResult();
            pnlPollUpdate.Update();
        }
        public IHttpActionResult PutPollOption(int id, PollOption pollOption)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != pollOption.PollOptionID)
            {
                return(BadRequest());
            }

            db.Entry(pollOption).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PollOptionExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public bool AddPoll(AddPollViewModel pollModel)
        {
            using (var dbContextTransaction = _db.Database.BeginTransaction())
            {
                try
                {
                    var  answers = pollModel.Answer.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                    Poll poll    = new Poll();
                    poll.Question = pollModel.Question;
                    poll.Active   = true;
                    _db.Poll.Add(poll);
                    _db.SaveChanges();

                    foreach (var answer in answers)
                    {
                        PollOption option = new PollOption();
                        option.PollId  = poll.PollId;
                        option.Answers = answer;
                        option.Vote    = 0;
                        _db.PollOption.Add(option);
                        _db.SaveChanges();
                    }

                    dbContextTransaction.Commit();
                }
                catch
                {
                    //TO DO: log error here
                    dbContextTransaction.Rollback();
                }
            }

            return(true);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 加入投票
        /// </summary>
        /// <param name="pollModel"></param>
        /// <returns></returns>
        public bool AddPoll(AddPollViewModel pollModel)
        {
            try
            {
                var answers = pollModel.Answer.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var answer in answers)
                {
                    PollOption option = new PollOption();

                    string sql = "select * from PollOption where PollID=1 and Answers='" + answer + "'";
                    var    queryCurrentItem = _connection.Query <PollOption>(sql);
                    if (queryCurrentItem.Any())
                    {
                        option       = queryCurrentItem.First();
                        option.Vote += 1;
                        _connection.Update(option);
                    }
                    else
                    {
                        option.PollID  = 1;                       //poll.PollID;
                        option.Answers = answer;
                        option.Vote    = 1;
                        _connection.Insert(option);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(true);
        }
Exemplo n.º 10
0
        protected String GetOptionResultText(Object oOptionGuid)
        {
            Guid optionGuid = new Guid(oOptionGuid.ToString());

            PollOption option = new PollOption(optionGuid);

            String orderNumber = String.Empty;

            if (option.Poll.ShowOrderNumbers)
            {
                orderNumber = option.Order.ToString() + ". ";
            }

            String votesText = (option.Votes == 1) ? PollResources.PollVoteText : PollResources.PollVotesText;

            // TODO: Some pattern based resource...
            String text = orderNumber + option.Answer + ", " + option.Votes + " " + votesText;

            if (option.Poll.TotalVotes != 0)
            {
                int percent = (int)((double)option.Votes * 100 / option.Poll.TotalVotes + 0.5);
                text += " (" + percent + " %)";
            }

            return(text);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Devuelve un objeto modelado con los valores del dataRow que recibe por parámetro.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public PollOption ConvertToModel(DataRow data)
        {
            PollOption pollOption = new PollOption();

            pollOption.Id     = int.Parse(data["id"].ToString());
            pollOption.Option = data["option"].ToString();
            return(pollOption);
        }
Exemplo n.º 12
0
 public static string PollOption(PollOption pollOption)
 {
     if (pollOption.Url.IsEmpty())
     {
         return(pollOption.Text);
     }
     return(H.Anchor(pollOption.Url, pollOption.Text).ToString());
 }
Exemplo n.º 13
0
 public PollOptionEditor(PollOption option)
 {
     Poll        = option.Poll;
     Key         = option.Key;
     Description = option.Description;
     Locked      = option.Locked;
     Apply();
 }
Exemplo n.º 14
0
        public ActionResult DeleteConfirmed(int id)
        {
            PollOption pollOption = db.PollOptions.Find(id);

            db.PollOptions.Remove(pollOption);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemplo n.º 15
0
 public PartialViewResult AddOptionAndVote(PollOption option)
 {
     if (string.IsNullOrEmpty(option.Text))
     {
         var poll = _db.Polls.Find(option.PollId);
         return(PartialView("Display", poll));
     }
     option = UpdateOrAppOption(option);
     return(AddVote(option.PollOptionId));
 }
Exemplo n.º 16
0
        void OnOptionRemoved(PollOption option)
        {
            Dispatcher.BeginInvoke((Action)(() => {
                if (option.Poll != selectedpoll)
                {
                    return;
                }

                options.RemoveWhere(i => i.Key == option.Key);
            }));
        }
 void OnOptionRemoved(PollOption option)
 {
     notifications.ShowNotification(
         new MessageBuilder().Text("Poll Option Removed").BuildMessage(),
         new MessageBuilder()
         .Bold().Color(StreamColors.Option).Text(option.Key).Reset()
         .Text(" was removed from poll ")
         .Bold().Color(StreamColors.Option).Text(option.Poll).Reset()
         .BuildMessage()
         );
 }
Exemplo n.º 18
0
 public ActionResult Edit([Bind(Include = "PollOptionID,PollID,Answers,Vote")] PollOption pollOption)
 {
     if (ModelState.IsValid)
     {
         db.Entry(pollOption).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.PollID = new SelectList(db.Polls, "PollID", "Question", pollOption.PollID);
     return(View(pollOption));
 }
        public IHttpActionResult GetPollOption(int id)
        {
            PollOption pollOption = db.PollOptions.Find(id);

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

            return(Ok(pollOption));
        }
Exemplo n.º 20
0
        public void PollOption_Mapping()
        {
            Entity.PollOption entity = new()
            {
                Description = "Description",
                Id          = Guid.NewGuid(),
            };
            var model = PollOption.Of(entity);

            model.Description.Should().Be(entity.Description);
            model.Id.Should().Be(entity.Id);
        }
        public IHttpActionResult PostPollOption(PollOption pollOption)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.PollOptions.Add(pollOption);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = pollOption.PollOptionID }, pollOption));
        }
Exemplo n.º 22
0
        public IActionResult CreatePollOptions([FromBody] PollOption item)
        {
            if (item == null)
            {
                return(BadRequest());
            }

            _context.PollOptions.Add(item);
            _context.SaveChanges();

            return(CreatedAtRoute("GetPollOption", new { id = item.Id }, item));
        }
Exemplo n.º 23
0
        public static PollOption GetPoll(int id)
        {
            PollOption poll = new PollOption();

            poll.Options = new List <Option>();
            using (MySqlConnection conn = new MySqlConnection(ConnectionString.Build()))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    cmd.Connection  = conn;
                    cmd.CommandText = @"SELECT * FROM polls
                                        INNER JOIN poll_poll_options
                                        ON poll_id = poll_poll_id";
                    using (MySqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            poll.Id               = id;
                            poll.Poll             = new Poll();
                            poll.Poll.Id          = Convert.ToInt32(reader["poll_id"]);
                            poll.Poll.Title       = reader["title"].ToString();
                            poll.Poll.Description = reader["description"].ToString();
                            poll.Poll.Date        = Convert.ToDateTime(reader["date"]);
                        }
                    }
                }
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.Parameters.AddWithValue("@id", poll.Poll.Id);
                    cmd.CommandText = @"SELECT * FROM poll_options 
                                       INNER JOIN poll_poll_options  
                                       ON option_id = poll_option_id 
                                       WHERE poll_poll_id = @id";

                    using (MySqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Option option = new Option()
                            {
                                Id    = Convert.ToInt32(reader["poll_option_id"]),
                                Name  = reader["name"].ToString(),
                                Count = Convert.ToInt32(reader["count"])
                            };
                            poll.Options.Add(option);
                        }
                    }
                }
            }
            return(poll);
        }
Exemplo n.º 24
0
        void OnOptionAdded(PollOption option)
        {
            Dispatcher.BeginInvoke((Action)(() => {
                if (option.Poll != selectedpoll || options.Any(i => i.Key == option.Key))
                {
                    return;
                }

                options.RemoveWhere(i => i.Key == option.Key);
                options.Add(new PollOptionEditor(option));
            }));
        }
Exemplo n.º 25
0
 public IActionResult GetPoll(int id)
 {
     try
     {
         PollOption pollOption = PollManager.GetPoll(id);
         return(Ok(pollOption));
     }
     catch
     {
         return(BadRequest());
     }
 }
Exemplo n.º 26
0
 public IActionResult AddPoll(PollOption poll)
 {
     try
     {
         PollManager.AddPoll(poll);
         return(Ok());
     }
     catch
     {
         return(BadRequest());
     }
 }
Exemplo n.º 27
0
        public ActionResult Create([Bind(Include = "PollOptionID,PollID,Answers,Vote")] PollOption pollOption)
        {
            if (ModelState.IsValid)
            {
                db.PollOptions.Add(pollOption);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.PollID = new SelectList(db.Polls, "PollID", "Question", pollOption.PollID);
            return(View(pollOption));
        }
Exemplo n.º 28
0
 public IActionResult EditOption(Guid id)
 {
     try
     {
         PollOption option = _pollsRepository.GetOptionById(id);
         var        model  = _mapper.Map <EditOptionViewModel>(option);
         return(View(model));
     }
     catch
     {
         return(View());
     }
 }
Exemplo n.º 29
0
        public PollResultViewModel(long chatId, long messageId, Poll poll, PollOption option, IProtoService protoService, ICacheService cacheService, ISettingsService settingsService, IEventAggregator aggregator)
            : base(protoService, cacheService, settingsService, aggregator)
        {
            _chatId    = chatId;
            _messageId = messageId;
            _poll      = poll;
            _option    = option;

            Items           = new MvxObservableCollection <User>();
            LoadMoreCommand = new RelayCommand(LoadMoreExecute);

            LoadMoreExecute();
        }
 void OnOptionAdded(PollOption option)
 {
     notifications.ShowNotification(
         new MessageBuilder().Text("Poll Option Added").BuildMessage(),
         new MessageBuilder()
         .Bold().Color(StreamColors.Game).Text(option.Description).Reset()
         .Text(" with key ")
         .Bold().Color(StreamColors.Option).Text(option.Key).Reset()
         .Text(" was added to poll ")
         .Bold().Color(StreamColors.Option).Text(option.Poll).Reset()
         .BuildMessage()
         );
 }