예제 #1
0
        public async void CreateTestAsync()
        {
            // Arrange
            using (var context = new VotingContext(new SqliteProvider().GetDbContextOptions()))
            {
                var saver = new Repository <Candidate>(context);

                // Act
                await saver.AddAsync(new Candidate()
                {
                    Name = "Ripal Barot"
                });

                await saver.AddAsync(new Candidate()
                {
                    Name = "Falguni Barot"
                });

                await saver.AddAsync(new Candidate()
                {
                    Name = "Neil Barot"
                });

                // Assert

                Assert.Equal(3, context.Candidates.Count());

                Assert.Equal("Neil Barot",
                             context.Candidates.Where(c => c.Name == "Neil Barot").Select(c => c.Name).FirstOrDefault());
            }
        }
예제 #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSingleton(c =>
            {
                var connection = new SqliteConnection("DataSource=:memory:");
                connection.Open();
                return(connection);
            });
            services.AddScoped(c =>
            {
                var options = new DbContextOptionsBuilder <VotingContext>()
                              .UseSqlite(c.GetService <SqliteConnection>())
                              .Options;
                var votingContext = new VotingContext(options);
                votingContext.Database.EnsureCreated();
                return(votingContext);
            });
        }
예제 #3
0
 public VotingManager()
 {
     Context             = new VotingContext();
     RankedVotingManager = new RankedVotingManager(Context);
     SingleVoteManager   = new SingleVoteManager(Context);
     MultiVoteManager    = new MultiVoteManager(Context);
 }
예제 #4
0
        public async void SearchTestAsync()
        {
            // Arrange
            using (var context = new VotingContext(new SqliteProvider().GetDbContextOptions()))
            {
                var repository = new Repository <Candidate>(context);

                // Act
                await repository.AddAsync(new Candidate()
                {
                    Id   = 1,
                    Name = "Ripal Barot"
                });

                await repository.AddAsync(new Candidate()
                {
                    Id   = 2,
                    Name = "Falguni Barot"
                });

                await repository.AddAsync(new Candidate()
                {
                    Id   = 3,
                    Name = "Neil Barot"
                });

                var candidateList = await repository.SearchAsync(candidate => candidate.Name.Contains("Barot"));


                // Assert
                Assert.Equal(3, candidateList.Count());
            }
        }
예제 #5
0
        public void GetSingleVoteItems()
        {
            var _context = new VotingContext();
            var _manager = new VotingManager();

            var canidates = _manager.SingleVoteManager.GetSingleVoteItems();
        }
예제 #6
0
        private static string GenerateHtml(Voting voting)
        {
            var    candidates = new VotingContext().Candidates.Where(c => c.VotingId == voting.ID).OrderBy(c => c.Surname).ToList();
            int    i          = 1;
            string s          =
                $"<h1>Głosowanie: {voting.Name}</h1><br>" +
                $"<h3>Szczegóły:</h3>" +
                $"<h5>Liczba wygrywających: {voting.NumberOfWinners}<br>" +
                $"Liczba uprawnionych do głosowania: {voting.NumberOfVoters}<br>" +
                $"Liczba kandydatów: {candidates.Count }</h5>" +
                $"<br><hr><br>" +
                $"<p> Pamiętaj, aby głos był ważny możesz oddać jedynie ustaloną ilość głosów. Oddanie ilości głosów większej niż {voting.NumberOfWinners} na kilku kandydatów spowoduje, iż głos będzie nieważny!<br> Po oddaniu głosu złóż kartkę na pół.<br>Głosowanie jest tajne! " +
                $"<br><hr><br>" +
                $"<h3>Kandydaci:</h3><br>" +
                $"<table style='width:100%;'><tr><th style='width:33%'>Imię</th><th style='width:33%'>Nazwisko</th><th style='width:33%'>Głos</th><tr>";

            foreach (var item in candidates)
            {
                if (i % 2 == 0)
                {
                    s += $"<tr><td style='text-align:center; padding:10px;'>{item.FirstName}</td><td style='text-align:center; padding:10px;'>{item.Surname}</td><td style=' padding:10px;'><div style='margin-left:42.5%; width:15%; height:30px; border: 1px solid black;'></div></td>";
                }
                else
                {
                    s += $"<tr style='background-color:gray'><td style='text-align:center; padding:10px;'>{item.FirstName}</td><td style='text-align:center; padding:10px;'>{item.Surname}</td><td style=' padding:10px;'><div style='margin-left:42.5%; width:15%; height:30px; border: 1px solid black;'></div></td>";
                }
                i++;
            }

            s += "</table>";

            return(s);
        }
        public async void CreateTestAsync()
        {
            // Arrange
            using (var context = new VotingContext(new SqliteProvider().GetDbContextOptions()))
            {
                IElectionSaver saver = new ElectionSaver(context);

                // Act
                await saver.AddAsync(new Election()
                {
                    ElectionQr     = Guid.NewGuid(),
                    CreatedDate    = DateTime.Now,
                    ExpirationDate = DateTime.Now.Add(new TimeSpan(5, 0, 0, 0))
                });

                await saver.AddAsync(new Election()
                {
                    ElectionQr     = Guid.NewGuid(),
                    CreatedDate    = DateTime.Now,
                    ExpirationDate = DateTime.Now.Add(new TimeSpan(5, 0, 0, 0))
                });

                await saver.AddAsync(new Election()
                {
                    ElectionQr     = Guid.NewGuid(),
                    CreatedDate    = DateTime.Now,
                    ExpirationDate = DateTime.Now.Add(new TimeSpan(5, 0, 0, 0))
                });

                // Assert

                Assert.Equal(3, context.Elections.Count());
            }
        }
