public bool ChangePassword(long userId, string newPassword) { var user = context.Users.SingleOrDefault(x => x.Id == userId); if (user == null) { return(false); } user.Password = newPassword; user.LastUpdatedTime = DateTime.Now; context.SaveChanges(); return(true); }
public static void Execute(int electionId, IJobCancellationToken cancellationToken) { using (var db = new VotingDbContext()) { Election election = db.Elections.Find(electionId); if (election == null) { throw new ArgumentOutOfRangeException(nameof(electionId), "No election with such id"); } if (election.DisableAutomaticEligibility) { // Nothing to do return; } using (var timetable = new TimetableDbContext()) { IEnumerable <ElectionEligibilityEntry> electionEntries = EligibilityGenerator.GenerateElectionEntries(election, timetable.Users); cancellationToken.ThrowIfCancellationRequested(); IEnumerable <PositionEligibilityEntry> positionEntries = EligibilityGenerator.GeneratePositionEntries(election, timetable.Users, db); cancellationToken.ThrowIfCancellationRequested(); // Note that we cannot dispose the timetable db context here // since the queries are only "planned" yet and not actually executed // Save election entries, only ones that do not exist in database AddNewEntries( electionEntries, db.ElectionEligibilityEntries, (entry, set) => set.Find(entry.Username, entry.Election.Id) ); cancellationToken.ThrowIfCancellationRequested(); // Save position entries, only ones that do not exist in database AddNewEntries( positionEntries, db.PositionEligibilityEntries, (entry, set) => set.Find(entry.Username, entry.Position.Id) ); cancellationToken.ThrowIfCancellationRequested(); db.SaveChanges(); } } }
public void Execute(Guid transitionId) { ElectionStateChange transition = GetTransition(transitionId); if (transition.CompletedAt != null) { throw new ArgumentOutOfRangeException( nameof(transitionId), "This transition is already executed" ); } // We don't need the return, but this does validation which we want (before executing the change) DecideTransitionKind(transition); transition.Election.State = transition.TargetState; transition.CompletedAt = DateTime.Now; _db.SaveChanges(); AuditLogManager.RecordElectionStateChange(transition); }
public void Synchronise(Func <VotingDbContext, TEntity> entityFetcher) { using (TransactionScope scope = new TransactionScope()) { using (_db = new VotingDbContext()) { TEntity entity = entityFetcher(_db); BackgroundJobClient jobClient = new BackgroundJobClient( new SqlServerStorage(Startup.HangfireConnectionName) ); foreach (IDelayedJobDescriptor descriptor in GetDescriptors(entity)) { ProcessDescriptor(descriptor, jobClient); } _db.SaveChanges(); } scope.Complete(); } }
public ActionResult NewElectionEntry(NewElectionEntry model) { if (!ModelState.IsValid) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } // STEP 1: Fetch everything we got as IDs Election election = _db.Elections.Find(model.ElectionId); TimetableUserEntry user = _userRepository.GetByUsername(model.UserId); // STEP 2: Check that everything is correct List <string> errors = new List <string>(); bool suggestReload = false; if (election == null) { errors.Add("Failed to find election"); suggestReload = true; } if (user == null) { errors.Add("Invalid student ID"); } if (user != null && !user.IsStudentActive) { errors.Add("Only active students can participate in elections"); } if (errors.Count > 0) { ViewBag.SuggestReload = suggestReload; string errorHtml = PartialView("_ErrorsDisplay", errors).RenderToString(); return(Json(new { Success = false, HumanErrorHtml = errorHtml })); } // STEP 3: Check that there isn't an entry already for this user // ReSharper disable PossibleNullReferenceException if (_db.ElectionEligibilityEntries.Find(user.UserId, election.Id) != null) { return(Json(new { Success = false, HumanError = "Error: there is already an entry for this user" })); } // STEP 4: Create a new entity and save it ElectionEligibilityEntry newEntry = new ElectionEligibilityEntry() { Username = model.UserId, Election = election }; _db.ElectionEligibilityEntries.Add(newEntry); _db.SaveChanges(); // STEP 5: Prepare the displayed table row ElectionTableRow tableRow = new ElectionTableRow { UserId = user.UserId }; PopulateUserInfo(tableRow, user); // STEP 6: Reply that we are done return(Json(new { Success = true, Entry = tableRow })); }
public static void Execute(int electionId, IJobCancellationToken cancellationToken) { TimetableDbContext timetableDb = new TimetableDbContext(); VotingDbContext db = new VotingDbContext(); Election election = db.Elections.Find(electionId); if (election == null) { throw new ArgumentOutOfRangeException(nameof(electionId), "No election with such id"); } if (election.Type != ElectionType.CourseRepresentative) { throw new Exception("Election must be of type " + ElectionType.CourseRepresentative); } if (!election.PositionGenerationInProcess) { throw new Exception($"Election {election.Name} is not pending position generation"); } // Generate the list as it is intended to be now List <RepresentativePositionData> desiredPositionDatas = timetableDb.Users .WhereIsStudentActive() .Select(entry => new { entry.ProgrammeName, entry.ExpectedGraduationYearString }) .Distinct() .AsEnumerable() .Select(combination => { var data = new RepresentativePositionData { ProgrammeName = combination.ProgrammeName, ExpectedGraduationYearString = combination.ExpectedGraduationYearString, PositionCommon = new VotablePosition { Election = election } }; data.SetPositionName(); return(data); }) .ToList(); // Get the current positions in DB List <RepresentativePositionData> matchedDesiredDatas = new List <RepresentativePositionData>(); IQueryable <RepresentativePositionData> positionsDataFromDb = db.RepresentativePositionData .Where(data => data.PositionCommon.ElectionId == electionId); foreach (RepresentativePositionData existingPositionData in positionsDataFromDb) { RepresentativePositionData matchingDesiredData = desiredPositionDatas.FirstOrDefault(desiredData => existingPositionData.ProgrammeName == desiredData.ProgrammeName && existingPositionData.ExpectedGraduationYearString == desiredData.ExpectedGraduationYearString ); if (matchingDesiredData != null) { // Found matching entry. Apply the position name in case the naming logic changed existingPositionData.PositionCommon.HumanName = matchingDesiredData.PositionCommon.HumanName; matchedDesiredDatas.Add(matchingDesiredData); } else { // Did not match - no longer needed db.RepresentativePositionData.Remove(existingPositionData); } } // Add the new positions (that didn't match existing) to the db db.RepresentativePositionData.AddRange(desiredPositionDatas.Except(matchedDesiredDatas)); // Make sure we are allowed to submit our changes cancellationToken.ThrowIfCancellationRequested(); // We are done election.PositionGenerationInProcess = false; db.SaveChanges(); }