public async void ExpirePoll(IPoll poll) { if (_activePolls.Contains(poll)) { _activePolls.Remove(poll); var channel = poll.Channel; var message = await channel.GetMessageAsync(poll.Message.Id); EmbedBuilder builder = new EmbedBuilder(); builder.WithTitle("Poll Results Are In!"); builder.WithDescription($"The results are in for {poll.Author.Mention}'s question \"{poll.Question}\":"); for (int i = 0; i < poll.Options.Length; i++) { var optionEmote = poll.AllowedEmoji[i]; var votes = 1; var key = message.Reactions.Keys.FirstOrDefault(k => k.Name == optionEmote.Name); if (key != null) { votes = message.Reactions[key].ReactionCount; } votes -= 1; builder.AddField(poll.Options[i], votes); } builder.WithFooter("* Initial bot votes not included in vote totals."); await poll.Channel.SendMessageAsync(embed : builder.Build()); await poll.Channel.DeleteMessageAsync(poll.Message); } }
private static Poll MapPollToModel(IPoll poll) { var result = new Poll(); result.PollID = poll.PollID.Value; result.UserID = poll.UserID; result.PollCategoryID = poll.PollCategoryID.Value; result.PollQuestion = poll.PollQuestion; result.PollImageLink = poll.PollImageLink; result.PollMaxAnswers = poll.PollMaxAnswers.Value; result.PollMinAnswers = poll.PollMinAnswers.Value; result.PollStartDate = poll.PollStartDate; result.PollEndDate = poll.PollEndDate; result.PollAdminRemovedFlag = poll.PollAdminRemovedFlag.GetValueOrDefault(false); result.PollDateRemoved = poll.PollDateRemoved; result.PollDeletedFlag = poll.PollDeletedFlag.GetValueOrDefault(false); result.PollDeletedDate = poll.PollDeletedDate; result.PollDescription = poll.PollDescription; result.PollOptions = poll.PollOptions.Select(_ => new PollOption { PollOptionID = _.PollOptionID, PollID = _.PollID, OptionPosition = _.OptionPosition, OptionText = _.OptionText }).ToList(); return(result); }
public PollAnswerViewModel(IPoll poll, IObjectFactory<IPollOption> objectFactory, short optionPosition) { this.poll = poll; this.objectFactory = objectFactory; this.optionPosition = optionPosition; }
public Poll Put([FromBody] Poll input) { IPoll poll = null; try { var userID = MyVoteAuthentication.GetCurrentUserID(); poll = this.PollFactory.Value.Create(userID.Value); var newPoll = this.SavePoll(input, poll); return(PollController.MapPollToModel(newPoll)); } catch (ValidationException ex) { var brokenRules = poll.GetBrokenRules().ToString(); throw new HttpResponseException( new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message.Replace(Environment.NewLine, " "), Content = new StringContent(brokenRules), RequestMessage = Request }); } catch (Exception ex) { throw new HttpResponseException( new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message.Replace(Environment.NewLine, " "), Content = new StringContent(ex.ToString()), RequestMessage = Request }); } }
private IPoll SavePoll(Poll input, IPoll poll) { poll.PollCategoryID = input.PollCategoryID; poll.PollQuestion = input.PollQuestion; poll.PollImageLink = input.PollImageLink; poll.PollMaxAnswers = input.PollMaxAnswers; poll.PollMinAnswers = input.PollMinAnswers; poll.PollStartDate = input.PollStartDate; poll.PollEndDate = input.PollEndDate; poll.PollAdminRemovedFlag = input.PollAdminRemovedFlag; poll.PollDateRemoved = input.PollDateRemoved; poll.PollDeletedFlag = input.PollDeletedFlag; poll.PollDeletedDate = input.PollDeletedDate; poll.PollDescription = input.PollDescription; // remove items from the real poll if they aren't in the input if (input.PollOptions == null) { poll.PollOptions.Clear(); } else { var toRemove = new List <IPollOption>(); toRemove.AddRange( poll.PollOptions.Where(item => input.PollOptions.All(_ => _.PollOptionID != item.PollOptionID))); foreach (var item in toRemove) { poll.PollOptions.Remove(item); } } // add or update according to new options list if (input.PollOptions != null && input.PollOptions.Count > 0) { var toAdd = new List <IPollOption>(); foreach (var item in input.PollOptions) { var existing = poll.PollOptions.FirstOrDefault(_ => _.PollOptionID == item.PollOptionID); if (existing == null) { var newOption = this.PollOptionFactory.Value.CreateChild(); newOption.OptionPosition = item.OptionPosition; newOption.OptionText = item.OptionText; toAdd.Add(newOption); } else { // updating existing item existing.OptionPosition = item.OptionPosition; existing.OptionText = item.OptionText; } } poll.PollOptions.AddRange(toAdd); } return(poll.Save() as IPoll); }
private ActionResult PollView(IPoll poll, string alias) { ViewData["alias"] = alias; ViewData[PortalExtensions.PortalViewContextKey] = PortalViewContext(); return(View("Poll", poll)); }
public GMainLoopWithPoll() { poll = new EPoll(); Console.WriteLine("GMainLoopWithPoll() {0}", (IntPtr)poll.Handle); poll_source = base.AddWatch(poll.Handle, WatchEventKind.In, delegate { Dispatch(); }); poll_handlers = new Dictionary<IntPtr, object[]>(); }
public PollOptionViewModel( IPoll poll, IObjectFactory <IPollOption> objectFactory, short optionPosition) { this.poll = poll; this.objectFactory = objectFactory; this.optionPosition = optionPosition; }
private void Child_Update(IPoll parent) { var entity = new MVPollOption(); DataMapper.Map(this, entity, this.IgnoredProperties.ToArray()); this.Entities.MVPollOptions.Attach(entity); this.Entities.SetState(entity, EntityState.Modified); this.Entities.SaveChanges(); }
public async void CreatePoll(IUser author, IMessageChannel channel, TimeSpan duration, string question, string[] options) { IPoll poll = _activePolls.FirstOrDefault(p => p.Author.Id == author.Id && p.Channel.Id == channel.Id); if (poll != null) { // user already has a poll running. We limit polls to one per user per channel } else { poll = new Poll { Author = author, Channel = channel, Question = question, Options = options, ExpiresOn = DateTime.Now + duration }; var optionEmoji = new string[] { "\u0031\uFE0F\u20E3", // 1 "\u0032\uFE0F\u20E3", // 2 "\u0033\uFE0F\u20E3", // 3 "\u0034\uFE0F\u20E3", // 4 "\u0035\uFE0F\u20E3", // 5 "\u0036\uFE0F\u20E3", // 6 "\u0037\uFE0F\u20E3", // 7 "\u0038\uFE0F\u20E3", // 8 "\u0039\uFE0F\u20E3", // 9 }; StringBuilder pollText = new StringBuilder(); EmbedBuilder builder = new EmbedBuilder(); builder.WithTitle($"A new poll has started"); pollText.AppendLine($"{author.Mention} started a {duration.Minutes} minute poll for: \"{ question}\""); List <IEmote> addEmoji = new List <IEmote>(); for (int i = 0; i < options.Length; i++) { pollText.AppendLine($"\t{optionEmoji[i]} {options[i]}"); addEmoji.Add(new Emoji(optionEmoji[i])); } pollText.Append("To vote for an option, click on the respective emote below."); builder.WithDescription(pollText.ToString()); poll.AllowedEmoji = addEmoji; _activePolls.Add(poll); var message = await channel.SendMessageAsync(embed : builder.Build()); poll.Message = message; // add the emote options for this poll foreach (var emoji in addEmoji) { await message.AddReactionAsync(emoji); } } }
private void Child_Insert(IPoll parent) { this.PollID = parent.PollID; var entity = new MVPollOption(); DataMapper.Map(this, entity, this.IgnoredProperties.ToArray()); this.Entities.MVPollOptions.Add(entity); this.Entities.SaveChanges(); this.PollOptionID = entity.PollOptionID; }
public Task <CommandHandlerResult> ProcessCommand(BotCommand command, TwitchChannel channel) { switch (command.Command) { case "!poll": if (AuthorizeCommand(command.Sender, channel)) { if (!_activePolls.ContainsKey(channel.Name)) { string[] optionArray = command.Arguments.Split(new char[] { '!' }, StringSplitOptions.RemoveEmptyEntries); optionArray = optionArray.Select(x => x.Trim()).ToArray(); IPoll poll = _pollFactory.CreatePoll(optionArray); _activePolls.Add(channel.Name, poll); return(Task.FromResult(new CommandHandlerResult(ResultType.HandledWithMessage, $"Poll started! use !vote <number> to case your vote. {poll.PrintPoll()}", $"#{channel.Name}"))); } else { IPoll poll = _activePolls[channel.Name]; string pollResult = poll.EndPoll(); _activePolls.Remove(channel.Name); return(Task.FromResult(new CommandHandlerResult(ResultType.HandledWithMessage, pollResult, $"#{channel.Name}"))); } } else { //Even if we've done nothing, the poll command has been handled. return(Task.FromResult(new CommandHandlerResult(ResultType.Handled))); } case "!vote": if (_activePolls.ContainsKey(channel.Name)) { if (Int32.TryParse(command.SplitArgumentsOnSpaces(1)[0], out int votersChoice)) { _activePolls[channel.Name].CastVote(command.Sender, votersChoice); } } //Even if we've done nothing, the vote command has been handled. return(Task.FromResult(new CommandHandlerResult(ResultType.Handled))); default: return(Task.FromResult(new CommandHandlerResult(ResultType.NotHandled))); } }
public PollDrop(IPortalLiquidContext portalLiquidContext, IPoll poll) : base(portalLiquidContext, poll.Entity) { if (poll == null) { throw new ArgumentNullException("poll"); } Poll = poll; _options = new Lazy <PollOptionDrop[]>(() => poll.Options.Select(e => new PollOptionDrop(this, e)).ToArray(), LazyThreadSafetyMode.None); UserSelectedOption = Poll.UserSelectedOption == null ? null : new PollOptionDrop(this, Poll.UserSelectedOption); _pollUrl = new Lazy <string>(GetPollUrl, LazyThreadSafetyMode.None); _submitUrl = new Lazy <string>(GetSubmitUrl, LazyThreadSafetyMode.None); }
public ctrPoll(IPoll poll) { InitializeComponent(); //------Инициализация-членов-интерфейса------\\ Id = poll.Id; Owner_id = poll.Owner_id; Votes = poll.Votes; Answer_id = poll.Answer_id; Question = poll.Question; Answers = poll.Answers; //-------------------------------------------\\ foreach (Answer ans in Answers) { AnserPanel.Add(new ctrPollAnswer(ans, Answer_id)); } }
public static void AddTopicPoll(int postid, string question, SortedList <int, string> choices) { IPoll dal = Factory <IPoll> .Create("Poll"); PollInfo poll = new PollInfo { TopicId = postid, DisplayText = question }; foreach (var choice in choices) { PollChoiceInfo pollchoice = new PollChoiceInfo { DisplayText = choice.Value, Order = choice.Key }; poll.AddChoice(pollchoice); } dal.Add(poll); }
public PollOption(Entity entity, IPoll poll) { if (entity == null) { throw new ArgumentNullException("entity"); } Entity = entity; _poll = poll; Id = entity.GetAttributeValue <Guid>("adx_polloptionid"); DisplayOrder = entity.GetAttributeValue <int?>("adx_displayorder"); Name = entity.GetAttributeValue <string>("adx_name"); Answer = entity.GetAttributeValue <string>("adx_answer"); Votes = entity.GetAttributeValue <int?>("adx_votes"); }
public Poll Put(int id, [FromBody] Poll input) { IPoll poll = null; try { poll = this.PollFactory.Value.Fetch(id); var updatedPoll = this.SavePoll(input, poll); return(PollController.MapPollToModel(updatedPoll)); } catch (ValidationException ex) { var brokenRules = poll.GetBrokenRules().ToString(); throw new HttpResponseException( new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message.Replace(Environment.NewLine, " "), Content = new StringContent(brokenRules), RequestMessage = Request }); } catch (NullReferenceException ex) { throw new HttpResponseException( new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound, ReasonPhrase = string.Format("No resource matching {0} found", id), Content = new StringContent(ex.ToString()), RequestMessage = Request }); } catch (Exception ex) { throw new HttpResponseException( new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message.Replace(Environment.NewLine, " "), Content = new StringContent(ex.ToString()), RequestMessage = Request }); } }
private void UpdateBin(Question question, IPoll poll) { if (poll.Questions == null) { Questions = new List <Question> { question }; } else { Questions = poll.Questions; Questions.Add(question); } QuestionAmount = Questions.Count; var serialize = JsonSerializer.Serialize(this); File.WriteAllText(WorkingDir + poll.PollName + ".bin", serialize); }
public static void UpdateTopicPoll(int pollId, string question, SortedList <int, string> choices) { PollInfo poll = new PollInfo { Id = pollId, DisplayText = question, Choices = null }; foreach (var choice in choices) { if (poll.Choices == null) { poll.Choices = new List <PollChoiceInfo>(); } poll.Choices.Add(new PollChoiceInfo { DisplayText = choice.Value, Order = choice.Key, PollId = pollId }); } IPoll dal = Factory <IPoll> .Create("Poll"); dal.Update(poll); }
public static async Task <Stats> TestMeasure(IPoll <int, string> polling, IMeasure <int, string, Exception> measuring, Random rnd) { var stats = new Stats(); for (int i = 0; true; i++) { if (stats.StopAfter(3000, 250)) { Console.WriteLine("Stopped condition fired at iteration " + i); break; } var input = rnd.Next(500); var measure = await measuring.measure(polling, input); Console.WriteLine("Input " + input + " Done after " + measure.elapsed.Milliseconds); Console.WriteLine(measure.success ? "success" : "failure"); Console.WriteLine(measure.success ? measure.output : measure.error.Message); stats.addEvent(measure.elapsed.Milliseconds); } return(stats); }
public Task VoteInPollAsync(IPoll poll, VoteType voteType) { throw new NotImplementedException(); }
public void SubmitPoll(IPoll poll, IPollOption pollOption) { if (poll == null) { throw new InvalidOperationException("Unable to retrieve active poll."); } if (HasUserVoted(poll) || pollOption == null) { return; } var serviceContext = Dependencies.GetServiceContextForWrite(); var pollClone = serviceContext.CreateQuery("adx_poll") .FirstOrDefault(p => p.GetAttributeValue <Guid>("adx_pollid") == poll.Entity.Id); if (pollClone == null) { throw new InvalidOperationException("Unable to retrieve the current poll."); } var optionClone = serviceContext.CreateQuery("adx_polloption") .FirstOrDefault(o => o.GetAttributeValue <Guid>("adx_polloptionid") == pollOption.Entity.Id); if (optionClone == null) { throw new InvalidOperationException("Unable to retrieve the current poll option."); } var user = Dependencies.GetPortalUser(); var visitorId = Dependencies.GetRequestContext().HttpContext.Profile.UserName; if (user != null && user.LogicalName == "contact") { var contact = serviceContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == user.Id); if (contact == null) { throw new InvalidOperationException("Unable to retrieve the current user contact."); } var submission = new Entity("adx_pollsubmission"); submission.SetAttributeValue("adx_name", ResourceManager.GetString("Poll_Submission_For_Message") + contact.GetAttributeValue <string>("fullname")); serviceContext.AddObject(submission); serviceContext.AddLink(submission, "adx_contact_pollsubmission".ToRelationship(), contact); serviceContext.AddLink(submission, "adx_polloption_pollsubmission".ToRelationship(), optionClone); serviceContext.AddLink(submission, "adx_poll_pollsubmission".ToRelationship(), pollClone); IncrementVoteCount(serviceContext, pollOption); serviceContext.SaveChanges(); } else if (!string.IsNullOrEmpty(visitorId)) { var submission = new Entity("adx_pollsubmission"); submission.SetAttributeValue("adx_visitorid", visitorId); submission.SetAttributeValue("adx_name", "Poll submission for " + visitorId); serviceContext.AddObject(submission); serviceContext.AddLink(submission, "adx_polloption_pollsubmission".ToRelationship(), optionClone); serviceContext.AddLink(submission, "adx_poll_pollsubmission".ToRelationship(), pollClone); IncrementVoteCount(serviceContext, pollOption); serviceContext.SaveChanges(); } }
private static Poll MapPollToModel(IPoll poll) { var result = new Poll(); result.PollID = poll.PollID.Value; result.UserID = poll.UserID; result.PollCategoryID = poll.PollCategoryID.Value; result.PollQuestion = poll.PollQuestion; result.PollImageLink = poll.PollImageLink; result.PollMaxAnswers = poll.PollMaxAnswers.Value; result.PollMinAnswers = poll.PollMinAnswers.Value; result.PollStartDate = poll.PollStartDate; result.PollEndDate = poll.PollEndDate; result.PollAdminRemovedFlag = poll.PollAdminRemovedFlag.GetValueOrDefault(false); result.PollDateRemoved = poll.PollDateRemoved; result.PollDeletedFlag = poll.PollDeletedFlag.GetValueOrDefault(false); result.PollDeletedDate = poll.PollDeletedDate; result.PollDescription = poll.PollDescription; result.PollOptions = poll.PollOptions.Select(_ => new PollOption { PollOptionID = _.PollOptionID, PollID = _.PollID, OptionPosition = _.OptionPosition, OptionText = _.OptionText }).ToList(); return result; }
public virtual void AssignPoll(IPoll poll) { Poll = poll; }
public static bool CanEdit(this IPoll poll) { return(!poll.Completed || poll.Reopen.GetValueOrDefault(false)); }
private IPoll SavePoll(Poll input, IPoll poll) { poll.PollCategoryID = input.PollCategoryID; poll.PollQuestion = input.PollQuestion; poll.PollImageLink = input.PollImageLink; poll.PollMaxAnswers = input.PollMaxAnswers; poll.PollMinAnswers = input.PollMinAnswers; poll.PollStartDate = input.PollStartDate; poll.PollEndDate = input.PollEndDate; poll.PollAdminRemovedFlag = input.PollAdminRemovedFlag; poll.PollDateRemoved = input.PollDateRemoved; poll.PollDeletedFlag = input.PollDeletedFlag; poll.PollDeletedDate = input.PollDeletedDate; poll.PollDescription = input.PollDescription; // remove items from the real poll if they aren't in the input if (input.PollOptions == null) { poll.PollOptions.Clear(); } else { var toRemove = new List<IPollOption>(); toRemove.AddRange( poll.PollOptions.Where(item => input.PollOptions.All(_ => _.PollOptionID != item.PollOptionID))); foreach (var item in toRemove) { poll.PollOptions.Remove(item); } } // add or update according to new options list if (input.PollOptions != null && input.PollOptions.Count > 0) { var toAdd = new List<IPollOption>(); foreach (var item in input.PollOptions) { var existing = poll.PollOptions.FirstOrDefault(_ => _.PollOptionID == item.PollOptionID); if (existing == null) { var newOption = this.PollOptionFactory.Value.CreateChild(); newOption.OptionPosition = item.OptionPosition; newOption.OptionText = item.OptionText; toAdd.Add(newOption); } else { // updating existing item existing.OptionPosition = item.OptionPosition; existing.OptionText = item.OptionText; } } poll.PollOptions.AddRange(toAdd); } return poll.Save() as IPoll; }
public virtual void AssignPoll(IPoll poll) { poll.Users.Add(this); Polls.Add(poll); }
public bool Remove(IPoll poll) { return(polls.Remove(poll)); }
private void InitializeBindings(IPoll model) { this.Poll = model; this.Bindings.RemoveAll(); }
protected override void Dispose(bool disposing) { Console.WriteLine("GMainLoopWithPoll.Dispose()"); base.RemoveSource(poll_source); if(disposing) poll.Dispose(); poll = null; base.Dispose(disposing); }
async Task <PollingReturn <string, Exception> > IMeasure <int, string, Exception> .measure(IPoll <int, string> polling, int input) { var timer = new Stopwatch(); timer.Start(); var ret = new PollingReturn <string, Exception>(); var pollingTask = polling.poll(input); try { ret.output = await pollingTask; ret.success = true; } catch (Exception exc) { ret.error = exc; } timer.Stop(); ret.elapsed = timer.Elapsed; return(ret); }
public void Add(IPoll poll) { throw new NotImplementedException(); }
public bool HasUserVoted(IPoll poll) { return(poll.UserSelectedOption != null); }
private IPollOption CreatePollOption(IPoll poll, Entity entity) { return(new PollOption(entity, poll)); }
public void Add(IPoll poll) { polls.Add(poll); }
public bool Remove(IPoll poll) { throw new NotImplementedException(); }
public PollController(IPoll pollService) { this.pollService = pollService; }