Exemplo n.º 1
0
        public IActionResult AddCandidate(Candidate candidate)
        {
            var manager = new CandidateRepository(_connectionString);

            manager.AddCandidate(candidate);
            return(Redirect("/home/pending"));
        }
        public void Simple_Status_Candidate()
        {
            IRaceRepository           raceRepository           = Substitute.For <IRaceRepository>();
            IPoliticalPartyRepository politicalPartyRepository = Substitute.For <IPoliticalPartyRepository>();
            var f              = new Fixture();
            var race           = f.Create <Race>();
            var politicalParty = f.Create <PoliticalParty>();
            var candidate      = Create();

            raceRepository.GetById(Arg.Any <Guid>()).Returns(race);
            politicalPartyRepository.GetById(Arg.Any <Guid>()).Returns(politicalParty);
            var candidateRepository = new CandidateRepository(ContextConnection(), politicalPartyRepository, raceRepository);

            candidateRepository.Save(candidate);
            candidateRepository.SetInactive(candidate);
            var inactive = candidateRepository.GetById(candidate.Id);

            Assert.That(inactive.Status == EntityStatus.Inactive);

            candidateRepository.SetActive(candidate);
            var active = candidateRepository.GetById(candidate.Id);

            Assert.That(active.Status == EntityStatus.Active);

            candidateRepository.SetAsDeleted(candidate);
            var deleted = candidateRepository.GetById(candidate.Id);

            Assert.That(deleted.Status == EntityStatus.Deleted);
        }
Exemplo n.º 3
0
 public ActionResult AddNameSubmit(CandidateModel cm)
 {
     try
     {
         cm.BidCount  = 0;
         cm.Hidden    = 1;
         cm.Priority  = 0;
         cm.BidAdjust = 0;
         CandidateRepository cr = new CandidateRepository();
         int duplicateId        = cr.CheckDuplicate(cm);
         if (duplicateId == -2)
         {
             return(Json(new { success = false, message = "提名失败,被提名对象已经存在。如果在投票页面上没有见到,可能处于审核状态。" }));
         }
         if (duplicateId != -1)
         {
             cm.Type = cm.Type + 10 * duplicateId;
         }
         cr.Insert(cm);
         cr.Save();
         return(Json(new { success = true }));
     }
     catch (Exception e)
     {
         return(Json(new { success = false, message = e.Message }));
     }
 }
Exemplo n.º 4
0
        public void Given_CandidateRepo_When_GetFormByEmailIsCalled_Then_CorrectCandidateIsReturned()
        {
            RunOnDatabase(async context =>
            {
                //Arrange
                var candidateRepo = new CandidateRepository(context, _loggerFactory);
                var candidate     = new Candidate
                {
                    Approved  = false,
                    CNP       = "12341423523523",
                    Completed = false,
                    Email     = "*****@*****.**",
                    FirstName = "Candi",
                    LastName  = "date",
                    School    = "yes",
                    Subject   = "matematica"
                };

                //Act
                await candidateRepo.AddAsync(candidate);
                var res = await candidateRepo.GetByFormEmail("*****@*****.**");

                //Assert
                res.Email.Should().Be("*****@*****.**");
            });
        }
Exemplo n.º 5
0
        public UnitOfWork(AddressRepository addressRepository, CandidateRepository candidateRepository, EmployerRepository employerRepository,
                          GorvernmentRepository gorvernmentRepository, JobRepository jobRepository, MicroCredentialRepository microCredentialRepository, MoocProviderRepository moocProviderRepository,
                          RecruitmentAgencyRepository recruitmentAgencyRepository, AccreditationBodyRepository accreditationBodyRepository, CandidateMicroCredentialCourseRepository candidateMicroCredentialCourseRepository,
                          EndorsementBodyRepository endorsementBodyRepository, CandidateJobApplicationRepository candidateJobApplicationRepository, CandidatetMicroCredentialBadgesRepository candidatetMicroCredentialBadgesRepository,
                          StratisAccountRepository stratisAccountRepository)
        {
            _addressRepository = addressRepository;

            _candidateRepository = candidateRepository;

            _employerRepository = employerRepository;

            _gorvernmentRepository = gorvernmentRepository;

            _jobRepository = jobRepository;

            _microCredentialRepository = microCredentialRepository;

            _moocProviderRepository = moocProviderRepository;

            _recruitmentAgencyRepository = recruitmentAgencyRepository;

            _accreditationBodyRepository = accreditationBodyRepository;

            _candidateMicroCredentialCourseRepository = candidateMicroCredentialCourseRepository;

            _endorsementBodyRepository = endorsementBodyRepository;

            _candidateJobApplicationRepository = candidateJobApplicationRepository;

            _candidatetMicroCredentialBadgesRepository = candidatetMicroCredentialBadgesRepository;

            _stratisAccountRepository = stratisAccountRepository;
        }
