Пример #1
0
 public void TestInitialize()
 {
     _voteForDateRepository  = new Mock <VoteForDateRepository>();
     _voteForPlaceRepository = new Mock <VoteForPlaceRepository>();
     _eventDetailsService    = new Mock <IEventDetailsService>();
     _votingService          = new VotingService(_eventDetailsService.Object, _voteForDateRepository.Object, _voteForPlaceRepository.Object);
 }
Пример #2
0
        public async Task UpVote_vote_does_not_exists_adding_vote_should_be_invoked()
        {
            votesRepositoryMock
            .Setup(x => x.AlreadyVoted(Link.Id, User.Id))
            .Returns(Task.FromResult(false));

            userRepositoryMock
            .Setup(x => x.GetById(User.Id))
            .Returns(Task.FromResult(User));

            votesRepositoryMock
            .Setup(x => x.Add(new Vote()));

            linksRepositoryMock
            .Setup(x => x.Update(Link));

            var service = new VotingService(linksRepositoryMock.Object,
                                            votesRepositoryMock.Object, userRepositoryMock.Object);


            int upsBefore = Link.Ups;

            await service.UpVote(Link.Id, User.Id);

            Assert.Equal(upsBefore + 1, Link.Ups);
            votesRepositoryMock.Verify(x => x.Add(It.IsAny <Vote>()), Times.Once);
        }
Пример #3
0
        public void CastVote_WithUserThatCannotVote_IgnoresVote()
        {
            // Arrange
            var couchDbMock = new Mock <ICouchDBService>();

            couchDbMock.Setup(c => c.FindByUsername <User>(It.IsAny <string>())).Returns(new []
            {
                new User {
                    Username = "******"
                }
            });
            couchDbMock.Setup(c => c.FindByUsername <Vote>(It.IsAny <string>())).Returns(new[]
            {
                new Vote {
                    Username = "******"
                },
                new Vote {
                    Username = "******"
                },
                new Vote {
                    Username = "******"
                }
            });

            // Act
            var votingService = new VotingService(couchDbMock.Object);

            votingService.CastVote("*****@*****.**", 1, 2);

            // Assert
            couchDbMock.Verify(c => c.Set <Vote>(It.IsAny <Vote>()), Times.Never);
        }
Пример #4
0
        public void GetVoterTurnout_WithNoVotes_ReturnsZeroTurnout()
        {
            // Arrange
            var couchDbMock = new Mock <ICouchDBService>();

            couchDbMock.Setup(c => c.FindByLevel <User>(It.Is <Level>(l => l == Level.A))).Returns(new[]
            {
                new User {
                    Username = "******", Level = Level.A
                },
                new User {
                    Username = "******", Level = Level.A
                },
                new User {
                    Username = "******", Level = Level.A
                }
            });

            // Act
            var votingService = new VotingService(couchDbMock.Object);
            var turnouts      = votingService.GetVoterTurnout();

            // Assert
            Assert.AreEqual(0, turnouts[Level.A]);
        }
Пример #5
0
        public void UserCanVote_UserWithAllVotes_ReturnsFalse()
        {
            // Arrange
            var couchDbMock = new Mock <ICouchDBService>();

            couchDbMock.Setup(c => c.FindByUsername <Vote>(It.IsAny <string>())).Returns(new[]
            {
                new Vote {
                    Username = "******"
                },
                new Vote {
                    Username = "******"
                },
                new Vote {
                    Username = "******"
                }
            });

            // Act
            var votingService = new VotingService(couchDbMock.Object);
            var canVote       = votingService.UserCanVote("*****@*****.**");

            // Assert
            Assert.IsFalse(canVote);
        }
        private async void ClientVoteCompletedPage_Loaded(object sender, RoutedEventArgs e)
        {
            var election = await BlobCache.UserAccount.GetObject <Setting>("ElectionSettings");

            MainGrid.Background = new ImageBrush(Util.BytesToBitmapImage(election.Logo))
            {
                Opacity = 0.2
            };
            try
            {
                //make rabbitmq event here for submission of votes
                //submission of skipped votes
                await VotingService.CastVote(_votes, _voter, _skippedVotes);

                Text.Text = $"Good Bye {_voter.VoterName.ToUpper()}, Thank You For Voting";
            }
            catch (Exception)
            {
                Text.Text = $"Sorry An Error Occured.\nYour Votes Were not Submitted.\n Contact the Administrators";
                await VotingService.ResetVoter(_voter);
            }
            var _timer = new DispatcherTimer();

            _timer.Interval = new TimeSpan(0, 0, 0, 3);
            _timer.Tick    += _timer_Tick;
            _timer.Start();
        }
