/// <summary>
        /// Votes for answers
        /// </summary>
        /// <param name="answerid">Answer Id</param>
        /// <param name="vote">Vote</param>
        /// <returns></returns>
        public ActionResult VoteForAnswer(int answerid, int vote)
        {
            if (!Request.IsAuthenticated)
            {
                //Check if the user logged in
                return(Json(Resources.Global.YouHaveToLoginBeforeVote));
            }
            else
            {
                //Check if the user already voted for this answer
                bool isVoted = VoteManager.IsVotedForAnswer(answerid, WebSecurity.GetUserId(User.Identity.Name));
                if (isVoted)
                {
                    return(Json(Resources.Global.YouAlreadyVotedForThisAnswer));
                }


                //Check if the user want to vote for his own question
                if (AnswerManager.GetAnswer(answerid).UserId == WebSecurity.GetUserId(User.Identity.Name))
                {
                    return(Json(Resources.Global.YouCantVoteForYourOwnAnswer));
                }
                //Store the vote
                VoteManager.VoteAnswer(answerid, WebSecurity.GetUserId(User.Identity.Name), vote);

                return(Json(AnswerManager.GetVote(answerid)));
            }
        }
Beispiel #2
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.menuview);
            var listView = FindViewById <ListView> (Resource.Id.menu_listview);

            var votes = new VoteManager().ReadVotesFromRemote();

            var listAdapter = new VoteListAdapter(this, votes);

            listView.Adapter          = listAdapter;
            listAdapter.VoteSelected += (object sender, VoteSelectedEventArgs e) => {
                var vote       = e.SelectedVote;
                var voteString = Newtonsoft.Json.JsonConvert.SerializeObject(vote);


                if (DateTime.Now > e.SelectedVote.EndTime)
                {
                    Intent voteResultView = new Intent(this, typeof(VoteResultActivity));
                    voteResultView.PutExtra("vote", voteString);
                    StartActivity(voteResultView);
                }
                else
                {
                    Intent voteTitleView = new Intent(this, typeof(VoteTitleActivity));
                    voteTitleView.PutExtra("vote", voteString);
                    StartActivity(voteTitleView);
                }
            };
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            // Perform any additional setup after loading the view, typically from a nib.
            var votes = new VoteManager ().ReadVotesFromRemote ();

            var source = new TableSource (votes);

            voteTable.Source = source;

            source.VoteSelected += (object sender, VoteSelectedEventArgs e) => {

                SelectedVote = e.SelectedVote;

                if (DateTime.Now > e.SelectedVote.EndTime) {
                    InvokeOnMainThread (() => {
                        PerformSegue ("moveToVoteResultViewSegue", this);
                    });
                }
                else {

                    InvokeOnMainThread (() => {
                        PerformSegue ("moveToVoteFlowSegue", this);
                    });
                }
            };
        }
Beispiel #4
0
        private static void VoteAddManager(UnverifiedQuestion questionData)
        {
            var verifiedQuestionResult = new VerifyQuestionService().VerifyQuestion(questionData);

            verifiedQuestionResult.Match(
                verifiedQuestion =>
            {
                var id = Guid.NewGuid();
                IReadOnlyCollection <VoteEnum> votes = Array.Empty <VoteEnum>();
                var question = new AskQuestionResult.QuestionAdded(id, questionData.Title, questionData.Text, questionData.Tags, 0, votes);
                question     = new VoteManager().Update(question, VoteEnum.Up);
                question     = new VoteManager().Update(question, VoteEnum.Up);
                question     = new VoteManager().Update(question, VoteEnum.Down);

                Console.WriteLine(question.Votes.Count);

                return(Unit.Default);
            },
                ex =>
            {
                Console.WriteLine("Question data could not be verified");
                return(Unit.Default);
            }
                );
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.
            var votes = new VoteManager().ReadVotesFromRemote();

            var source = new TableSource(votes);

            voteTable.Source = source;

            source.VoteSelected += (object sender, VoteSelectedEventArgs e) => {
                SelectedVote = e.SelectedVote;

                if (DateTime.Now > e.SelectedVote.EndTime)
                {
                    InvokeOnMainThread(() => {
                        PerformSegue("moveToVoteResultViewSegue", this);
                    });
                }
                else
                {
                    InvokeOnMainThread(() => {
                        PerformSegue("moveToVoteFlowSegue", this);
                    });
                }
            };
        }