Exemplo n.º 6
0
        public void AddCandidate(Candidate candidate)
        {
            var repo = new CandidateRepository(_connectionString);

            candidate.Status = Status.Pending;
            repo.AddCandidate(candidate);
        }
Exemplo n.º 7
0
 public HttpResponseMessage Post([Bind(Exclude = "Id")][FromBody] Candidate entity)
 {
     try
     {
         if (ModelState.IsValid)
         {
             CandidateRepository rep      = new CandidateRepository();
             Validate            repValid = rep.ValidateInsert(entity);
             if (repValid.IsValid)
             {
                 int Id = rep.Insert(entity);
                 return(Request.CreateResponse(HttpStatusCode.OK, new { Id = Id, Message = "Operação efetuada com sucesso!" }));
             }
             else
             {
                 return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, repValid.Message));
             }
         }
         else
         {
             return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
         }
     }
     catch (Exception ex)
     {
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
     }
 }
Exemplo n.º 8
0
 public HttpResponseMessage Put([FromBody] Candidate entity)
 {
     try
     {
         if (ModelState.IsValid)
         {
             CandidateRepository rep      = new CandidateRepository();
             Validate            repValid = rep.ValidateUpdate(entity);
             if (repValid.IsValid)
             {
                 rep.Update(entity);
                 return(Request.CreateResponse(HttpStatusCode.OK, "Operação efetuada com sucesso!"));
             }
             else
             {
                 return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, repValid.Message));
             }
         }
         else
         {
             return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
         }
     }
     catch (Exception ex)
     {
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
     }
 }
Exemplo n.º 9
0
 public HttpResponseMessage Get([Bind(Include = "Id")] long Id)
 {
     try
     {
         if (ModelState.IsValid)
         {
             CandidateRepository     rep  = new CandidateRepository();
             IEnumerable <Candidate> list = Mapper.ToList <Candidate>(rep.GetById(Id));
             if (list != null && list.Count() > 0)
             {
                 return(Request.CreateResponse(HttpStatusCode.OK, list.FirstOrDefault()));
             }
             else
             {
                 return(Request.CreateResponse(HttpStatusCode.NoContent));
             }
         }
         else
         {
             return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
         }
     }
     catch (Exception ex)
     {
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
     }
 }
        public List <Candidate> Refuse(CandidateViewModel vm)
        {
            var repo = new CandidateRepository(_connectionString);

            repo.RefuseCandidate(vm.CandidateId);
            return(repo.GetAll());
        }
Exemplo n.º 11
0
 public ActionResult ForgiveBidsByCandidate(int candidateId = 0)
 {
     try
     {
         CandidateRepository cr = new CandidateRepository();
         bidRepository       br = new bidRepository();
         if (candidateId == 0)
         {
             IEnumerable <int> candidateList = cr.GetAllCandidates();
             foreach (int cId in candidateList)
             {
                 br.UpdateVoteStatusByCandidateId(cId, 2);
             }
         }
         else
         {
             br.UpdateVoteStatusByCandidateId(candidateId, -1);
         }
         return(Json(new { success = true }));
     }
     catch (Exception e)
     {
         return(Json(new { success = false, message = e.Message }));
     }
 }
Exemplo n.º 12
0
        public ActionResult EditApply(int id)
        {
            CandidateRepository cr = new CandidateRepository();
            CandidateModel      cm = cr.GetInfoById(id);

            return(View(cm));
        }
Exemplo n.º 13
0
        public ActionResult Candidate(Applicant applicant)
        {
            var repo = new CandidateRepository(Properties.Settings.Default.ConStr);

            repo.AddCandidate(applicant);
            return(Redirect("/home/index"));
        }
Exemplo n.º 14
0
        public IActionResult Pending()
        {
            var db = new CandidateRepository(_connectionString);

            ViewBag.PendingCount = db.GetPendingCount();
            return(View(db.GetPending()));
        }
Exemplo n.º 15
0
        public ActionResult AddCandidate(Candidate candidate)
        {
            var manager = new CandidateRepository(Properties.Settings.Default.ConStr);

            manager.AddCandidate(candidate);
            return(Redirect("/home/pending"));
        }
Exemplo n.º 16
0
        //
        // GET: api/Candidate/

        public Candidate[] Get(string databaseId)
        {
            CandidateRepository candidateRepository;

            candidateRepository = new CandidateRepository(databaseId);
            return(candidateRepository.GetAll().Values.ToArray());
        }
Exemplo n.º 17
0
        // POST api/Candidate
        public HttpResponseMessage Post(string databaseId, NewCandidate value)
        {
            try
            {
                CandidateRepository candidateRepository;
                candidateRepository = new CandidateRepository(databaseId);
                string message = string.Empty;

                if (!candidateRepository.IsValidCandidate(value, out message))
                {
                    var dataErrorResponse = Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, message);

                    return(dataErrorResponse);
                }

                Candidate result = candidateRepository.CreateCandidate(value);

                var response = Request.CreateResponse <Candidate>(System.Net.HttpStatusCode.Created, result);
                return(response);
            }
            catch (Exception ex)
            {
                var response = Request.CreateErrorResponse(System.Net.HttpStatusCode.InternalServerError, ex);
                return(response);
            }
        }