예제 #8
0
        public void GetBallot()
        {
            var _context = new VotingContext();
            var ballot   = _context.Ballots.FirstOrDefault();

            Assert.IsNotNull(ballot);
        }
예제 #9
0
        public void GetJurisdiction()
        {
            var _context     = new VotingContext();
            var jurisdiction = _context.Jurisdictions.FirstOrDefault();

            Assert.IsNotNull(jurisdiction);
        }
예제 #10
0
        public async void UpdateTestAsync2()
        {
            // Arrange
            using (var context = new VotingContext(new SqliteProvider().GetDbContextOptions()))
            {
                var saver     = new Repository <Candidate>(context);
                var candidate = new Candidate
                {
                    Name = "Ripal Barot"
                };

                // Act
                candidate = await saver.AddAsync(candidate);

                candidate = new Candidate()
                {
                    Id   = 3,
                    Name = "Anila Barot"
                };

                var exception = await Record.ExceptionAsync(async() => await saver.UpdateAsync(candidate));

                // Assert
                Assert.NotNull(exception);
            }
        }
예제 #11
0
        public void AddAWriteInCanididate()
        {
            var _context = new VotingContext();
            var _manager = new VotingManager();

            var builder = new RankingVoteTicketBuilder();

            var RankingVoteItem = new RankingVoteItem
            {
                RankingVoteItemId  = Guid.NewGuid(),
                PrimeCandidateItem = new VotingApp.Models.CandidateItem()
                {
                    CandidateId = Guid.NewGuid(),
                    Name        = "Test",
                    JobId       = Guid.Parse("521C573E-91E8-47CA-ACBC-BF3D63706F29")
                },
                SubCandidateItem = new VotingApp.Models.CandidateItem()
                {
                    CandidateId = Guid.NewGuid(),
                    Name        = "Vice Test",
                    JobId       = Guid.Parse("057A2ED5-CDE9-44DB-9697-041B0F09555F")
                },
                Ranking = 1
            };

            _manager.Context.RankingVotes.Add(builder.GetEntity(RankingVoteItem));
            _manager.Context.SaveChanges();
        }
예제 #12
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // Aby uzyskać więcej informacji o sposobie włączania potwierdzania konta i resetowaniu hasła, odwiedź stronę https://go.microsoft.com/fwlink/?LinkID=320771
                    // Wyślij wiadomość e-mail z tym łączem
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Potwierdź konto", "Potwierdź konto, klikając <a href=\"" + callbackUrl + "\">tutaj</a>");
                    Profile profile = new Profile {
                        Login = model.Email
                    };
                    VotingContext db = new VotingContext();
                    db.Profiles.Add(profile);
                    db.SaveChanges();

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // Dotarcie do tego miejsca wskazuje, że wystąpił błąd, wyświetl ponownie formularz
            return(View(model));
        }