Beispiel #6
0
        private void castVoteButton_Click(object sender, EventArgs e)
        {
            string      voterID              = voterIDTextBox.Text;
            VoteManager aVoteManager         = new VoteManager();
            string      candidateName        = candidateSymbolComboBox.Text;
            bool        ifCastVoteSuccessful = aVoteManager.CastVote(candidateName);


            if (ifCastVoteSuccessful)
            {
                bool ifVoteStatusUpdated = aVoteManager.UpdateVoterVoteStatus(voterID);
                if (ifVoteStatusUpdated)
                {
                    MessageBox.Show("You have given vote successfully");
                    castVoteButton.Enabled          = false;
                    candidateSymbolComboBox.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Vote Status not updated");
                }
            }
            else
            {
                MessageBox.Show("Something is wrong");
            }
        }
        /// <summary>
        /// Votes for a questions
        /// </summary>
        /// <param name="questionid">Question Id</param>
        /// <param name="vote">Vote: +1 or -1</param>
        /// <returns></returns>
        public ActionResult VoteForQuestion(int questionid, int vote)
        {
            if (!Request.IsAuthenticated)
            {
                //If the user is not logged in, we create an error message
                return(Json(Resources.Global.YouHaveToLoginBeforeVote));
            }
            else
            {
                //Check if the user already voted for this question
                bool isvoted = VoteManager.IsVotedForQuestion(questionid, WebSecurity.GetUserId(User.Identity.Name));
                if (isvoted)
                {
                    return(Json(Resources.Global.YouAlreadyVotedForThisQuestion));
                }
                //Check if the user want to vote for his own question
                if (QuestionManager.GetQuestion(questionid).UserId == WebSecurity.GetUserId(User.Identity.Name))
                {
                    return(Json(Resources.Global.YouCantVoteForYourOwnQuestion));
                }
                //Store the vote
                VoteManager.Vote(questionid, WebSecurity.GetUserId(User.Identity.Name), vote);

                //Returns the new vote of the question
                return(Json(QuestionManager.GetVote(questionid)));
            }
        }
Beispiel #8
0
        public JsonResult LikeVote(string JsonResult)
        {
            string  result = JsonResult;
            Vote    vote   = null;
            JObject jobj   = JObject.Parse(JsonResult);

            vote = VoteManager.getVotedByComment_idAndParticipantId(Convert.ToInt32(jobj["CommentId"]), Convert.ToInt32(jobj["ParticipantId"]));
            int comment_id     = Convert.ToInt32(jobj["CommentId"]);
            int partucipant_id = Convert.ToInt32(jobj["ParticipantId"]);
            int ck             = Convert.ToInt32(jobj["isLike"]);

            if (vote == null)
            {
                vote               = new Vote();
                vote.CommentId     = comment_id;
                vote.ParticipantId = partucipant_id;

                vote.IsLike = null;
                if (ck == -1)
                {
                    vote.IsLike = null;
                }
                else if (ck == 0)
                {
                    vote.IsLike = false;
                }
                else if (ck == 1)
                {
                    vote.IsLike = true;
                }
                VoteManager.AddVoted(vote);
                VoteManager.SumVotedScore(Convert.ToInt32(jobj["CommentId"]));
            }
            else
            {
                vote.IsLike = null;
                if (ck == -1)
                {
                    vote.IsLike = null;
                }
                else if (ck == 0)
                {
                    vote.IsLike = false;
                }
                else if (ck == 1)
                {
                    vote.IsLike = true;
                }
                VoteManager.EditVotedIslike(vote);
                VoteManager.SumVotedScore(Convert.ToInt32(jobj["CommentId"]));
            }
            Comment comment = CommentsManage.GetCommentById(Convert.ToInt32(jobj["CommentId"]));
            String  res     = comment.VoteScore + "";

            String[] str = new String[2];
            str[0] = res;
            str[1] = ck + "";
            return(Json(str, JsonRequestBehavior.AllowGet));
        }
Beispiel #9
0
    IEnumerator PlayEventRoutine(GameEvent gameEvent)
    {
        AudioSource source = SoundManager.instance.Play2DSong("EventPopUp");

        yield return(new WaitForSeconds(source.clip.length - 3f));

        currentGameEvent = gameEvent;

        eventImage.sprite = currentGameEvent.sprite;
        eventText.text    = currentGameEvent.text;
        while (eventText.text.Contains("[p]"))
        {
            eventText.text = eventText.text.Replace("[p]", firstNames[Random.Range(0, firstNames.Length - 1)] + " " +
                                                    lastNames[Random.Range(0, lastNames.Length - 1)]);
        }

        // Play event sound
        // Wait for song to end

        // Slide Panel In
        Vector3 startPos = eventPanelInitPos;
        Vector3 endPos   = eventPanelInitPos + new Vector3(0f, panelMoveDist, 0f);

        float slideTimer = 0f;

        while (slideTimer < slideTime)
        {
            eventPanel.transform.position = Vector3.Lerp(startPos, endPos, slideTimer / slideTime);
            slideTimer += Time.deltaTime;
            yield return(0);
        }
        eventPanel.transform.position = endPos;

        if (gameEvent is DynamicEvent)
        {
            voteSlider.enabled = false;
//			DynamicEvent dynamicEvent = (DynamicEvent)gameEvent;
//			if(dynamicEvent.Success(village))
//			{
//
//			}
//			else
//			{
//
//			}
        }
        else
        {
            Debug.Log("Choice Event");
            voteSlider.enabled = true;
            VoteManager.instance.StopCoroutine("MoveVote");

            VoteManager.SetLastTime();
            yield return(new WaitForSeconds(eventVoteTime));

            VoteManager.instance.voteCallbacks = EventVoteCallback;
            VoteManager.QueryVotes(true);
        }
    }