Exemplo n.º 18
0
        public async Task Find_Canditates_By_FirstName()
        {
            //Arrange
            using (var context = new AppDbContext(_options))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
                SetupSkills(context);

                var repo      = new CandidateRepository(context);
                var candidate = new Candidate
                {
                    FirstName = "Tom",
                    LastName  = "Liu",
                };

                await repo.SaveCandidateAsync(candidate, new List <int> {
                    1, 3, 4
                });

                //Act
                var actual = await repo.GetCandidatesByNameAsync("tom");

                //Assert
                Assert.Single(actual);
                context.Database.EnsureDeleted();
            }
        }
Exemplo n.º 19
0
        public async Task Save_Canditate_Success()
        {
            //Arrange
            using (var context = new AppDbContext(_options))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
                SetupSkills(context);

                var repo      = new CandidateRepository(context);
                var candidate = new Candidate
                {
                    FirstName = "Tom",
                    LastName  = "Liu",
                };
                var skillIds = new List <int> {
                    1, 3
                };
                //Act
                await repo.SaveCandidateAsync(candidate, skillIds);

                var actual = repo.CandidateCount();

                //Assert
                Assert.Equal(1, actual.Result);
                context.Database.EnsureDeleted();
            }
        }
Exemplo n.º 20
0
        public async Task AddCandidate_ShouldAddOneCandidate()
        {
            var options = new DbContextOptionsBuilder <GeekHunterContext>()
                          .UseInMemoryDatabase("AddCandidate_ShouldAddOneCandidate")
                          .Options;

            var context = new GeekHunterContext(options);

            await Seed(context);

            CandidateRepository candidateRepository = new CandidateRepository(context);

            await candidateRepository.AddCandidate(new AddCandidateDto
            {
                FirstName = "TestFirstName",
                LastName  = "TestLastName",
                Skills    = new List <string> {
                    "SQL", "Entity Framework"
                }
            });

            var candidates = (await candidateRepository.GetCandidates()).ToList();

            Assert.Equal(4, candidates.Count);
            var addedCustomer = candidates[3];

            Assert.Equal("TestFirstName", addedCustomer.FirstName);
            Assert.Equal("TestLastName", addedCustomer.LastName);
            Assert.Equal(2, addedCustomer.Skills.Count);
        }
Exemplo n.º 21
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            try
            {
                new AppDbContext().CreateDB();
                var candidateRepository = new CandidateRepository();
                if (candidateRepository.IsAnyCandidate())
                {
                    return;
                }

                var candidateJsonData = new CandidateJsonData().GetAll();
                if (candidateJsonData != null)
                {
                    candidateRepository.AddAll(candidateJsonData);
                }
                else
                {
                    Current.Shutdown();
                }
            }
            catch (Exception exception)
            {
                ErrorMessage.ShowError($"Can not connect to database.\n", exception);
                Current.Shutdown();
            }
        }
    protected void OnGridCandidateDocument_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Lucene.Net.Documents.Document doc = e.Row.DataItem as Lucene.Net.Documents.Document;
            if(doc != null)
            {
                HyperLink lnkCandidateID = (HyperLink)e.Row.FindControl("lnkCandidateID");
                if(lnkCandidateID != null)
                {
                    Candidate candidate = new CandidateRepository().FindOne(new Candidate(Convert.ToInt32(doc.Get("candidateID"))));
                    if (candidate != null)
                    {
                        lnkCandidateID.Text = string.Format("{0} {1}", candidate.FirstName, candidate.LastName);
                        lnkCandidateID.NavigateUrl = string.Format("~/CandidateProfile.aspx?CandidateID={0}&mode=edit", candidate.CandidateId);
                    }
                }
                Literal lblCandidateContent = (Literal)e.Row.FindControl("lblCandidateContent");
                if (lblCandidateContent != null)
                {
                    lblCandidateContent.Text = Common.FirstWords(doc.Get("content"), 50);
                }

                HyperLink lnkCandidateCV = (HyperLink)e.Row.FindControl("lnkCandidateCV");
                if (lnkCandidateCV != null)
                {
                    lnkCandidateCV.Text = doc.Get("path");
                    lnkCandidateCV.NavigateUrl = doc.Get("path");
                }
            }
        }
    }
        public void GivenExistingCandidates_WhenGetAll_ThenReturnAllCandidates()
        {
            using (var context = new SwintakeContext(_options))
            {
                var guidId  = Guid.NewGuid();
                var janneke = new CandidateBuilder()
                              .WithId(guidId)
                              .WithFirstName("Janneke")
                              .WithLastName("Janssens")
                              .WithEmail("*****@*****.**")
                              .WithPhoneNumber("0470000000")
                              .WithGitHubUsername("janneke")
                              .WithLinkedIn("janneke")
                              .Build();

                IRepository <Candidate> candidateRepository = new CandidateRepository(context);

                //when
                candidateRepository.Save(janneke);
                IList <Candidate> searchCandidate = candidateRepository.GetAll();

                //then
                Assert.Equal(1, searchCandidate.Count);
            }
        }
