Пример #1
0
        public IActionResult New(ElectionViewModel election)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            try
            {
                Election newElection = new Election
                {
                    Name = election.Name,
                    DistributableSeats = election.DistributableSeats,
                    Date          = election.Date,
                    PartyProfiles = new List <PartyProfile>()
                };

                electionCollection.CreateElection(newElection);
                return(RedirectToAction("Index", "Election"));
            }
            catch (CreatingElectionFailedException exception)
            {
                ModelState.AddModelError("", exception.Message);
                return(View());
            }
        }
Пример #2
0
        public void CanGetElectionById()
        {
            // Expected Result
            Election expected = fakeElectionRepository._fakeRepository.First();
            // Actual Result
            ElectionViewModel _vm    = _electionServices.GetElectionById(123456);
            Election          result = ElectionViewModel.ToDataModel(_vm);

            // Assert
            expected.Should().BeEquivalentTo(result);
        }
Пример #3
0
        public IActionResult CreateElection(ElectionViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            _electionPresentation.CreateElection(model);

            return(RedirectToAction("Index", "Elections"));
        }
Пример #4
0
        public static ElectionViewModel ToViewModel(this Election election)
        {
            var ret = new ElectionViewModel
            {
                Id          = election.Id.ToString(),
                Title       = election.Title,
                Description = election.Description
            };

            return(ret);
        }
Пример #5
0
        public void CanGetAllElections()
        {
            // Expected Result
            ICollection <Election>          elections = fakeElectionRepository._fakeRepository.Where(x => !x.Dormant).ToList();
            ICollection <ElectionViewModel> expected  = elections.Select(x => ElectionViewModel.ToViewModel(x)).ToList();
            // Actual Result
            ICollection <ElectionViewModel> result = _electionServices.GetAllElections();

            // Assert
            expected.Should().BeEquivalentTo(result);
        }
Пример #6
0
        public void CanDeleteElection()
        {
            //Delete Election
            _electionServices.DeleteElection(123456);
            // Actual Result
            ElectionViewModel _vm            = _electionServices.GetElectionById(123456);
            Election          resultElection = ElectionViewModel.ToDataModel(_vm);
            bool result = resultElection.Dormant;

            // Assert
            result.Should().Equals(true);
        }
Пример #7
0
        public async Task <IActionResult> UpdateElection(ElectionViewModel election)
        {
            try
            {
                await _electionServices.UpdateElection(election);

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }
        }
Пример #8
0
        public void CanAddElection()
        {
            //Create Additonal Election
            Election          expected     = fakeElectionRepository.GenerateAdditionalElection();
            ElectionViewModel _newElection = ElectionViewModel.ToViewModel(expected);

            //Add Election
            _electionServices.AddElection(_newElection);
            // Actual Result
            ElectionViewModel _vm    = _electionServices.GetElectionById(654321);
            Election          result = ElectionViewModel.ToDataModel(_vm);

            // Assert
            expected.Should().BeEquivalentTo(result);
        }