Beispiel #10
0
    void EventVoteCallback(VoteManager voteManager)
    {
        if (currentGameEvent)
        {
            Debug.Log(voteManager.winningVote);

            if ((int)voteManager.winningVote < 4)
            {
                Debug.LogError("Direction received instead of answer!");
            }
            else if (voteManager.winningVote == VoteResponse.Yes)
            {
                SoundManager.instance.Play2DSong("HoorayChildren");

                eventText.text = currentGameEvent.yesResult.text;
                while (eventText.text.Contains("[p]"))
                {
                    eventText.text = eventText.text.Replace("[p]", firstNames[Random.Range(0, firstNames.Length - 1)] + " " +
                                                            lastNames[Random.Range(0, lastNames.Length - 1)]);
                }

                Village.instance.AddVillagers(currentGameEvent.noResult.peopleChange);
                Village.instance.AddVillagers(currentGameEvent.noResult.peopleChange);
            }
            else if (voteManager.winningVote == VoteResponse.No)
            {
                SoundManager.instance.Play2DSong("KidsBooing");

                eventText.text = currentGameEvent.noResult.text;
                while (eventText.text.Contains("[p]"))
                {
                    eventText.text = eventText.text.Replace("[p]", firstNames[Random.Range(0, firstNames.Length - 1)] + " " +
                                                            lastNames[Random.Range(0, lastNames.Length - 1)]);
                }

                Village.instance.AddVillagers(currentGameEvent.noResult.peopleChange);
                Village.instance.AddVillagers(currentGameEvent.noResult.peopleChange);
            }
            else if (currentGameEvent is ChoiceEvent &&
                     voteManager.winningVote == VoteResponse.Tie)
            {
                ChoiceEvent choiceEvent = (ChoiceEvent)currentGameEvent;

                eventText.text = choiceEvent.tieResult.text;
                while (eventText.text.Contains("[p]"))
                {
                    eventText.text = eventText.text.Replace("[p]", firstNames[Random.Range(0, firstNames.Length - 1)] + " " +
                                                            lastNames[Random.Range(0, lastNames.Length - 1)]);
                }

                Village.instance.AddVillagers(choiceEvent.tieResult.peopleChange);
                Village.instance.AddFood(choiceEvent.tieResult.foodChange);
            }

            voteSlider.value = voteManager.noVotePercentage;
            StartCoroutine(FinishEvent());
        }
    }
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            var serialziedLegislator = Arguments.GetString(BundleType.Legislator);

            _legislator = new Legislator().DeserializeFromJson(serialziedLegislator);

            _voteManager = new VoteManager(MyLogger);
            currentPage  = RetrieveCurrentPageIfAvailable(savedInstanceState);
        }
Beispiel #12
0
        public Server()
        {
            vManager = new VoteManager();

            // Создание файла опросника на тот случай если его нет.
            // Шаблон.
            //vManager.GenerateFooFile();

            listener = new TcpListener(new IPAddress(new Byte[] { 127, 0, 0, 1 }), 8789);
            clients  = new List <TcpClient>();
        }
Beispiel #13
0
        // moveToVerifyViewSegue
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            btnAdd.Enabled = false;

            PopMenuView = new PopMenuViewController();
            PopMenuView.FeatureSelected += (sender, e) => {
                Debug.WriteLine(e.SelectedFeatureName);

                if ("Edit" == e.SelectedFeatureName)
                {
                    btnAdd.Enabled = true;
                }
                else if ("Edit" == e.SelectedFeatureName)
                {
                    btnAdd.Enabled = true;
                }
                else
                {
                    btnAdd.Enabled = false;
                }
            };


            btnMenu.Clicked += (sender, e) => {
                UIPopoverController pop = new UIPopoverController(PopMenuView);
                pop.SetPopoverContentSize(new CGSize(200, 150), true);
                pop.PresentFromBarButtonItem(btnMenu, UIPopoverArrowDirection.Any, true);
            };

            btnAdd.Clicked += (sender, e) => {
                PerformSegue("moveToFlow01ViewSegue", this);
            };

            var editingVotes = new VoteManager().ReadEditVotesFromRemote();

            AppDelegate.EditingVotes.AddRange(editingVotes);

            var source = new TableSource(AppDelegate.EditingVotes);

            editingVoteTable.Source = source;

            source.EditingVoteSelected += (sender, e) => {
                AppDelegate.SelectedEditingVote = e.SelectedEditingVote;

                if (AppDelegate.SelectedEditingVote.Status == EditStatus.Request)
                {
                    PerformSegue("moveToVerifyViewSegue", this);
                }
            };
        }
Beispiel #14
0
 void Awake()
 {
     if (instance == null)
     {
         instance = this;
         DontDestroyOnLoad(gameObject);
     }
     else
     {
         if (instance != this)
         {
             Destroy(gameObject);
         }
     }
 }