Exemplo n.º 24
0
        public void GetBestCandidateForJobWithXYearsExperience_WithMultipleCandidatesMatchingCriteria_ReturnsCandidateWithMostExperience()
        {
            // Arrange
            var candidate = new Candidate {
                Name = "Nick", WorkHistory = new List <CandidateJob> {
                    new CandidateJob {
                        JobTitle = "Software Developer", StartDate = DateTime.UtcNow, EndDate = DateTime.UtcNow.AddYears(1).AddDays(1)
                    }
                }
            };
            var candidate2 = new Candidate {
                Name = "Nick 2", WorkHistory = new List <CandidateJob> {
                    new CandidateJob {
                        JobTitle = "Software Developer", StartDate = DateTime.UtcNow, EndDate = DateTime.UtcNow.AddYears(1).AddDays(2)
                    }
                }
            };
            var candidateRepo = new CandidateRepository(new List <Candidate> {
                candidate, candidate2
            });

            // Act
            var result = candidateRepo.GetBestCandidateForJobWithXYearsExperience("Software Developer", 1);

            // Assert
            Assert.AreEqual(candidate2.Name, result.Name);
        }
Exemplo n.º 25
0
 protected void OnMyAjaxManager_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
 {
     CandidateAjaxManager.AjaxSettings.AddAjaxSetting(CandidateAjaxManager, RadCandidateGrid);
     if (e.Argument.IndexOf("DeletedSelectedCandidate") > -1)
     {
         if (RadCandidateGrid.SelectedItems.Count == 1)
         {
             CandidateRepository candRepo = new CandidateRepository();
             candRepo.Delete(new Candidate(GetSelectedCandidateID()));
             RadCandidateGrid.Rebind();
         }
     }
     else if (e.Argument.IndexOf("OpenSelectedCandidate") > -1)
     {
         if (RadCandidateGrid.SelectedItems.Count == 1)
         {
             int candidateID = GetSelectedCandidateID();
             if (candidateID > -1)
                 Response.Redirect("~/CandidateProfile.aspx?CandidateID=" + candidateID + "&mode=edit&backurl=visible", true);
         }
     }
     else if (e.Argument.IndexOf("ViewCandidateActions") > -1)
     {
         if (RadCandidateGrid.SelectedItems.Count == 1)
         {
             int candidateID = GetSelectedCandidateID();
             if (candidateID > -1)
                 Response.Redirect(string.Format("~/CandidateProfile.aspx?CandidateID={0}&tab=action&mode=edit&backurl=visible", candidateID, true));
         }
     }
 }
Exemplo n.º 26
0
 public GeekHunterUnitOfWork(DbContext context)
 {
     this._Context                  = context;
     this._SkillRepository          = new SkillRepository(context);
     this._CandidateRepository      = new CandidateRepository(context);
     this._SkillCandidateRepository = new CandidateSkillRepository(context);
 }
        public List <Candidate> Add(Candidate c)
        {
            var repo = new CandidateRepository(_connectionString);

            repo.Add(c);
            return(repo.GetAll());
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var manager = new CandidateRepository(Properties.Settings.Default.ConStr);

            filterContext.Controller.ViewBag.CandidateCounts = manager.GetCounts();
            base.OnActionExecuting(filterContext);
        }
Exemplo n.º 29
0
        public ActionResult GetAllNewCandidate()
        {
            CandidateRepository   cr         = new CandidateRepository();
            List <CandidateModel> NewCanList = cr.GetAllHidden();

            return(Json(NewCanList));
        }
Exemplo n.º 30
0
        public static void Seed(EvotingContext context)
        {
            var voterRepository     = new VoterRepository(context);
            var candidateRepository = new CandidateRepository(context);

            for (var i = 1; i <= 5; i++)
            {
                // Get a voter
                var voter = voterRepository.GetVoterById(i);

                // Get the constituency the voter is registered to
                var constituency = voter.Constituency;

                // Reoccur for three votes
                for (var t = 0; t < Preferential.MAX_VOTES; t++)
                {
                    // Get a random candidate in the list of candidates
                    var candidates = candidateRepository.GetCandidatesByConstituency(constituency);
                    var candidate  = candidates.ElementAt(Faker.RandomNumber.Next(1, candidates.Count()));

                    // Create a preferential vote
                    var vote = new Votes
                    {
                        Candidate = candidate,
                        Voter     = voter,
                        Priority  = (Priority)t
                    };
                    context.Votes.Add(vote);
                }
            }
            context.SaveChanges();
        }
Exemplo n.º 31
0
        public ActionResult GetCurrentVote()
        {
            CandidateRepository   cr         = new CandidateRepository();
            List <CandidateModel> NewCanList = cr.GetAllShown();

            return(Json(NewCanList));
        }