Пример #7
0
        public Group_PollViewModel(Poll poll)
        {
            Experts = new List <Group_Poll_ExpertViewModel>();

            if (poll != null)
            {
                Id         = poll.Id;
                Title      = poll.Title;
                Text       = poll.Text;
                IsFinished = poll.IsFinished;
                State      = (ContentState)poll.State;
                if (poll.GroupId.HasValue)
                {
                    GroupId = poll.GroupId.Value;
                }


                var publishData = VotingService.GetPollPublishData(poll.Id);
                if (publishData != null)
                {
                    IsCreationInProccess = true;
                    IsCreationFailed     = publishData.IsFailed;
                }

                PollStatus = new Group_PollStatusViewModel(poll);

                var totalBulletins = poll.Bulletins.Count;
                foreach (var expertBulletin in poll.Bulletins.Where(x => x.Weight > 1).OrderByDescending(x => x.Weight).Take(5))
                {
                    Experts.Add(new Group_Poll_ExpertViewModel(expertBulletin, totalBulletins));
                }
            }
        }
Пример #8
0
        public ActionResult EditPetition(_EditPetitionViewModel model)
        {
            if (!Request.IsAuthenticated)
            {
                throw new AuthenticationException();
            }

            if (ModelState.IsValid)
            {
                PetitionContainer data = new PetitionContainer
                {
                    GroupId   = model.GroupId,
                    Id        = model.Id,
                    IsPrivate = model.IsPrivate,
                    Tags      = model.TagTitles,
                    Text      = model.Text,
                    Title     = model.Title
                };

                Petition petition = VotingService.EditPetition(data, UserContext.Current.Id);

                return(RedirectToAction("petition", petition.Controller, new { id = petition.Id }));
            }

            if (model.GroupId != null)
            {
                View("../group/editpetition", model);
            }

            return(View("../user/editpetition", model));
        }
Пример #9
0
        public void _Call_VoteFactory_CreateVote_IfVoteNotNull(int postId, string userId)
        {
            //Arrange
            var vote  = new Vote();
            var votes = new List <Vote>()
            {
                vote
            }.AsQueryable();

            var post = new Post();

            var mockedRepository = new Mock <IRepository <Vote> >();

            mockedRepository.Setup(r => r.GetAll).Returns(votes);

            var mockedUnitOfWork  = new Mock <IUnitOfWork>();
            var mockedVoteFactory = new Mock <IVoteFactory>();

            var mockedPostService = new Mock <IPostService>();

            mockedPostService.Setup(p => p.GetPostById(It.IsAny <int>())).Returns(post);

            var voteService = new VotingService(
                mockedRepository.Object,
                mockedUnitOfWork.Object,
                mockedVoteFactory.Object,
                mockedPostService.Object);

            //Act
            voteService.Vote(postId, userId);

            //Assert
            mockedVoteFactory.Verify(r => r.CreateVote(postId, userId), Times.Once);
        }
Пример #10
0
 public async Task Vote(string title, string description, Emoji yesEmoji, Emoji noEmoji,
                        [Remainder][OverrideTypeReader(typeof(TimeSpanCustomReader))]
                        TimeSpan time)
 {
     await VotingService.StartVote(title, description, time, yesEmoji.Name, noEmoji.Name, Context.Guild, Context.Channel,
                                   Context.User);
 }
Пример #11
0
 private void VoteDown()
 {
     if (_voted)
     {
         return;
     }
     VotingService.VoteDown(_clientId);
     _voted = true;
 }
Пример #12
0
        private async void BtnReset_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(ResetIndexNumber.Text))
            {
                await VotingService.ResetVoter(new Voter { IndexNumber = ResetIndexNumber.Text });

                await metroWindow.ShowMessageAsync("Sucecss", $"Successfully reset Voter");
            }
        }
Пример #13
0
 public CastVoteTests()
 {
     _repo = A.Fake <IVotingRepository>(options => options.Strict());
     A.CallTo(() => _repo.GetCitizen(CitizenId)).Returns(Citizen);
     A.CallTo(() => _repo.GetBallotItem(BallotItemId)).Returns(BallotItemWithoutWriteIn);
     A.CallTo(() => _repo.IsCitizenEligibleToVoteOnBallotItem(CitizenId, BallotItemId)).Returns(true);
     A.CallTo(() => _repo.GetVote(CitizenId, BallotItemId)).Returns(null);
     A.CallTo(() => _repo.AddVote(CitizenId, BallotItemId, A <int> ._, A <string> ._)).Returns(VoteConfirmation);
     _service = new VotingService(_repo);
 }
Пример #14
0
        public ActionResult GetSectionVotingDetails(int id)
        {
            VotingService      service = new VotingService();
            VotingResultsModel model   = service.GetResultsForLawSection(new VotingResultsModel {
                ID = id
            });

            model.ActionName = "FilterSectionVotingDetails";

            return(PartialView("_VotingDetails", model));
        }