Beispiel #15
0
        private void OnVoteClick(int position)
        {
            var vote = _votes[position];

            if (vote == null)
            {
                _logger.Error("Cannot process Vote click event. Unable to find vote at position " + position);
                return;
            }

            var title   = VoteManager.GetVoteDisplayTitle(vote);// $"{vote.Question} - {vote.Question}";
            var summary = VoteManager.GetVoteSummary(vote);

            //Not passing voter.source as additionalInfoLink since it is a JSON date link
            AppHelper.ShowDetailsDialog(_fragment, title, summary, string.Empty);// vote.Source);
        }
Beispiel #16
0
        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            base.OnBindViewHolder(holder, position);

            var vote = _votes[position] ?? null;

            if (vote == null)
            {
                _logger.Error("Cannot bind vote. Unable to find vote at position " + position);
                return;
            }

            var viewHolder = holder as VoteAdapterViewHolder;

            viewHolder.Question.Text = VoteManager.GetVoteDisplayTitle(vote);

            if (string.IsNullOrWhiteSpace(vote.Result))
            {
                viewHolder.VoteResult.Visibility = ViewStates.Gone;
            }
            else
            {
                viewHolder.VoteResult.Visibility = ViewStates.Visible;
                viewHolder.VoteResult.Text       = $"{voteResult}: {vote.Result}";
            }

            if (vote?.VotedAt == DateTime.MinValue)
            {
                viewHolder.VotedAt.Visibility = ViewStates.Gone;
            }
            else
            {
                viewHolder.VotedAt.Visibility = ViewStates.Visible;
                viewHolder.VotedAt.Text       = $"{date}: {vote.VotedAt.ToShortDateString()}";
            }

            var voteMoreInfo = VoteManager.GetVoteMoreInfoTitle(vote);

            viewHolder.MoreInfo.Text       = voteMoreInfo;
            viewHolder.MoreInfo.Visibility = string.IsNullOrWhiteSpace(voteMoreInfo)
                ? ViewStates.Gone
                : ViewStates.Visible;

            viewHolder.Image.SetImageResource(GetImageResourceForVoteCastedType(vote.VoteCastedByLegislator));
        }
Beispiel #17
0
    public void Vote()
    {
        var         playerManager = newPlayerManager.LocalPlayerInstance.GetComponent <newPlayerManager>();
        VoteManager myVM          = cl.VM;

        //Debug.Log(newPlayerManager.LocalPlayerInstance.GetPhotonView().IsMine + " owner active " + newPlayerManager.LocalPlayerInstance.GetComponent<newPlayerManager>().playerNameText.text );

        if (playerManager.photonView.IsMine && playerManager.hasVoted != true)
        {
            ;
        }
        {
            myVM.AgainstVote(playerManager, cl.thisPlayer);
            cl.GetComponent <Button>().interactable = false;
            gameObject.transform.parent.transform.gameObject.SetActive(false);
            playerManager.hasVoted = true;
        }
    }
Beispiel #18
0
        public IActionResult Vote(Option option)
        {
            int id = Int32.Parse(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value);

            try
            {
                VoteManager.Vote(new Vote
                {
                    UserId = id,
                    Option = option
                });
                return(Ok());
            }
            catch
            {
                return(BadRequest());
            }
        }
Beispiel #19
0
        /// <summary>
        /// Called when the voteban admin command is executed.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">An <see cref="AdminCommandEventArgs"/> object containing the event data.</param>
        private void OnVotebanCommandExecuted(object sender, AdminCommandEventArgs e)
        {
            if (e.Arguments.Count < 1)
            {
                e.Command.PrintUsage(e.Client, "<{0:t}>", "target");
                return;
            }

            if (this.ParseSingleTargetString(e.Client, e.Arguments[0], out var target))
            {
                if (VoteManager.CreateVote("Voteban Started", target.PlayerName).SetData(target).Start())
                {
                    this.LogAction(e.Client, target, "\"{0:L}\" initiated a ban vote against \"{1:L}\"", e.Client, target);
                    this.ShowActivity(e.Client, "Initiated Vote Ban", target.PlayerName);
                    VoteManager.CurrentVote.Ended += this.OnBanVoteEnded;
                }
            }
        }
Beispiel #20
0
    //void Movement()
    //{
    //	float hInput = Input.GetAxis("Horizontal");
    //	float vInput = Input.GetAxis("Vertical");

    //	if(Mathf.Abs(hInput) > WadeUtils.SMALLNUMBER)
    //	{
    //		if(inputTimer > inputTime)
    //		{
    //			MovePlayer(hInput > 0f ? VoteResponse.East : VoteResponse.West);
    //			inputTimer = 0f;
    //		}
    //	}
    //	else if(Mathf.Abs(vInput) > WadeUtils.SMALLNUMBER)
    //	{
    //		if(inputTimer > inputTime)
    //		{
    //			MovePlayer(vInput > 0f ? VoteResponse.North : VoteResponse.South);
    //			inputTimer = 0f;
    //		}
    //	}

    //	inputTimer += Time.deltaTime;
    //}

    public void MovePlayer(VoteManager voteManager)
    {
        int newX = x;
        int newY = y;

        switch (voteManager.winningVote)
        {
        case VoteResponse.North:
            newY++;
            break;

        case VoteResponse.East:
            newX++;
            break;

        case VoteResponse.South:
            newY--;
            break;

        case VoteResponse.West:
            newX--;
            break;

        case VoteResponse.Tie:
            return;
        }

        if (GridManager.IsGridLocationOpen(newX, newY))
        {
            Vector3 newPos = transform.position;
            newPos.x           = (float)newX;
            newPos.y           = (float)newY;
            transform.position = newPos;
        }
        else
        {
            GridObject gridObject = GridManager.Get(newX, newY);
            gridObject.Interact(GetComponent <Village>());
        }

        Village.ConsumeFood();
        Village.instance.AddHealthBasedOnFood();
    }