예제 #13
0
        public async void GetByIdTestAsync()
        {
            // Arrange
            using (var context = new VotingContext(new SqliteProvider().GetDbContextOptions()))
            {
                var repository = new Repository <Candidate>(context);

                // Act
                await repository.AddAsync(new Candidate()
                {
                    Id   = 1,
                    Name = "Ripal Barot"
                });

                await repository.AddAsync(new Candidate()
                {
                    Id   = 2,
                    Name = "Falguni Barot"
                });

                await repository.AddAsync(new Candidate()
                {
                    Id   = 3,
                    Name = "Neil Barot"
                });

                // Assert
                var candidate = await repository.GetByIdAsync(2);

                Assert.Equal("Falguni Barot", candidate.Name);
            }
        }
예제 #14
0
        public List <VoteResult> CreateElectionResult(List <VotingApp.Models.VoteResults> voteResults)
        {
            var _context = new VotingContext();
            var _builder = new VoteResultsBuilder();

            return(voteResults.Select(_builder.GetEntity).ToList());
        }
예제 #15
0
 private static void DataCleanUp(this VotingContext context)
 {
     context.Database.ExecuteSqlCommand("delete from OptionsToQuestions");
     context.Database.ExecuteSqlCommand("delete from Questions");
     context.Database.ExecuteSqlCommand("delete from FormSections");
     context.Database.ExecuteSqlCommand("delete from FormVersions");
     // context.Database.ExecuteSqlCommand("delete from County");
 }
예제 #16
0
 private static void DataCleanUp(this VotingContext context)
 {
     context.Database.ExecuteSqlCommand("delete from RaspunsDisponibil");
     context.Database.ExecuteSqlCommand("delete from Intrebare");
     context.Database.ExecuteSqlCommand("delete from Sectiune");
     context.Database.ExecuteSqlCommand("delete from VersiuneFormular");
     // context.Database.ExecuteSqlCommand("delete from Judet");
 }
예제 #17
0
        public VotingApp.Models.Job GetJob(string jobName)
        {
            var _context = new VotingContext();
            var _builder = new JobBuilder();
            var job      = _builder.GetModel(_context.Jobs.First(x => x.Name == jobName));

            return(job);
        }
예제 #18
0
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            VotingContext context = new VotingContext();

            context.Database.Initialize(false);
        }
예제 #19
0
        public List <VotingApp.Models.CandidateItem> GetCanidates()
        {
            var _context = new VotingContext();
            var _builder = new CandidateBuilder();

            var canindates = _context.Candidates.AsNoTracking().Include("Job");

            return(canindates.Select(_builder.GetModel).ToList());
        }
예제 #20
0
        private static string GenerateHtmlCodes(Voting voting)
        {
            var codes = new VotingContext().Votes.Where(v => v.VotingId == voting.ID).ToList();

            string s = "";

            foreach (var item in codes)
            {
                s += $"<div style='text-align:center;float:left;border-bottom:1px dotted black; border-right:1px dotted black; width:45%; padding: 15px;'><p>Głosowanie:   <b>{voting.Name}</b></p><p>Kod:   <b>{item.Code}</b></p></div>";
            }

            return(s);
        }
예제 #21
0
        public void GetSingleVoteElectionResults()
        {
            var _context = new VotingContext();
            var _manager = new VotingManager();

            var canidates = _manager.GetVoteResults();



            var electionResultsForSingleVoteItems = new Dictionary <SingleVoteItem, Dictionary <bool, int> >();

            var singleVoteItems = canidates.Where(x => x.SingleVoteId != null).ToList();

            foreach (var singleVoteItem in singleVoteItems)
            {
                if (singleVoteItem.SingleVoteItem != null &&
                    electionResultsForSingleVoteItems.ContainsKey(singleVoteItem.SingleVoteItem))
                {
                    if (singleVoteItem.VotedYes != null && singleVoteItem.VotedYes.Value)
                    {
                        electionResultsForSingleVoteItems[singleVoteItem.SingleVoteItem][true]++;
                    }
                    if (singleVoteItem.VotedNo != null && singleVoteItem.VotedNo.Value)
                    {
                        electionResultsForSingleVoteItems[singleVoteItem.SingleVoteItem][false]++;
                    }
                }
                else
                {
                    var firstEntry = new Dictionary <bool, int>();
                    firstEntry.Add(true, 0);
                    firstEntry.Add(false, 0);
                    if (singleVoteItem.VotedYes != null && singleVoteItem.VotedYes.Value)
                    {
                        firstEntry[true]++;
                    }
                    if (singleVoteItem.VotedNo != null && singleVoteItem.VotedNo.Value)
                    {
                        firstEntry[false]++;
                    }
                    if (singleVoteItem.SingleVoteItem != null)
                    {
                        electionResultsForSingleVoteItems.Add(singleVoteItem.SingleVoteItem, firstEntry);
                    }
                }
            }


            var test = electionResultsForSingleVoteItems;
        }