Exemplo n.º 32
0
 public HttpResponseMessage Delete(long Id)
 {
     try
     {
         if (Id > 0)
         {
             CandidateRepository rep      = new CandidateRepository();
             Validate            repValid = rep.ValidateDelete(Id);
             if (repValid.IsValid)
             {
                 rep.Delete(Id);
                 return(Request.CreateResponse(HttpStatusCode.OK, "Operação efetuada com sucesso!"));
             }
             else
             {
                 return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, repValid.Message));
             }
         }
         else
         {
             return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Id inválido!"));
         }
     }
     catch (Exception ex)
     {
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
     }
 }
Exemplo n.º 33
0
        public JsonResult DeleteCandidate(int candidateId)
        {
            using (var candidateRepository = new CandidateRepository())
            {
                var result = candidateRepository.DeleteCandidate(candidateId, ElectionConductor.ElectionId((int)Session["UserId"]));

                return new JsonResult
                {
                    Data = new { isOk = result }
                };
            }
        }
Exemplo n.º 34
0
 protected void OnDropdownCandidate_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
 {
     string name = e.Text;
     if (!string.IsNullOrEmpty(name))
     {
         if(name.Length >= 3)
         {
             List<Candidate> list = new CandidateRepository().SearchCandidatesOnName(name);
             ddlCandidate.DataTextField = "FullName";
             ddlCandidate.DataValueField = "CandidateId";
             ddlCandidate.DataSource = list;
             ddlCandidate.DataBind();
         }
     }
 }
Exemplo n.º 35
0
    protected void OnBtnOkClicked(object sender, EventArgs e)
    {
        if (gridCandidate.SelectedValue != null)
        {
            int candidateID = (int)gridCandidate.SelectedValue;
            Candidate selectedCandidate = new CandidateRepository().FindOne(new Candidate(candidateID));
            string argument = selectedCandidate.CandidateId.ToString() + "/"
                + selectedCandidate.LastName + " " + selectedCandidate.FirstName;
            string script = "<script type=\"text/javascript\">";
            script += " OnBtnOkClientClicked(\"" + argument + "\");";
            script += " </script>";

            if (!ClientScript.IsClientScriptBlockRegistered("redirectUser"))
                ClientScript.RegisterStartupScript(this.GetType(), "redirectUser", script);
        }
    }
Exemplo n.º 36
0
        public ActionResult CreateCandidateWithPhoto(string name, HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                var imgByte = new Byte[file.ContentLength];
                file.InputStream.Read(imgByte, 0, file.ContentLength);

                using (var candidateRepository = new CandidateRepository())
                {
                    candidateRepository.CreateCandidateWithPhoto(new Candidate
                    {
                        ElectionId = ElectionConductor.ElectionId((int)Session["UserId"]),
                        Name = name
                    },
                    imgByte);
                }
            }
            return RedirectToAction("Index");
        }
Exemplo n.º 37
0
        public JsonResult ChangeElectionStatus(int newStatus)
        {
            using (var electionRepository = new ElectionRepository())
            using (var candidateRepository = new CandidateRepository())
            {
                var election = electionRepository.GetElectionByElectionId(ElectionConductor.ElectionId((int)Session["UserId"]));

                if ((newStatus == 1) && election.NoVote)
                {
                    var path = Server.MapPath("~/Content/Banners/NoVote.jpg");
                    var noVoteImage = System.IO.File.ReadAllBytes(path);
                    candidateRepository.CreateCandidateWithPhoto(new Candidate { ElectionId = ElectionConductor.ElectionId((int)Session["UserId"]), Name = "No Vote" }, noVoteImage);
                }

                var result = electionRepository.ChangeElectionStatus(ElectionConductor.ElectionId((int)Session["UserId"]), newStatus);

                return new JsonResult
                {
                    Data = new { isOk = result == 1 }
                };
            }
        }
