Exemplo n.º 1
0
        protected virtual async Task <List <PollingStation> > CalculateVotesByCounty(string csvContent,
                                                                                     ElectionsConfig electionsConfig)
        {
            var csvParser       = new CsvParser(new StringReader(csvContent));
            var pollingStations = new List <PollingStation>();
            var headers         = (await csvParser.ReadAsync()).ToList();

            do
            {
                var rowValues = await csvParser.ReadAsync();

                if (rowValues == null)
                {
                    break;
                }
                var pollingStation = new PollingStation();
                pollingStation.County = rowValues[1].StartsWith("SECTOR") ? "BUCUREȘTI" : rowValues[1];
                pollingStation.Name   = rowValues[4];
                foreach (var candidate in electionsConfig.Candidates)
                {
                    var votes = int.Parse(rowValues[headers.IndexOf(candidate.CsvId)]);
                    pollingStation.Candidates.Add(new CandidateConfig
                    {
                        Id    = candidate.CsvId,
                        Votes = votes
                    });
                    pollingStation.TotalVotes += votes;
                }
                pollingStations.Add(pollingStation);
            } while (true);

            return(pollingStations);
        }
        public async Task <IActionResult> Edit(int id, [Bind("PollingStationId,ElectionId,Name,AdditionalInfo,Address,WheelchairInfo,ParkingInfo,WashroomInfo,GeneralAccessInfo,Latitude,Longitute")] PollingStation pollingStation)
        {
            if (id != pollingStation.PollingStationId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(pollingStation);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PollingStationExists(pollingStation.PollingStationId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ElectionId"] = new SelectList(_context.Elections, "ElectionId", "Name", pollingStation.ElectionId);
            return(View(pollingStation));
        }
Exemplo n.º 3
0
        public async Task <ActionResult <PollingStation> > PostPollingStation(PollingStation pollingStation)
        {
            _context.PollingStations.Add(pollingStation);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetPollingStation", new { id = pollingStation.StationId }, pollingStation));
        }
Exemplo n.º 4
0
        public IActionResult EditPollingStation(int id, PollingStation station)
        {
            var address  = db.Addresses.Get(station.AddressId.Value);
            var district = db.Districts.Get(station.DistrictId.Value);

            if (id != station.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid && address != null && district != null)
            {
                try
                {
                    db.PollingStations.Update(station);
                    db.Save();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PollingStationExists(station.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("StartAdminPage", "Admin"));
            }
            return(View(station));
        }
Exemplo n.º 5
0
        public async Task <IActionResult> PutPollingStation(long id, PollingStation pollingStation)
        {
            if (id != pollingStation.StationId)
            {
                return(BadRequest());
            }

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

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

            return(NoContent());
        }
Exemplo n.º 6
0
        public Highcharts TransDaily(String Polling)
        {
            SMSServersEntities tp             = new SMSServersEntities();
            List <Series>      sr             = new List <Series>();
            PollingStation     pollingstation = db.PollingStations.Where(c => c.PollingStationName.Equals(Polling)).FirstOrDefault();

            foreach (var sp in Getnumbers(pollingstation.ID))
            {
                sr.Add(new Series {
                    Name = sp.Abrev, Data = new Data(new object[] { Math.Round(sp.Total, 2) })
                });
            }

            Highcharts chart1 = new Highcharts("chart1")
                                .InitChart(new Chart {
                DefaultSeriesType = ChartTypes.Column
            })
                                .SetTitle(new Title {
                Text = "Total votes per party"
            })
                                .SetSubtitle(new Subtitle {
                Text = String.Format("Summary for: {0}", pollingstation.PollingStationName)
            })
                                .SetXAxis(new XAxis {
                Categories = new[] { pollingstation.PollingStationName }
            })
                                .SetYAxis(new YAxis
            {
                Min   = 0,
                Title = new YAxisTitle {
                    Text = "Votes (%)"
                }
            })
                                .SetLegend(new Legend
            {
                Layout          = Layouts.Vertical,
                Align           = HorizontalAligns.Left,
                VerticalAlign   = VerticalAligns.Top,
                X               = 100,
                Y               = 70,
                Floating        = true,
                BackgroundColor = new BackColorOrGradient(ColorTranslator.FromHtml("#FFFFFF")),
                Shadow          = true
            })
                                .SetTooltip(new Tooltip {
                Formatter = @"function() { return ''+ this.series.name +': '+ this.y +' %'; }"
            })
                                .SetPlotOptions(new PlotOptions
            {
                Column = new PlotOptionsColumn
                {
                    PointPadding = 0.2,
                    BorderWidth  = 0
                }
            })
                                .SetSeries(sr.ToArray());

            return(chart1);
        }
Exemplo n.º 7
0
        private async void PollingStationClicked(object sender, RoutedEventArgs e)
        {
            var            buttonSender = sender as Button;
            PollingStation poll         = buttonSender.DataContext as PollingStation;
            MessageDialog  dialog       = new MessageDialog(poll.DisplayName + " Clicked");
            await dialog.ShowAsync();

            //this.Frame.Navigate(typeof(PollingStationPage), poll.ID);
        }
Exemplo n.º 8
0
        /// <summary>
        /// голосуем))
        /// </summary>
        /// <param name="elections"></param>
        private static void StartElections(ref PollingStation elections)
        {
            int rand = Randomize.rnd.Next(100, 1000);

            for (int i = 0; i < rand; i++)
            {
                elections.GetVote(elections.Candidates[Randomize.rnd.Next(0, elections.Candidates.Count)]);
            }
        }
Exemplo n.º 9
0
 public IActionResult CreatePollingStation(PollingStation station)
 {
     if (ModelState.IsValid && db.PollingStations.Get(station.Id) == null)
     {
         db.PollingStations.Create(station);
         db.Save();
         return(RedirectToAction("StartAdminPage", "Admin"));
     }
     return(View(station));
 }
        public async Task <IActionResult> Create([Bind("PollingStationId,ElectionId,Name,AdditionalInfo,Address,WheelchairInfo,ParkingInfo,WashroomInfo,GeneralAccessInfo,Latitude,Longitute")] PollingStation pollingStation)
        {
            if (ModelState.IsValid)
            {
                _context.Add(pollingStation);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ElectionId"] = new SelectList(_context.Elections, "ElectionId", "Name", pollingStation.ElectionId);
            return(View(pollingStation));
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            PollingStation elections = new PollingStation(Randomize.CreateNewCandidates());

            StartElections(ref elections);
            Console.WriteLine($"Winner: {elections.FinishElections()}");
            Console.WriteLine($"All Candidates:\n{elections}");
            FileStream fs = new FileStream("../../../result.json", FileMode.Create);
            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(PollingStation));

            //enum сериализуется как число(это логично с какойто стороны с другой нет)
            //другими словами никогда не юзайте enum дал чтобы просто вспомнили есть некторые неочевидные моменты с работой с ними
            json.WriteObject(fs, elections);
            //кстати json очень читаемый, поэтому достаточно открыть файлик с помощью блокнотика и все проверить))
            fs.Close();
            Console.Read();
        }
        public async Task <IActionResult> Create([Bind("IdPollingStation,Name,StationId,CityDistrictId,StreetId,MicroDistrictId,HouseId")] PollingStation pollingStation)
        {
            if (ModelState.IsValid)
            {
                Station stationFind = _context.Station.Where(s => s.IdStation == pollingStation.StationId).FirstOrDefault();
                pollingStation.Name = stationFind.Name;
                _context.Add(pollingStation);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["StationId"]       = new SelectList(_context.Station, "IdStation", "Name");
            ViewData["CityDistrictId"]  = new SelectList(_context.CityDistrict, "IdCityDistrict", "Name", pollingStation.CityDistrictId);
            ViewData["MicroDistrictId"] = new SelectList(_context.Microdistrict, "IdMicroDistrict", "Name", pollingStation.MicroDistrictId);
            List <Street> selectStreets = _context.Street.Where(s => s.CityId == pollingStation.CityDistrictId).ToList();

            ViewData["StreetId"] = new SelectList(_context.Street, "IdStreet", "Name", pollingStation.StreetId);
            ViewData["HouseId"]  = new SelectList(_context.House, "IdHouse", "Name", pollingStation.HouseId);

            return(View(pollingStation));
        }
        public async Task <IActionResult> Edit(int id, [Bind("IdPollingStation,Name,StationId,CityDistrictId,StreetId,MicroDistrictId,HouseId")] PollingStation pollingStation)
        {
            if (id != pollingStation.IdPollingStation)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    Station stationFind = _context.Station.Where(s => s.IdStation == pollingStation.StationId).FirstOrDefault();
                    pollingStation.Name = stationFind.Name;
                    _context.Update(pollingStation);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PollingStationExists(pollingStation.IdPollingStation))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["StationId"]       = new SelectList(_context.Station, "IdStation", "Name", pollingStation.StationId);
            ViewData["CityDistrictId"]  = new SelectList(_context.CityDistrict, "IdCityDistrict", "Name", pollingStation.CityDistrictId);
            ViewData["HouseId"]         = new SelectList(_context.House, "IdHouse", "Name", pollingStation.HouseId);
            ViewData["MicroDistrictId"] = new SelectList(_context.Microdistrict, "IdMicroDistrict", "Name", pollingStation.MicroDistrictId);
            ViewData["StreetId"]        = new SelectList(_context.Street, "IdStreet", "Name", pollingStation.StreetId);
            return(View(pollingStation));
        }
Exemplo n.º 14
0
        public async Task <IActionResult> CheackStationsAndDistricts()
        {
            int countSeccefful = 0;
            int countError     = 0;
            //List<long> masId = new List<long> {434, 1401, 1646, 2481, 2504, 2565, 2732, 2890, 3518, 4001, 4047, 4203, 4895, 4897, 4996, 5007, 5100, 5183, 5494, 5682, 6631, 7217, 7247, 7465, 7472, 7999, 8199, 8212, 8433, 8619, 9986, 10096, 10127, 10128, 10144, 10146, 10360, 10684, 10885, 10975, 11935, 11959, 11978, 12197, 12669, 12717, 13436, 13736, 14466, 14489, 15215, 17054, 17400};

            List <FriendDTOShot> friendDTOs = new List <FriendDTOShot>();

            List <Friend> friends = _context.Friend.Where(f => f.CityId == 1 && f.Unpinning == false).ToList();

            foreach (Friend friend in friends)
            {
                int idStation           = 0;
                int idElectoralDistrict = 0;

                PollingStation pollingStation = null;
                if (friend.HouseId != null)
                {
                    try
                    {
                        pollingStation = _context.PollingStation.FirstOrDefault(p => p.HouseId == friend.HouseId);
                    }
                    catch
                    {
                        countError++;
                        continue;
                    }
                }
                else
                {
                    countError++;
                    continue;
                }

                if (pollingStation != null)
                {
                    idStation = pollingStation.StationId ?? 0;
                    try
                    {
                        idElectoralDistrict = _context.District.FirstOrDefault(d => d.StationId == idStation).ElectoralDistrictId ?? 0;
                    }
                    catch
                    {
                        countError++;
                        continue;
                    }
                }
                else
                {
                    countError++;
                    continue;
                }
                //friendDTOs.Add(new FriendDTOShot { Name = friend.Name, FamilyName = friend.FamilyName, PatronymicName = friend.PatronymicName,
                //    FieldActivityName = friend.FieldActivity.Name, Organization = friend.Organization_.Name, Group = friend.GroupU.Name,
                //     City = friend.City.Name, Street = friend.Street.Name, House = friend.House.Name});

                if (idStation != 0 && idElectoralDistrict != 0)
                {
                    friend.StationId           = idStation;
                    friend.ElectoralDistrictId = idElectoralDistrict;
                    try
                    {
                        _context.Update(friend);
                        countSeccefful++;
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        countError++;
                        continue;
                        //friendDTOs.Add(new FriendDTOShot
                        //{
                        //    Name = friend.Name,
                        //    FamilyName = friend.FamilyName,
                        //    PatronymicName = friend.PatronymicName,
                        //    FieldActivityName = friend.FieldActivity.Name,
                        //    Organization = friend.Organization_.Name,
                        //    Group = friend.GroupU.Name,
                        //    City = friend.City.Name,
                        //    Street = friend.Street.Name,
                        //    House = friend.House.Name
                        //});
                    }
                }
            }
            try
            {
                _context.SaveChanges();
            }
            catch
            {
                return(Ok("Изменения не сохранены!"));
            }
            return(Ok("Выгружено записей: " + friends.Count + " Успешно обновленных записей: " + countSeccefful.ToString() + " Необновленных: " + countError.ToString()));
            //return Ok(friendDTOs);
        }
Exemplo n.º 15
0
        public async Task <ActionResult> Edit(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            IEnumerable <AspNetRole> cmx = await this.db.AspNetRoles.OrderBy(c => c.Name).ToListAsync();

            List <SelectListItem> itemRegions        = new List <SelectListItem>();
            List <SelectListItem> itemConstituencies = new List <SelectListItem>();
            List <SelectListItem> itemPolling        = new List <SelectListItem>();

            if (db.Agents.Find(id) != null)
            {
                Constituency cst = db.Agents.Find(id).Constituency;
                itemConstituencies.Add(new SelectListItem
                {
                    Text  = cst.ConstituencyName,
                    Value = cst.ID.ToString()
                });

                PollingStation plt = db.Agents.Find(id).PollingStation;
                itemPolling.Add(new SelectListItem
                {
                    Text  = plt.PollingStationName,
                    Value = plt.ID.ToString()
                });
            }

            foreach (Region rg in db.Regions.ToList())
            {
                itemRegions.Add(new SelectListItem {
                    Text = rg.RegionName, Value = rg.ID.ToString()
                });
            }

            List <SelectListItem> items = new List <SelectListItem>();

            AspNetUser aspNetUser = await this.db.AspNetUsers.FindAsync(id);

            Agent agent = await db.Agents.FindAsync(id);

            if (agent == null)
            {
                agent = new Agent {
                    IsEnable = false, UserID = "", ContituencyID = 0, DistrictID = 0, RegionID = 0
                };
            }

            EditAccountViewModel usr = new EditAccountViewModel
            {
                AspNetRoles      = aspNetUser.AspNetRoles,
                AspNetUserClaims = aspNetUser.AspNetUserClaims,
                AspNetUserLogins = aspNetUser.AspNetUserLogins,

                Email            = aspNetUser.Email,
                FullName         = aspNetUser.FullName,
                Id               = aspNetUser.Id,
                UserName         = aspNetUser.UserName,
                ContituencyID    = agent.ContituencyID,
                DistrictID       = agent.DistrictID,
                PollingStationID = agent.PollingStationID,
                RegionID         = agent.RegionID,
                IsEnable         = agent.IsEnable
            };

            if (usr == null)
            {
                return(this.HttpNotFound());
            }
            foreach (AspNetRole com in cmx)
            {
                if (this.UserManager.IsInRole(usr.Id, com.Name))
                {
                    items.Add(new SelectListItem {
                        Text = com.Name.ToUpper(), Value = com.Id, Selected = true
                    });
                }
                else
                {
                    items.Add(new SelectListItem {
                        Text = com.Name.ToUpper(), Value = com.Id, Selected = false
                    });
                }
            }
            this.ViewBag.AppRoles      = items;
            ViewBag.itemRegions        = itemRegions;
            ViewBag.itemConstituencies = itemConstituencies;
            ViewBag.itemPolling        = itemPolling;
            return(this.View(usr));
        }