Пример #15
0
        public ActionResult PublishPetition(Guid id)
        {
            if (!Request.IsAuthenticated)
            {
                throw new AuthenticationException();
            }

            Petition petition = VotingService.PublishPetition(id, UserContext.Current.Id);

            return(RedirectToAction("petition", petition.Controller, new { id = petition.Id }));
        }
Пример #16
0
        public ActionResult FilterSectionVotingDetails(VotingResultsModel model)
        {
            TryUpdateModel(model);

            VotingService service = new VotingService();

            model            = service.GetResultsForLawSection(model);
            model.ActionName = "FilterSectionVotingDetails";

            return(PartialView("_VotingDetails", model));
        }
Пример #17
0
        public void CastVote_WithNonExistentUser_ThrowsException()
        {
            // Arrange
            var couchDbMock = new Mock <ICouchDBService>();

            couchDbMock.Setup(c => c.FindByUsername <User>(It.IsAny <string>())).Returns(new List <User>());

            // Act
            var votingService = new VotingService(couchDbMock.Object);

            votingService.CastVote("*****@*****.**", 1, 2);
        }
Пример #18
0
        protected override void OnInitialized()
        {
            base.OnInitialized();
            _question = VotingService.Question;

            var currentResults = VotingService.GetCurrentState();

            _up       = currentResults.ThumbsUp;
            _down     = currentResults.ThumbsDown;
            _question = VotingService.Question;
            VotingService.VoteChangedEventHandler += OnVoteHasChanged;
            VotingService.ResetEventHandler       += OnReset;
        }
Пример #19
0
        /// <summary>
        /// Checks all server settings, auto vc channels, active vc channels and the welcome message
        /// </summary>
        /// <returns></returns>
        public async Task CheckConnectedServerSettings()
        {
            Logger.Log("Checking pre-connected server settings...");

            //To avoid saving possibly 100 times we will only save once if something has changed
            bool somethingChanged = false;

            List <ServerList> serversToRemove = new List <ServerList>();

            ServerList[] servers = ServerListsManager.GetServers();
            foreach (ServerList server in servers)
            {
                //The bot is not longer in this guild, remove it from the server settings
                if (_client.GetGuild(server.GuildId) == null)
                {
                    somethingChanged = true;
                    serversToRemove.Add(server);
                    continue;
                }

                await CheckServerWelcomeSettings(server);
                await CheckServerRuleMessageChannel(server);

                CheckServerVoiceChannels(server);
                CheckServerActiveVoiceChannels(server);
                CheckServerPerms(server);

                //Start up all votes
                foreach (Vote serverVote in server.Votes)
                {
#pragma warning disable 4014
                    Task.Run(() => VotingService.RunVote(serverVote, _client.GetGuild(server.GuildId)));
#pragma warning restore 4014
                }
            }

            //Like all the other ones, we remove all the unnecessary servers after to avoid System.InvalidOperationException
            foreach (ServerList toRemove in serversToRemove)
            {
                Logger.Log($"The bot is not longer in the {toRemove.GuildId}, Removing server settings...");
                ServerListsManager.RemoveServer(toRemove);
            }

            //If a server was updated then save the ServerList.json file
            if (somethingChanged)
            {
                ServerListsManager.SaveServerList();
            }

            Logger.Log("Checked all server settings.");
        }
Пример #20
0
        public void GetVoterTurnout_WithNoMatchingUsers_ReturnsEmptyResult()
        {
            // Arrange
            var couchDbMock = new Mock <ICouchDBService>();

            couchDbMock.Setup(c => c.FindByLevel <User>(It.IsAny <Level>())).Returns(new List <User>());

            // Act
            var votingService = new VotingService(couchDbMock.Object);
            var turnouts      = votingService.GetVoterTurnout();

            // Assert
            Assert.AreEqual(0, turnouts.Keys.Count);
        }
Пример #21
0
        public ActionResult SignPetition(Guid id)
        {
            if (!Request.IsAuthenticated)
            {
                throw new AuthenticationException();
            }

            if (ModelState.IsValid)
            {
                Petition petition = VotingService.SignPetition(id, UserContext.Current.Id);
                UserContext.Abandon();
                return(RedirectToAction("petition", petition.Controller, new { id = petition.Id }));
            }

            return(Redirect(Request.UrlReferrer.PathAndQuery));
        }
Пример #22
0
        private async Task SetClientIp()
        {
            const string identifier = "VotingClientID";

            if (await LocalStorage.ContainKeyAsync(identifier))
            {
                _clientId = await LocalStorage.GetItemAsync <Guid>(identifier);
            }
            else
            {
                _clientId = Guid.NewGuid();
                await LocalStorage.SetItemAsync(identifier, _clientId);
            }

            _voted = VotingService.HasAlreadyVoted(_clientId);
            StateHasChanged();
        }