예제 #22
0
        private static string GenerateHtmlSummary(Voting voting)
        {
            var    candidates = new VotingContext().Candidates.Where(c => c.VotingId == voting.ID).OrderByDescending(c => c.VotesCount).ToList();
            int    i          = 1;
            string s          =
                $"<h1>Głosowanie: {voting.Name}</h1><br>" +
                $"<h3>Szczegóły:</h3>" +
                $"<h5>Liczba wygrywających: {voting.NumberOfWinners}<br>" +
                $"Liczba uprawnionych do głosowania: {voting.NumberOfVoters}<br>" +
                $"Liczba kandydatów: {candidates.Count }</h5>" +
                $"<br><hr><br>" +
                $"<h3>Kandydaci:</h3><br>" +
                $"<table style='width:100%;'><tr><th style='width:33%'>Imię</th><th style='width:33%'>Nazwisko</th><th style='width:33%'>Wynik</th><tr>";

            foreach (var item in candidates)
            {
                if (i % 2 == 0)
                {
                    s += $"<tr><td style='text-align:center; padding:10px;'>{item.FirstName}</td><td style='text-align:center; padding:10px;'>{item.Surname}</td><td style='padding:10px; text-align:center;'>";
                    if (i <= voting.NumberOfWinners)
                    {
                        s += $"<p style='color:green;'>Osoba wygrywająca<br>Liczba głosów {item.VotesCount}</p>";
                    }
                    else
                    {
                        s += $"<p>Osoba przegrywająca<br>Liczba głosów {item.VotesCount}</p>";
                    }
                    s += $"</td>";
                }
                else
                {
                    s += $"<tr style='background-color:gray'><td style='text-align:center; padding:10px;'>{item.FirstName}</td><td style='text-align:center; padding:10px;'>{item.Surname}</td><td style='padding:10px; text-align:center;'>";
                    if (i <= voting.NumberOfWinners)
                    {
                        s += $"<p style='color:#7FFF00;'>Osoba wygrywająca<br>Liczba głosów {item.VotesCount}</p>";
                    }
                    else
                    {
                        s += $"<p>Osoba przegrywająca<br>Liczba głosów {item.VotesCount}</p>";
                    }
                    s += $"</td>";
                }
                i++;
            }

            s += "</table>";

            return(s);
        }
예제 #23
0
        public void GetElectionResults()
        {
            var _context = new VotingContext();
            var _manager = new VotingManager();

            var canidates = _manager.GetVoteResults();



            var electionResultsForPresidents = new Dictionary <RankingVoteItem, Dictionary <int, int> >();

            var presidentialCandidates = canidates.Where(x => x.RankingVoteId != null).ToList();

            foreach (var presidentialCandidate in presidentialCandidates)
            {
                if (presidentialCandidate.RankingVoteId != null &&
                    electionResultsForPresidents.ContainsKey(presidentialCandidate.RankingVoteItem))
                {
                    if (electionResultsForPresidents[presidentialCandidate.RankingVoteItem]
                        .ContainsKey(presidentialCandidate.RankingVoteItem.Ranking))
                    {
                        var i = electionResultsForPresidents[presidentialCandidate.RankingVoteItem][
                            (int)presidentialCandidate.Ranking];
                        electionResultsForPresidents[presidentialCandidate.RankingVoteItem][
                            (int)presidentialCandidate.Ranking] = i++;
                        electionResultsForPresidents[presidentialCandidate.RankingVoteItem] = electionResultsForPresidents[presidentialCandidate.RankingVoteItem].OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                    }
                    else
                    {
                        electionResultsForPresidents[presidentialCandidate.RankingVoteItem].Add((int)presidentialCandidate.Ranking, 1);
                        electionResultsForPresidents[presidentialCandidate.RankingVoteItem] = electionResultsForPresidents[presidentialCandidate.RankingVoteItem].OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                    }
                }
                else
                {
                    if (presidentialCandidate.RankingVoteId != null)
                    {
                        var firstEntry = new Dictionary <int, int>();
                        firstEntry.Add((int)presidentialCandidate.Ranking, 1);
                        electionResultsForPresidents.Add(presidentialCandidate.RankingVoteItem, firstEntry);
                        electionResultsForPresidents[presidentialCandidate.RankingVoteItem] = electionResultsForPresidents[presidentialCandidate.RankingVoteItem].OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                    }
                }
            }


            var test = electionResultsForPresidents;
        }