Beispiel #21
0
        void rptContents_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var voteInfo = new VoteInfo(e.Item.DataItem);

                var ltlItemIndex  = e.Item.FindControl("ltlItemIndex") as Literal;
                var ltlTitle      = e.Item.FindControl("ltlTitle") as Literal;
                var ltlKeywords   = e.Item.FindControl("ltlKeywords") as Literal;
                var ltlType       = e.Item.FindControl("ltlType") as Literal;
                var ltlStartDate  = e.Item.FindControl("ltlStartDate") as Literal;
                var ltlEndDate    = e.Item.FindControl("ltlEndDate") as Literal;
                var ltlUserCount  = e.Item.FindControl("ltlUserCount") as Literal;
                var ltlPVCount    = e.Item.FindControl("ltlPVCount") as Literal;
                var ltlIsEnabled  = e.Item.FindControl("ltlIsEnabled") as Literal;
                var ltlLogUrl     = e.Item.FindControl("ltlLogUrl") as Literal;
                var ltlPreviewUrl = e.Item.FindControl("ltlPreviewUrl") as Literal;
                var ltlEditUrl    = e.Item.FindControl("ltlEditUrl") as Literal;

                ltlItemIndex.Text = (e.Item.ItemIndex + 1).ToString();
                ltlTitle.Text     = voteInfo.Title;
                ltlKeywords.Text  = DataProviderWX.KeywordDAO.GetKeywords(voteInfo.KeywordID);
                ltlType.Text      = TranslateUtils.ToBool(voteInfo.ContentIsImageOption) ? "图文" : "文字";
                ltlType.Text     += TranslateUtils.ToBool(voteInfo.ContentIsCheckBox) ? " 多选" : " 单选";
                ltlStartDate.Text = DateUtils.GetDateAndTimeString(voteInfo.StartDate);
                ltlEndDate.Text   = DateUtils.GetDateAndTimeString(voteInfo.EndDate);
                ltlUserCount.Text = voteInfo.UserCount.ToString();
                ltlPVCount.Text   = voteInfo.PVCount.ToString();

                ltlIsEnabled.Text = StringUtils.GetTrueOrFalseImageHtml(!voteInfo.IsDisabled);

                var urlLog = BackgroundVoteLog.GetRedirectUrl(PublishmentSystemID, voteInfo.ID, GetRedirectUrl(PublishmentSystemID));
                ltlLogUrl.Text = $@"<a href=""{urlLog}"">投票记录</a>";

                var urlPreview = VoteManager.GetVoteUrl(voteInfo, string.Empty);
                urlPreview         = BackgroundPreview.GetRedirectUrlToMobile(urlPreview);
                ltlPreviewUrl.Text = $@"<a href=""{urlPreview}"" target=""_blank"">预览</a>";

                var urlEdit = BackgroundVoteAdd.GetRedirectUrl(PublishmentSystemID, voteInfo.ID);
                ltlEditUrl.Text = $@"<a href=""{urlEdit}"">编辑</a>";
            }
        }
Beispiel #22
0
        /// <summary>
        /// Called when the voteshutdown admin command is executed.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">An <see cref="AdminCommandEventArgs"/> object containing the event data.</param>
        private void OnVoteshutdownCommandExecuted(object sender, AdminCommandEventArgs e)
        {
            if (!this.enableVote.AsBool)
            {
                return;
            }

            if (this.shutdownInProgress)
            {
                this.ReplyToCommand(e.Client, $"{(this.autoRestart.AsBool ? "Restart" : "Shutdown")} In Progress");
                return;
            }

            if (VoteManager.CreateVote($"{(this.autoRestart.AsBool ? "Restart" : "Shutdown")} Vote").Start())
            {
                this.ShowActivity(e.Client, $"Initiated Vote {(this.autoRestart.AsBool ? "Restart" : "Shutdown")}");
                this.LogAction(e.Client, null, "\"{0:L}\" initiated a server shutdown vote", e.Client);
                VoteManager.CurrentVote.Ended += this.OnShutdownVoteEnded;
            }
        }