Exemplo n.º 38
0
    private void BindGridData(GridSortCommandEventArgs sortEventArgs)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["CandidateId"]))
        {
            int id = int.Parse(Request.QueryString["CandidateId"]);
            Candidate candidate = NeosDAO.GetCandidateById(id);
            List<Candidate> candidateList = new List<Candidate>();
            candidateList.Add(candidate);
            RadCandidateGrid.DataSource = candidateList;
        }
        else if (!string.IsNullOrEmpty(Request.QueryString["lastname"])
                || !string.IsNullOrEmpty(Request.QueryString["type"]))
        {
            //int pageSize = 20;
            int pageNumber = RadCandidateGrid.CurrentPageIndex + 1;
            string sortExpress = string.Empty;
            string sortExpressInvert = string.Empty;
            foreach (GridSortExpression item in RadCandidateGrid.MasterTableView.SortExpressions)
            {
                GridSortOrder newSortOrder = item.SortOrder;
                if (sortEventArgs != null && item.FieldName == sortEventArgs.SortExpression)
                {
                    newSortOrder = sortEventArgs.NewSortOrder;
                }

                if (!string.IsNullOrEmpty(sortExpress) && newSortOrder != GridSortOrder.None)
                {
                    sortExpress += ", ";
                    sortExpressInvert += ", ";
                }
                if (newSortOrder == GridSortOrder.Ascending)
                {
                    sortExpress += item.FieldName + " ASC";
                    sortExpressInvert += item.FieldName + " DESC";
                }
                else if (newSortOrder == GridSortOrder.Descending)
                {
                    sortExpress += item.FieldName + " DESC";
                    sortExpressInvert += item.FieldName + " ASC";
                }
            }

            if (sortEventArgs != null && !sortExpress.Contains(sortEventArgs.SortExpression))
            {
                if (!string.IsNullOrEmpty(sortExpress) && sortEventArgs.NewSortOrder != GridSortOrder.None)
                {
                    sortExpress += ", ";
                    sortExpressInvert += ", ";
                }
                if (sortEventArgs.NewSortOrder == GridSortOrder.Ascending)
                {
                    sortExpress += sortEventArgs.SortExpression + " ASC";
                    sortExpressInvert += sortEventArgs.SortExpression + " DESC";
                }
                else if (sortEventArgs.NewSortOrder == GridSortOrder.Descending)
                {
                    sortExpress += sortEventArgs.SortExpression + " DESC";
                    sortExpressInvert += sortEventArgs.SortExpression + " ASC";
                }
            }

            if (!string.IsNullOrEmpty(sortExpress))
            {
                if (sortExpress.Contains("LastName"))
                {
                    sortExpress = sortExpress.Replace("LastName", "Nom");
                    sortExpressInvert = sortExpressInvert.Replace("LastName", "Nom");
                }
                if (sortExpress.Contains("FirstName"))
                {
                    sortExpress = sortExpress.Replace("FirstName", "Prenom");
                    sortExpressInvert = sortExpressInvert.Replace("FirstName", "Prenom");
                }
                if (sortExpress.Contains("Inactive"))
                {
                    sortExpress = sortExpress.Replace("Inactive", "inactif");
                    sortExpressInvert = sortExpressInvert.Replace("Inactive", "inactif");
                }
                if (sortExpress.Contains("LastModifDate"))
                {
                    sortExpress = sortExpress.Replace("LastModifDate", "DateModif");
                    sortExpressInvert = sortExpressInvert.Replace("LastModifDate", "DateModif");
                }
            }
            else
            {
                sortExpress = "Nom ASC";
                sortExpressInvert = "Nom DESC";
            }
            if (!string.IsNullOrEmpty(Request.QueryString["lastname"]))
            {
                string name = Request.QueryString["lastname"];
                SessionManager.LastNameSearchCriteria = name;

                RadCandidateGrid.VirtualItemCount = new CandidateRepository().CountSearchCandidatesOnName(name);
                IList<Candidate> candidateList = new CandidateRepository().SearchCandidatesOnName(name, pageSize, pageNumber, sortExpress, sortExpressInvert);

                candidateList = FillContactInfo(candidateList);
                RadCandidateGrid.DataSource = candidateList;
            }
            else if (!string.IsNullOrEmpty(Request.QueryString["type"])
                    && Request.QueryString["type"] == "AdvancedSearch"
                    && SessionManager.CandidateSearchCriteria != null)
            {
                RadCandidateGrid.VirtualItemCount = NeosDAO.CountAdvancedSearchCandidates(SessionManager.CandidateSearchCriteria);
                IList<Candidate> candidateList = NeosDAO.AdvancedSearchCandidatesByPage(
                    SessionManager.CandidateSearchCriteria, pageSize, pageNumber, sortExpress, sortExpressInvert);
                candidateList = FillContactInfo(candidateList);
                RadCandidateGrid.DataSource = candidateList;
            }
            //RadCandidateGrid.SortCommand += new GridSortCommandEventHandler(OnRadCandidateGridSortCommand);
        }
        else
        {
            IList<Candidate> candidateList = new List<Candidate>();
            RadCandidateGrid.DataSource = candidateList;
        }
    }
Exemplo n.º 39
0
        public static Candidate GetCandidateById(int candidateId)
        {
            CandidateRepository repository = new CandidateRepository();
            Candidate item = new Candidate();
            item.CandidateId = candidateId;
            item = repository.FindOne(item);
            item.ContactInfo = string.Empty;
            if (!string.IsNullOrEmpty(item.Address))
            {
                item.ContactInfo += "Address : " + item.Address + "/n";
            }
            if (!string.IsNullOrEmpty(item.CVMail))
            {
                item.ContactInfo += "Mail : " + item.CVMail;
            }

            if (item.Inactive.HasValue)
            {
                if(item.Inactive.Value)
                    item.InactiveString = "inactif";
                else
                    item.InactiveString = "actif";
            }

            return item;
        }