Пример #9
0
        public void CanUpdateElection()
        {
            //Create Updated Election
            Election          updatedElection  = fakeElectionRepository.GenerateUpdatedElection();
            ElectionViewModel _updatedElection = ElectionViewModel.ToViewModel(updatedElection);

            //Update Election
            _electionServices.UpdateElection(_updatedElection);
            // Expected Result
            Election expected = updatedElection;
            // Actual Result
            ElectionViewModel _vm    = _electionServices.GetElectionById(123456);
            Election          result = ElectionViewModel.ToDataModel(_vm);

            // Assert
            expected.Should().BeEquivalentTo(result);
        }
 public ActionResult AddEdit(int id = 0)
 {
     if (id == 0)
     {
         ViewBag.Action = "New Election";
         return(PartialView("AddEdit"));
     }
     else
     {
         var Election         = db.tblElections.Where(a => a.ElectionId == id).FirstOrDefault();
         ElectionViewModel cv = new ElectionViewModel();
         cv.ElectionId        = Election.ElectionId;
         cv.ElectionName      = Election.ElectionName;
         cv.ElectionStartDate = Election.ElectionStartDate;
         cv.ElectionEndDate   = Election.ElectionEndDate;
         ViewBag.Action       = "Edit Election";
         return(PartialView("AddEdit", cv));
     }
 }
        public ElectionViewModel ConvertElection_ToElectionViewModel(Election election)
        {
            try
            {
                ElectionViewModel e = new ElectionViewModel
                {
                    Id                 = election.Id,
                    Name               = election.Name,
                    StartDate          = election.StartDate,
                    DurationInDays     = election.DurationInDays,
                    HasNeutral         = election.HasNeutral,
                    NumberOfCandidates = election.Candidates.Where(c => c.isNeutralOpinion != true).Count(),
                    NumberOfVotes      = election.Votes.Count()
                };

                return(e);
            }
            catch (Exception E)
            {
                throw E;
            }
        }
        public JsonResult AddEdit(ElectionViewModel pvm)
        {
            if (pvm.ElectionId > 0)
            {
                tblElection tb = db.tblElections.Where(x => x.ElectionId == pvm.ElectionId).FirstOrDefault();
                tb.ElectionName      = pvm.ElectionName;
                tb.ElectionStartDate = pvm.ElectionStartDate;
                tb.ElectionEndDate   = pvm.ElectionEndDate;

                db.SaveChanges();
                return(Json(new { success = true, message = "Updated Successfully" }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                tblElection tb = new tblElection();
                tb.ElectionName      = pvm.ElectionName;
                tb.ElectionStartDate = pvm.ElectionStartDate;
                tb.ElectionEndDate   = pvm.ElectionEndDate;
                tb.NoOfCandidate     = 0;
                db.tblElections.Add(tb);
                db.SaveChanges();
                return(Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet));
            }
        }
Пример #13
0
        /// <summary>
        /// Return a list of ElectionListViewModel with all elections not marked dormant
        /// </summary>
        /// <returns></returns>
        public ICollection <ElectionViewModel> GetAllElections()
        {
            ICollection <Election> elections = _electionRepository.GetAllElections();

            return(elections.Select(x => ElectionViewModel.ToViewModel(x)).ToList());
        }
Пример #14
0
 public async Task UpdateElection(ElectionViewModel election)
 {
     await _electionRepository.UpdateElection(ElectionViewModel.ToDataModel(election));
 }
Пример #15
0
        /// <summary>
        /// Get Election by unique Election ID
        /// </summary>
        /// <param name="electionId">Unique Election ID</param>
        /// <returns type="ElectionViewModel">Election</returns>
        public ElectionViewModel GetElectionById(int electionId)
        {
            Election toReturn = _electionRepository.GetElection(electionId);

            return(ElectionViewModel.ToViewModel(toReturn));
        }
Пример #16
0
        public IActionResult EditElection(ElectionViewModel viewModel)
        {
            _electionPresentation.EditElection(viewModel);

            return(RedirectToAction("ElectionDetails", "Elections"));
        }
Пример #17
0
        public void EditElection(ElectionViewModel viewModel)
        {
            var election = _mapper.Map <Election>(viewModel);

            _electionRepository.Save(election);
        }
Пример #18
0
        public void CreateElection(ElectionViewModel model)
        {
            var election = _mapper.Map <Election>(model);

            _electionRepository.Save(election);
        }
Пример #19
0
        public IActionResult PreviousElectionsDataTable()
        {
            //This method is called by jQuery datatables to get paged data
            //First, we'll try to read the variables sent from the jQuery request, and then, based on these variables' values we'll query
            //the db


            try
            {
                //lets first get the variables of the request (of the form), and then build the linq query accordingly
                //above each variable I wrote the official doc of jQuery


                // draw
                // integer Type
                // Draw counter.This is used by DataTables to ensure that the Ajax returns from server - side processing requests
                // are drawn in sequence by DataTables(Ajax requests are asynchronous and thus can return out of sequence).
                // This is used as part of the draw return parameter(see below).

                var draw = HttpContext.Request.Form["draw"].FirstOrDefault();



                // start
                // integer type
                // Paging first record indicator.This is the start point in the current data set(0 index based -i.e. 0 is the first record).

                var start = HttpContext.Request.Form["start"].FirstOrDefault();



                // length
                // integer type
                // Number of records that the table can display in the current draw. It is expected that the number of records returned
                // will be equal to this number, unless the server has fewer records to return. Note that this can be -1 to indicate that
                // all records should be returned (although that negates any benefits of server-side processing!)

                var length = HttpContext.Request.Form["length"].FirstOrDefault();



                // search[value]
                // string Type
                // Global search value. To be applied to all columns which have searchable as true.

                var searchValue = HttpContext.Request.Form["search[value]"].FirstOrDefault();


                // order[i][column]
                // integer Type
                // Column to which ordering should be applied. This is an index reference to the columns array of information
                // that is also submitted to the server.

                var sortColumnName = HttpContext.Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();


                // order[i][dir]
                // integer Type
                // Ordering direction for this column.It will be asc or desc to indicate ascending ordering or descending ordering, respectively.


                var sortColumnDirection = HttpContext.Request.Form["order[0][dir]"].FirstOrDefault();


                //Page Size (10, 20, 50,100)
                int pageSize = length != null?Convert.ToInt32(length) : 0;

                //how many rows too skip?
                int skip = start != null?Convert.ToInt32(start) : 0;

                //totalRecords too inform user
                int totalRecords = 0;



                //declaring an expression that is special to Election objects
                Expression <Func <Election, bool> > expr;
                //now lets look for a value in FirstName/LastName/StateName if user asked to
                if (!string.IsNullOrEmpty(searchValue))
                {
                    expr = e => e.StartDate.AddDays(e.DurationInDays) < DateTime.Now &&
                           e.Name.Contains(searchValue);
                }
                else
                {
                    //so user didn't ask for filtering, he only asked for paging
                    expr = e => e.StartDate.AddDays(e.DurationInDays) < DateTime.Now;
                }
                //lets get the list of elections paged
                PagedResult <Election> pagedResult1 = _electionBusiness.GetAllFilteredPaged(expr, sortColumnName, sortColumnDirection, skip, pageSize);

                //Now the pagedResult we've got has two properties: pagedResult.Items and pagedResult.TotalCount
                //the first one is a list of Elections with their Candidates icnluded. When I try to serialise it to json
                //I got the following error:
                //Self referencing loop detected for property 'Election' with type 'WebApplication1.Models.Election'. Path 'data[1].Candidates[0]'.
                //so what we need is to create another PagedResult<Election> object 'pagedResult2' and fill it with data that we have in pagedResult1
                //but instead of filling the list o candidates for each Election we'll only fill the count of the candidates
                //which means we'll use a list of ElectionViewModels instead of Elections


                List <ElectionViewModel> electionViewModels = new List <ElectionViewModel>();
                foreach (var election in pagedResult1.Items)
                {
                    ElectionViewModel e = new ElectionViewModel();
                    e.Id                 = election.Id;
                    e.Name               = election.Name;
                    e.StartDate          = election.StartDate;
                    e.DurationInDays     = election.DurationInDays;
                    e.HasNeutral         = election.HasNeutral;
                    e.NumberOfCandidates = election.Candidates.Count;
                    e.NumberOfVotes      = election.Votes.Count;
                    electionViewModels.Add(e);
                }
                PagedResult <ElectionViewModel> pagedResult2 = new PagedResult <ElectionViewModel>(electionViewModels, pagedResult1.TotalCount);

                //lets assign totalRecords the correct value
                totalRecords = pagedResult2.TotalCount;

                //now lets return json data so that it is understandable by jQuery
                JsonSerializerSettings settings = new JsonSerializerSettings {
                    DateFormatString = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern
                };
                var json = JsonConvert.SerializeObject(new
                {
                    draw            = draw,
                    recordsFiltered = totalRecords,
                    recordsTotal    = totalRecords,
                    data            = pagedResult2.Items
                }, settings);
                return(Ok(json));
            }
            catch (Exception E)
            {
                HttpContext.Response.StatusCode = 500;
                return(Json(new { Message = E.Message }));
                //In above code I created an internal server error so that the response returned is an ERROR, and jQuery ajax will understand that.
            }
        }