Beispiel #23
0
        /// <summary>
        /// Called when the vote admin command is executed.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">An <see cref="AdminCommandEventArgs"/> object containing the event data.</param>
        private void OnVoteCommandExecuted(object sender, AdminCommandEventArgs e)
        {
            if (e.Arguments.Count < 1)
            {
                e.Command.PrintUsage(e.Client, "<{0:t}> [{1:t}] ...", "question", "option");
                return;
            }

            if (e.Arguments.Count > 5)
            {
                this.ReplyToCommand(e.Client, "Too many options");
                return;
            }

            if (VoteManager.CreateVote(e.Arguments[0]).SetOptions(e.Arguments.GetRange(1, e.Arguments.Count - 1)).Start())
            {
                this.LogAction(e.Client, null, "\"{0:L}\" initiated a generic vote.", e.Client);
                this.ShowActivity(e.Client, "Initiated Vote", e.Arguments[0]);
                VoteManager.CurrentVote.Ended += this.OnVoteEnded;
            }
        }
Beispiel #24
0
        /// <inheritdoc/>
        public void InitMod()
        {
            ModEvents.ChatMessage.RegisterHandler((ClientInfo cInfo, EChatType chatType, int senderEntityId, string msg, string mainName, bool localizeMain, List <int> recipientEntityIds) => this.OnChatMessage(cInfo, chatType, msg, recipientEntityIds));
            ModEvents.GameAwake.RegisterHandler(this.OnGameAwake);
            ModEvents.GameShutdown.RegisterHandler(this.OnGameShutdown);
            ModEvents.GameStartDone.RegisterHandler(this.OnGameStartDone);
            ModEvents.PlayerDisconnected.RegisterHandler(this.OnPlayerDisconnected);
            ModEvents.PlayerLogin.RegisterHandler((ClientInfo cInfo, string compatibilityVersion, StringBuilder rejectReason) => this.OnPlayerLogin(cInfo, rejectReason));
            ModEvents.PlayerSpawnedInWorld.RegisterHandler(this.OnPlayerSpawnedInWorld);
            ModEvents.PlayerSpawning.RegisterHandler((ClientInfo cInfo, int chunkViewDim, PlayerProfile playerProfile) => this.OnPlayerSpawning(cInfo));
            ModEvents.SavePlayerData.RegisterHandler((ClientInfo cInfo, PlayerDataFile playerDataFile) => this.OnSavePlayerData(cInfo));

            Language.Init();
            ChatHelper.Init();
            ChatHook.Init();
            VoteManager.Init();

            ConVarManager.AutoExecConfig(null, true, "Core");

            PluginManager.Refresh();
        }
Beispiel #25
0
    //void Movement()
    //{
    //    float hInput = Input.GetAxis("Horizontal");
    //    float vInput = Input.GetAxis("Vertical");
    //    if(Mathf.Abs(hInput) > WadeUtils.SMALLNUMBER)
    //    {
    //        if(inputTimer > inputTime)
    //        {
    //            MovePlayer(hInput > 0f ? VoteResponse.East : VoteResponse.West);
    //            inputTimer = 0f;
    //        }
    //    }
    //    else if(Mathf.Abs(vInput) > WadeUtils.SMALLNUMBER)
    //    {
    //        if(inputTimer > inputTime)
    //        {
    //            MovePlayer(vInput > 0f ? VoteResponse.North : VoteResponse.South);
    //            inputTimer = 0f;
    //        }
    //    }
    //    inputTimer += Time.deltaTime;
    //}
    public void MovePlayer( VoteManager voteManager )
    {
        int newX = x;
        int newY = y;

        switch( voteManager.winningVote )
        {
        case VoteResponse.North:
            newY++;
            break;
        case VoteResponse.East:
            newX++;
            break;
        case VoteResponse.South:
            newY--;
            break;
        case VoteResponse.West:
            newX--;
            break;
        case VoteResponse.Tie:
            return;
        }

        if( GridManager.IsGridLocationOpen( newX, newY ) )
        {
            Vector3 newPos = transform.position;
            newPos.x = (float)newX;
            newPos.y = (float)newY;
            transform.position = newPos;
        }
        else
        {
            GridObject gridObject = GridManager.Get( newX, newY );
            gridObject.Interact( GetComponent<Village>() );
        }

        Village.ConsumeFood();
        Village.instance.AddHealthBasedOnFood();
    }
Beispiel #26
0
 public void OnAnswer(bool accept)
 {
     Debug.Log(accept.ToString());
     VoteManager.Vote(accept ? 1 : 0);
     GameObject.Destroy(gameObject);
 }
Beispiel #27
0
 // 다음날
 public void NextDay()
 {
     VoteManager.NextDay();
     ShowVote();
 }
Beispiel #28
0
 void Start()
 {
     VoteManager.Initialize("vote");
     ShowVote();
 }
Beispiel #29
0
 // 투표 동의
 public void Yes()
 {
     VoteManager.Vote(1);
 }