Exemplo n.º 40
0
        public ActionResult RetrievePhotoCandidate(int id)
        {
            byte[] image;

            using (var candidateRepository = new CandidateRepository())
            {
                image = candidateRepository.GetCandidateWithPhoto(id);
            }
            if (image == null)
                return File("~/Content/Banners/NoCandidate.jpg", "image/jpg");

            return File(image, "image/png");
        }
Exemplo n.º 41
0
        public JsonResult SaveCandidateName(int candidateId, string candidateName)
        {
            using (var candidateRepository = new CandidateRepository())
            {
                var result = candidateRepository.UpdateCandidateName(candidateId, candidateName, ElectionConductor.ElectionId((int)Session["UserId"]));

                return new JsonResult
                {
                    Data = new { isOk = result }
                };
            }
        }
Exemplo n.º 42
0
        public ActionResult UpdateCandidatePhoto(string name, HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                var imgByte = new Byte[file.ContentLength];
                file.InputStream.Read(imgByte, 0, file.ContentLength);

                using (var candidateRepository = new CandidateRepository())
                {
                    candidateRepository.UpdateCandidatePhoto(Convert.ToInt32(name), imgByte, ElectionConductor.ElectionId((int)Session["UserId"]));
                }
            }
            return RedirectToAction("Index");
        }
Exemplo n.º 43
0
        /*public JsonResult GetCandidates()
        {
            using (var candidateRepository = new CandidateRepository())
            {
                var candidateListModel = new CandidateListModel { CandidateList = candidateRepository.GetCandidatesForElectionId(ElectionConductor.ElectionId((int)Session["UserId"])).OrderBy(x => x.Name).ToList() };

                return new JsonResult
                {
                    Data = new { isOk = true, CandidateList = candidateListModel }
                };
            }
        }*/
        /*public JsonResult GetVoters()
        {
            using (var voterRepository = new VoterRepository())
            {
                var voterListModel = new VoterListModel { VoterList = voterRepository.GetVotersForElectionId(ElectionConductor.ElectionId((int)Session["UserId"])) };

                return new JsonResult
                {
                    Data = new { isOk = true, VoterList = voterListModel }
                };
            }
        }*/
        public JsonResult ViewVotes()
        {
            using (var votesRepository = new VotesRepository())
            using (var candidateRepository = new CandidateRepository())
            {
                var voteList = new List<CandidateVotes>();
                var candidateList = candidateRepository.GetCandidatesForElectionId(ElectionConductor.ElectionId((int)Session["UserId"]));

                foreach (var candidate in candidateList)
                {
                    var votes = votesRepository.GetVotesForElectionIdAndCandidateId(ElectionConductor.ElectionId((int)Session["UserId"]), candidate.CandidateId);
                    voteList.Add(new CandidateVotes { Candidate = candidate, Votes = votes });
                }

                var voteListModel = new VoteListModel { VoteList = voteList.OrderByDescending(x => x.Votes).ToList() };

                return new JsonResult
                {
                    Data = new { isOk = true, VoteList = voteListModel }
                };
            }
        }
Exemplo n.º 44
0
    /// <summary>
    /// Save general data of candidate to database.
    /// </summary>
    private Candidate SaveCandidateData()
    {
        if (string.IsNullOrEmpty(txtLastName.Text) || string.IsNullOrEmpty(txtFirstName.Text))
        {
            string message = ResourceManager.GetString("messageCanNameMustNotBeEmpty");
            string script = "<script type=\"text/javascript\">";
            script += " alert(\"" + message + "\")";
            script += " </script>";

            if (!ClientScript.IsClientScriptBlockRegistered("redirectUser"))
                ClientScript.RegisterStartupScript(this.GetType(), "redirectUser", script);
            return null;
        }
        bool isNew = false;
        //Save Candidate
        Candidate candidate = new Candidate();
        if (SessionManager.CurrentCandidate != null)
        {
            candidate = SessionManager.CurrentCandidate;
        }
        else
        {
            isNew = true;
            candidate = new Candidate();
        }
        //Common
        candidate.LastName = txtLastName.Text.Trim();
        candidate.FirstName = txtFirstName.Text.Trim();
        candidate.Unit = ddlUnit.SelectedValue;
        if (!string.IsNullOrEmpty(ddlInterviewer.SelectedValue))
            candidate.Interviewer = ddlInterviewer.SelectedValue;
        else
            candidate.Interviewer = null;
        candidate.DateOfInterView = datDateInterview.SelectedDate;
        candidate.LastModifDate = DateTime.Now;

        //Tab general
        candidate.Address = txtAddress.Text.Trim();
        candidate.ZipCode = txtZip.Text.Trim();
        candidate.City = txtCity.Text.Trim();
        candidate.CountryCode = ddlCountry.SelectedValue;
        candidate.Gender = ddlGenre.SelectedValue;
        if (!string.IsNullOrEmpty(ddlNationality.SelectedValue))
            candidate.Nationlity = ddlNationality.SelectedValue;
        else
            candidate.Nationlity = null;
        candidate.BirthDate = datDateOfBirth.SelectedDate;
        candidate.CreationDate = datCreationDate.SelectedDate;
        if (string.IsNullOrEmpty(ddlStatus.SelectedValue))
            candidate.Inactive = null;
        else
            candidate.Inactive = bool.Parse(ddlStatus.SelectedValue);
        candidate.ReasonDesactivation = txtInactivityReason.Text.Trim();
        candidate.Remark = txtRemarkGeneral.Text.Trim();
        //tab presentation
        if (!string.IsNullOrEmpty(radTabStripCandidateProfile.FindTabByValue("PresentationView").PageViewID))
            candidate.Presentation = txtPresentationText.Text;

        CandidateRepository repo = new CandidateRepository();
        if (isNew)
            repo.Insert(candidate);
        else
            repo.Update(candidate);
        candidate = repo.FindOne(candidate);
        SessionManager.CurrentCandidate = candidate;
        SaveLastViewCandidatesToCookie(candidate);
        if (isNew)
        {
            string script = "<script type='text/javascript'>";
            script += "onSaveOrLoadCandidateProfilePage();";
            script += "</script>";
            if (!ClientScript.IsClientScriptBlockRegistered("onSaveOrLoadCandidateProfilePage"))
                ClientScript.RegisterStartupScript(this.GetType(), "onSaveOrLoadCandidateProfilePage", script);
        }
        return candidate;
    }