예제 #24
0
        public FileResult Create(int?votingId)
        {
            if (votingId == null)
            {
                throw new ArgumentNullException();
            }

            var db     = new VotingContext();
            var voting = db.Votings.Find(votingId);

            PDFGenerator.Generate(voting);
            string ReportURL = Server.MapPath("~/documents/") + $"Karta głosowania {voting.Name}.pdf";

            byte[] FileBytes = System.IO.File.ReadAllBytes(ReportURL);
            return(File(FileBytes, "application/pdf"));
        }
예제 #25
0
        private static void SeedOptions(this VotingContext context)
        {
            if (context.Options.Any())
            {
                return;
            }
            context.Options.AddRange(
                new Option {
                Id = 1, Text = "Da",
            },
                new Option {
                Id = 2, Text = "Nu",
            },
                new Option {
                Id = 3, Text = "Nu stiu",
            },
                new Option {
                Id = 4, Text = "Dark Island",
            },
                new Option {
                Id = 5, Text = "London Pride",
            },
                new Option {
                Id = 6, Text = "Zaganu",
            },
                new Option {
                Id = 7, Text = "Transmisia manualã",
            },
                new Option {
                Id = 8, Text = "Transmisia automatã",
            },
                new Option {
                Id = 9, Text = "Altele (specificaţi)", IsFreeText = true
            },
                new Option {
                Id = 10, Text = "Metrou"
            },
                new Option {
                Id = 11, Text = "Tramvai"
            },
                new Option {
                Id = 12, Text = "Autobuz"
            }
                );

            context.SaveChanges();
        }
예제 #26
0
        public DbContextOptions <VotingContext> GetDbContextOptions()
        {
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            var options = new DbContextOptionsBuilder <VotingContext>()
                          .UseSqlite(connection)
                          .Options;

            using (var context = new VotingContext(options))
            {
                context.Database.EnsureCreated();
            }

            return(options);
        }
예제 #27
0
        private static void SeedFormSections(this VotingContext context)
        {
            if (context.FormSections.Any())
            {
                return;
            }

            context.FormSections.AddRange(
                new FormSection {
                Id = 1, Code = "B", Description = "Despre Bere"
            },
                new FormSection {
                Id = 2, Code = "C", Description = "Description masini"
            }
                );

            context.SaveChanges();
        }
예제 #28
0
        private static void SeedSectiune(this VotingContext context)
        {
            if (context.Sectiune.Any())
            {
                return;
            }

            context.Sectiune.AddRange(
                new Sectiune {
                IdSectiune = 1, CodSectiune = "B", Descriere = "Despre Bere"
            },
                new Sectiune {
                IdSectiune = 2, CodSectiune = "C", Descriere = "Descriere masini"
            }
                );

            context.SaveChanges();
        }
예제 #29
0
 protected void master_Page_PreLoad(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         using (var db = new VotingContext())
             // Set Anti-XSRF token
             ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
         ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
     }
     else
     {
         // Validate the Anti-XSRF token
         if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue ||
             (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
         {
             throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
         }
     }
 }
        private static void SeedNGOs(this VotingContext context)
        {
            if (context.Ngos.Any())
            {
                return;
            }

            context.Ngos.Add(new Ngo
            {
                Id = 1, Name = "Code4Romania", Organizer = true, ShortName = "C4R"
            });
            context.Ngos.Add(new Ngo
            {
                Id        = 2,
                Name      = "Guest NGO",
                Organizer = false,
                ShortName = "GUE"
            });
            context.SaveChanges();
        }
예제 #31
0
 public UserRepository(VotingContext votingContext)
 {
     _context = votingContext;
 }
예제 #32
0
 public QuestionRepository(VotingContext votingContext)
 {
     _context = votingContext;
 }