Beispiel #30
0
        private void ChestBehavior_ItemDrop(On.RoR2.ChestBehavior.orig_ItemDrop orig, ChestBehavior self)
        {
            if (!NetworkServer.active)
            {
                Debug.LogWarning("[Server] function 'System.Void RoR2.ChestBehavior::ItemDrop()' called on client");
                return;
            }

            var chestName = self.gameObject.name.ToLower();

            if (chestName.StartsWith("lunarchest"))
            {
                orig(self);
                return;
            }

            FieldInfo dropPickup      = self.GetType().GetField("dropPickup", BindingFlags.Instance | BindingFlags.NonPublic);
            var       dropPickupValue = (PickupIndex)dropPickup.GetValue(self);

            if (dropPickupValue != PickupIndex.none)
            {
                if (!DropItems && (chestName.StartsWith("chest") || chestName.StartsWith("goldchest")))
                {
                    var pickupController = gameObject.GetComponent <GenericPickupController>();

                    if (pickupController == null)
                    {
                        pickupController = this.gameObject.AddComponent <GenericPickupController>();
                    }

                    var characterBody = LocalUserManager.GetFirstLocalUser().cachedBody;

                    characterBody.inventory.GiveItem(dropPickupValue.itemIndex, 1);

                    pickupController.GetType().GetMethod("SendPickupMessage", BindingFlags.Static | BindingFlags.NonPublic)
                    .Invoke(pickupController, new object[] { characterBody.inventory.GetComponent <CharacterMaster>(), dropPickupValue });

                    dropPickup.SetValue(self, PickupIndex.none);
                    return;
                }

                orig(self);
                return;
            }

            // Steal opening sound from timed chest without changing to a problematic state
            EntityStateMachine component = self.GetComponent <EntityStateMachine>();

            if (component)
            {
                component.SetNextState(EntityState.Instantiate(new SerializableEntityStateType(typeof(EntityStates.TimedChest.Opening))));
            }

            // Generate list of 3 random item indexes
            var randomItemList = new List <PickupIndex>();

            randomItemList.Add(RollVoteItem(self));
            randomItemList.Add(RollVoteItem(self));
            randomItemList.Add(RollVoteItem(self));

            // Create a new vote, by passing valid poll options and vote duration
            var vote = new Vote(new List <string>(new string[] { "1", "2", "3" }), VoteDuration);

            vote.StartEventHandler += (_, __) =>
            {
                var characterBody = LocalUserManager.GetFirstLocalUser().cachedBody;

                var notificationQueue = characterBody.gameObject.GetComponent <VoteNotificationQueue>();

                if (notificationQueue == null)
                {
                    notificationQueue = characterBody.gameObject.AddComponent <VoteNotificationQueue>();
                }

                notificationQueue.OnVoteStart(randomItemList, VoteDuration);

                // Notify the event in chat
                SendChatMessage(
                    string.Format("Vote for the next item! (1) {0} | (2) {1} | (3) {2}",
                                  Language.GetString(randomItemList[0].GetPickupNameToken()),
                                  Language.GetString(randomItemList[1].GetPickupNameToken()),
                                  Language.GetString(randomItemList[2].GetPickupNameToken())
                                  )
                    );
            };

            vote.EndEventHandler += (_, e) =>
            {
                var votedItemName = Language.GetString(randomItemList[e.VotedIndex].GetPickupNameToken());

                float totalVotesCount = 1f;
                int   winnerCount     = 1;

                if (e.VoteCounter.Keys.Count > 0)
                {
                    totalVotesCount = e.VoteCounter.Sum(el => el.Value);
                    winnerCount     = e.VoteCounter[(e.VotedIndex + 1).ToString()];
                }

                SendChatMessage(
                    string.Format(
                        "({0}) {1} won! ({2})",
                        e.VotedIndex + 1,
                        votedItemName,
                        (winnerCount / totalVotesCount).ToString("P1", CultureInfo.InvariantCulture).Replace(" %", "%")
                        )
                    );

                var votedItem = randomItemList[e.VotedIndex];

                dropPickup.SetValue(self, votedItem);
                self.Open();
            };

            VoteManager.AddVote(vote);
        }