Exemplo n.º 45
0
    private void BindLast5ViewedCandidate()
    {
        //Last 5 viewed candidates.
        XmlDocument doc = new XmlDocument();
        IList<Candidate> last5Candidates = new List<Candidate>();
        try
        {
            doc.Load(Server.MapPath("~/App_Data/LastViewedCandidates.xml"));

            XmlElement rootNode = doc.DocumentElement;
            if (rootNode != null)
            {
                XmlNode userNode = rootNode.SelectSingleNode("User[@id='" + SessionManager.CurrentUser.UserID + "']");
                if (userNode != null) //user node existed
                {
                    if (userNode.Attributes["viewed-candidates"] != null && !string.IsNullOrEmpty(userNode.Attributes["viewed-candidates"].Value))
                    {
                        List<string> list = new List<string>(userNode.Attributes["viewed-candidates"].Value.Split('&'));
                        foreach (string candidateID in list)
                        {
                            if (!string.IsNullOrEmpty(candidateID))
                            {
                                Candidate cand = new CandidateRepository().FindOne(new Candidate(Convert.ToInt32(candidateID)));
                                if (cand != null)
                                {
                                    last5Candidates.Add(cand);
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        #region commented
        /*
        if (lastCanCookie != null)
        {
            CandidateRepository canRepo = new CandidateRepository();
            string[] values = lastCanCookie.Values.ToString().Split('&');
            if (values.Length > 0 && !string.IsNullOrEmpty(values[0]))
            {
                string idList = string.Empty;
                for (int i = 0; i < values.Length; i++)
                {
                    string[] userAndCanIds = values[i].Split('=');
                    if (userAndCanIds[0] == SessionManager.CurrentUser.UserID.Trim())
                    {
                        idList = userAndCanIds[1];
                        break;
                    }
                }
                if (idList != string.Empty)
                {
                    string[] idArray = idList.Split('A');
                    for (int j = idArray.Length - 1; j >= 0; j--)
                    {
                        int id = int.Parse(idArray[j]);
                        Candidate can = canRepo.FindOne(new Candidate(id));
                        if (can != null)
                        {
                            last5Candidates.Add(can);
                        }
                    }
                }
            }
        }*/
        #endregion

        lastFiveCandidateList.DataSource = last5Candidates;
        lastFiveCandidateList.DataBind();
    }
Exemplo n.º 46
0
        public ActionResult Index()
        {
            if (Session["UserId"] == null)
                return RedirectToAction("Index", "Home");

            using (var electionRepository = new ElectionRepository())
            using (var candidateRepository = new CandidateRepository())
            using (var voterRepository = new VoterRepository())
            {
                if (electionRepository.GetElectionByUserId((int)Session["UserId"]) == null)
                {
                    electionRepository.CreateElection(new Election
                    {
                        UserId = (int)Session["UserId"],
                        Name = "My Election"
                    });
                }

                var election = electionRepository.GetElectionByUserId((int)Session["UserId"]);

                var electionIndexModel = new ElectionIndexModel
                {
                    Setup = new ElectionSetupModel
                    {
                        Name = election.Name,
                        Status = election.Status,
                        MinVotes = election.MinVotes,
                        MaxVotes = election.MaxVotes,
                        NoVote = election.NoVote
                    },
                    Candidates = candidateRepository.GetCandidatesForElectionId(ElectionConductor.ElectionId((int)Session["UserId"])).OrderBy(x => x.Name).ToList(),
                    VotersCount = voterRepository.GetVotersForElectionId(ElectionConductor.ElectionId((int)Session["UserId"])).Count
                };

                return View(electionIndexModel);
            }
        }