Пример #23
0
        public ActionResult InvitePetitionCoauthor(_EditPetitionCoauthorsViewModel model)
        {
            if (!Request.IsAuthenticated)
            {
                throw new AuthenticationException();
            }

            PetitionCoauthorContainer data = new PetitionCoauthorContainer
            {
                PetitionId = model.PetitionId,
                UserName   = model.UserNameForInvite
            };

            VotingService.InvitePetitionCoauthor(data, UserContext.Current.Id);

            return(Redirect(Request.UrlReferrer.PathAndQuery));
        }
Пример #24
0
        public ActionResult RespondToPetitionInvite(Guid id, bool accept)
        {
            if (!Request.IsAuthenticated)
            {
                throw new AuthenticationException();
            }

            Petition petition = VotingService.RespondToPetitionInvite(id, UserContext.Current.Id, accept);

            if (accept)
            {
                return(RedirectToAction("petition", petition.Controller, new { id = petition.Id }));
            }
            else
            {
                return(RedirectToAction("petitionnotices", "user"));
            }
        }
Пример #25
0
        public void _Initialize_NotNull_WhenEverythingPassed_Correctly()
        {
            //Arrange
            var mockedRepository  = new Mock <IRepository <Vote> >();
            var mockedUnitOfWork  = new Mock <IUnitOfWork>();
            var mockedVoteFactory = new Mock <IVoteFactory>();
            var mockedPostService = new Mock <IPostService>();

            //Act
            var voteService = new VotingService(
                mockedRepository.Object,
                mockedUnitOfWork.Object,
                mockedVoteFactory.Object,
                mockedPostService.Object);

            //Assert
            Assert.IsNotNull(voteService);
        }
Пример #26
0
        public ActionResult DeletePetitionCoauthor(Guid id)
        {
            if (!Request.IsAuthenticated)
            {
                throw new AuthenticationException();
            }

            Coauthor coauthor = DataService.PerThread.CoauthorSet.SingleOrDefault(x => x.Id == id);

            if (coauthor == null)
            {
                throw new Exception("Неверный идентификатор соавтора");
            }

            VotingService.DeletePetitionCoauthor(id, UserContext.Current.Id);

            return(RedirectToAction("editpetitioncoauthors", "user", new { id = coauthor.PetitionId }));
        }
Пример #27
0
        public async Task Vote(string title, string description, string yesEmoji, string noEmoji, [Remainder][OverrideTypeReader(typeof(TimeSpanCustomReader))] TimeSpan time)
        {
            if (!yesEmoji.ContainsUnicodeCharacter())
            {
                await Context.Channel.SendMessageAsync("Your yes emoji is not a unicode!");

                return;
            }

            if (!noEmoji.ContainsUnicodeCharacter())
            {
                await Context.Channel.SendMessageAsync("Your no emoji is not a unicode!");

                return;
            }

            await VotingService.StartVote(title, description, time, yesEmoji, noEmoji, Context.Guild, Context.Channel,
                                          Context.User);
        }
Пример #28
0
        public void _Call_Repository_GetAll(int postId, string userId)
        {
            //Arrange
            var mockedRepository  = new Mock <IRepository <Vote> >();
            var mockedUnitOfWork  = new Mock <IUnitOfWork>();
            var mockedVoteFactory = new Mock <IVoteFactory>();
            var mockedPostService = new Mock <IPostService>();

            var voteService = new VotingService(
                mockedRepository.Object,
                mockedUnitOfWork.Object,
                mockedVoteFactory.Object,
                mockedPostService.Object);

            //Act
            voteService.Vote(postId, userId);

            //Assert
            mockedRepository.Verify(r => r.GetAll, Times.Once);
        }
Пример #29
0
        public void UserCanVote_UserWithNoPreviousVotesOnTrack_ReturnsTrue()
        {
            // Arrange
            var couchDbMock = new Mock <ICouchDBService>();

            couchDbMock.Setup(c => c.FindByUsername <Vote>(It.IsAny <string>())).Returns(new[]
            {
                new Vote {
                    Username = "******", TrackId = 100
                },
                new Vote {
                    Username = "******", TrackId = 200
                }
            });

            // Act
            var votingService = new VotingService(couchDbMock.Object);
            var canVote       = votingService.UserCanVote("*****@*****.**", 300, 2);

            // Assert
            Assert.IsTrue(canVote);
        }
Пример #30
0
        static void Main(string[] args)
        {
            VotingService votingService = new VotingService();

            try
            {
                Console.Write("Informe o caminho do arquivo: ");
                string path = @"" + Console.ReadLine();

                Dictionary <string, int> result = votingService.GetResult(path);

                Console.WriteLine("Exibindo os resultados:");
                foreach (var item in result)
                {
                    Console.WriteLine(item.Key + ": " + item.Value);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Erro: {0}", e.Message);
            }
        }