Beispiel #31
0
        private IResponseMessageBase GetResponseMessage(KeywordInfo keywordInfo, string keyword)
        {
            try
            {
                if (keywordInfo != null && !keywordInfo.IsDisabled)
                {
                    if (keywordInfo.KeywordType == EKeywordType.Text)
                    {
                        DataProviderWX.CountDAO.AddCount(publishmentSystemInfo.PublishmentSystemId, ECountType.RequestText);

                        var responseMessage = CreateResponseMessage <ResponseMessageText>();
                        responseMessage.Content = keywordInfo.Reply;
                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.News)
                    {
                        DataProviderWX.CountDAO.AddCount(publishmentSystemInfo.PublishmentSystemId, ECountType.RequestNews);

                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();

                        foreach (var resourceInfo in DataProviderWX.KeywordResourceDAO.GetResourceInfoList(keywordInfo.KeywordID))
                        {
                            var imageUrl = PageUtils.AddProtocolToUrl(PageUtility.ParseNavigationUrl(publishmentSystemInfo, resourceInfo.ImageUrl));

                            var pageUrl = string.Empty;
                            if (resourceInfo.ResourceType == EResourceType.Site)
                            {
                                if (resourceInfo.ChannelID > 0 && resourceInfo.ContentID > 0)
                                {
                                    pageUrl = PageUtilityWX.GetContentUrl(publishmentSystemInfo, resourceInfo.ChannelID, resourceInfo.ContentID, false);
                                }
                                else if (resourceInfo.ChannelID > 0)
                                {
                                    pageUrl = PageUtilityWX.GetChannelUrl(publishmentSystemInfo, resourceInfo.ChannelID);
                                }
                                else
                                {
                                    pageUrl = PageUtilityWX.GetChannelUrl(publishmentSystemInfo, publishmentSystemInfo.PublishmentSystemId);
                                }
                            }
                            else if (resourceInfo.ResourceType == EResourceType.Content)
                            {
                                pageUrl = PageUtilityWX.GetWeiXinFileUrl(publishmentSystemInfo, resourceInfo.KeywordID, resourceInfo.ResourceID);
                            }
                            else if (resourceInfo.ResourceType == EResourceType.Url)
                            {
                                pageUrl = resourceInfo.NavigationUrl;
                            }

                            responseMessage.Articles.Add(new Article()
                            {
                                Title       = resourceInfo.Title,
                                Description = MPUtils.GetSummary(resourceInfo.Summary, resourceInfo.Content),
                                PicUrl      = imageUrl,
                                Url         = pageUrl
                            });
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Coupon)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = CouponManager.Trigger(keywordInfo, keyword, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Vote)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = VoteManager.Trigger(publishmentSystemInfo, keywordInfo, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Message)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = MessageManager.Trigger(publishmentSystemInfo, keywordInfo, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Appointment)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = AppointmentManager.Trigger(keywordInfo, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Conference)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = ConferenceManager.Trigger(publishmentSystemInfo, keywordInfo, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Map)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = MapManager.Trigger(publishmentSystemInfo, keywordInfo, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.View360)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = View360Manager.Trigger(publishmentSystemInfo, keywordInfo, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Album)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = AlbumManager.Trigger(publishmentSystemInfo, keywordInfo, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Scratch)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = LotteryManager.Trigger(keywordInfo, ELotteryType.Scratch, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.BigWheel)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = LotteryManager.Trigger(keywordInfo, ELotteryType.BigWheel, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.GoldEgg)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = LotteryManager.Trigger(keywordInfo, ELotteryType.GoldEgg, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Flap)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = LotteryManager.Trigger(keywordInfo, ELotteryType.Flap, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.YaoYao)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = LotteryManager.Trigger(keywordInfo, ELotteryType.YaoYao, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Search)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = SearchManager.Trigger(publishmentSystemInfo, keywordInfo, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Store)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = StoreManager.Trigger(publishmentSystemInfo, keywordInfo, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Collect)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = CollectManager.Trigger(publishmentSystemInfo, keywordInfo, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                    else if (keywordInfo.KeywordType == EKeywordType.Card)
                    {
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                        var articleList     = CardManager.Trigger(publishmentSystemInfo, keywordInfo, RequestMessage.FromUserName);
                        if (articleList.Count > 0)
                        {
                            foreach (var article in articleList)
                            {
                                responseMessage.Articles.Add(article);
                            }
                        }

                        return(responseMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtils.AddLog(string.Empty, "Gexia Error", ex.StackTrace);
            }

            return(null);
        }
Beispiel #32
0
 // 투표 반대
 public void No()
 {
     VoteManager.Vote(0);
 }
        // moveToVerifyViewSegue
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            // Perform any additional setup after loading the view, typically from a nib.

            btnAdd.Enabled = false;

            PopMenuView = new PopMenuViewController ();
            PopMenuView.FeatureSelected += (sender, e) => {
                Debug.WriteLine (e.SelectedFeatureName);

                if ("Edit" == e.SelectedFeatureName) {
                    btnAdd.Enabled = true;
                }
                else if ("Edit" == e.SelectedFeatureName) {
                    btnAdd.Enabled = true;
                }
                else {
                    btnAdd.Enabled = false;
                }

            };

            btnMenu.Clicked += (sender, e) => {
                UIPopoverController pop = new UIPopoverController (PopMenuView);
                pop.SetPopoverContentSize (new CGSize (200, 150), true);
                pop.PresentFromBarButtonItem ( btnMenu, UIPopoverArrowDirection.Any, true);
            };

            btnAdd.Clicked += (sender, e) => {
                PerformSegue ("moveToFlow01ViewSegue", this);
            };

            var editingVotes = new VoteManager ().ReadEditVotesFromRemote ();
            AppDelegate.EditingVotes.AddRange (editingVotes);

            var source = new TableSource (AppDelegate.EditingVotes);

            editingVoteTable.Source = source;

            source.EditingVoteSelected += ( sender, e) => {

                AppDelegate.SelectedEditingVote = e.SelectedEditingVote;

                if (AppDelegate.SelectedEditingVote.Status == EditStatus.Request) {
                    PerformSegue ("moveToVerifyViewSegue", this);
                }
            };
        }