Esempio n. 1
0
 protected static void LogImageHeadshotChange(string politicianKey, byte[] oldImageBlob, byte[] newImageBlob,
                                              DateTime uploadTime)
 {
     LogDataChange.LogUpdate(PoliticiansImagesBlobs.Column.Headshot100,
                             oldImageBlob, newImageBlob, UserName, UserSecurityClass, uploadTime,
                             politicianKey);
 }
Esempio n. 2
0
        public async Task UpdateAsync(string email, string rolName)
        {
            var rol = AppRoles.FindByName(rolName);

            var edit = await _userManager.FindByEmailAsync(email);

            if (edit == null)
            {
                throw new AppNotFoundException("Usuario no encontrado");
            }

            var roles = await _userManager.GetRolesAsync(edit);

            await _userManager.RemoveFromRolesAsync(edit, roles);

            await _userManager.AddToRoleAsync(edit, rol.Name);

            var log = new LogDataChange
            {
                UpdatedAt = DateTime.UtcNow,
                UpdatedBy = _appIdentity.Username,
                Table     = "UsersRoles",
                Pk        = int.Parse(edit.Id.ToString()),
                Changes   = $"Role: {roles[0]} => {rol.Name}"
            };

            await _unitOfWork.LogsDataChanges.AddAsync(log);

            await _unitOfWork.SaveChangesAsync();
        }
Esempio n. 3
0
 protected void LogImageChange(byte[] oldImageBlob, byte[] newImageBlob,
                               DateTime uploadTime)
 {
     LogDataChange.LogUpdate(PoliticiansImagesBlobs.Column.ProfileOriginal,
                             oldImageBlob, newImageBlob, UserName, UserSecurityClass, uploadTime,
                             PoliticianKey);
 }
Esempio n. 4
0
        protected void ButtonRevertToLog_ServerClick(object sender, EventArgs e)
        {
            try
            {
                var politicianKey = LabelPoliticianKey.Text;
                var latestLogDate =
                    LogDataChange.GetSecondLatestProfileImageDate(politicianKey, out _);

                var logTime    = new DateTime(latestLogDate.Ticks);
                var loggedBlob = LatestLoggedImagePage.GetLoggedImageByDate(politicianKey, logTime);
                if (latestLogDate.IsDefaultDate() || loggedBlob == null || loggedBlob.Length == 0)
                {
                    Msg.Text = Fail("No log profile image for ID " + politicianKey + " was found.");
                }
                else
                {
                    var now = DateTime.UtcNow;
                    ImageManager.UpdatePoliticianProfileImages(politicianKey,
                                                               new MemoryStream(loggedBlob), now, out _);
                    CommonCacheInvalidation.ScheduleInvalidation("politicianimage", politicianKey);
                    LogImageChange(politicianKey, null, loggedBlob, now);
                    Msg.Text = Ok("The profile image for ID " + politicianKey +
                                  " was reverted to the most recent logged version.");
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
Esempio n. 5
0
            protected override bool Update(object newValue)
            {
                var orderChanged = false;
                var stringValue  = newValue.ToString();
                var electionKey  = Page.GetElectionKey();

                if (!IsNullOrWhiteSpace(stringValue))
                {
                    var referendumKeys = stringValue
                                         .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                                         .Select(s => s.Substring(s.LastIndexOf('-') + 1));
                    var referendumOrder = 10;
                    foreach (var referendumKey in referendumKeys)
                    {
                        var oldReferendumOrder =
                            Referendums.GetOrderOnBallot(electionKey, referendumKey, 0);
                        if (referendumOrder != oldReferendumOrder)
                        {
                            Referendums.UpdateOrderOnBallot(referendumOrder, electionKey, referendumKey);
                            LogDataChange.LogUpdate(Referendums.Column.OrderOnBallot,
                                                    oldReferendumOrder.ToString(CultureInfo.InvariantCulture),
                                                    referendumOrder.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow,
                                                    electionKey, referendumKey);
                            orderChanged = true;
                        }
                        referendumOrder += 10;
                    }
                }
                LoadControl();
                return(orderChanged);
            }
Esempio n. 6
0
 protected override void Log(string oldValue, string newValue)
 {
     if (Column != "AdImageChanged" && Column != "AdImageUpdated")
     {
         LogDataChange.LogUpdate(Politicians.TableName, Column, oldValue, newValue,
                                 VotePage.UserName, SecurePage.UserSecurityClass, DateTime.UtcNow,
                                 ThisControl.GetPoliticianKeyToEdit().Key);
     }
 }
 protected override void Log(string oldValue, string newValue)
 {
     if (ThisControl.Mode == DataMode.ManageCandidates)
     {
         LogDataChange.LogUpdate(ElectionsPoliticians.Column.IsIncumbent, oldValue,
                                 newValue, VotePage.UserName, SecurePage.UserSecurityClass, DateTime.UtcNow,
                                 ThisControl.SafeGetElectionKey(), ThisControl.SafeGetOfficeKey(),
                                 ThisControl.GetPoliticianKeyToEdit());
     }
 }
Esempio n. 8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Page.Title   = "Payments";
                H1.InnerHtml = "Payments";

                LogDataChange.GetBillingSummary("Ilya.Shambat",
                                                new DateTime(2014, 1, 1), new DateTime(2014, 4, 30));
            }
        }
Esempio n. 9
0
            //private Control GenerateReport(string userName, DateTime startDate, DateTime endDate)
            //{
            //  var table1 =
            //    LogPoliticianAnswers.GetBillingDataByUserNameDateStampRange(userName,
            //      startDate, endDate);
            //  var table2 =
            //    LogDataChange.GetBillingDataByUserNameTableNameDateStampRange(
            //      userName, "Answers", startDate, endDate);

            //  var dateList = table1.Select(row => row.DateStamp.Date)
            //    .Concat(table2.Select(row => row.DateStamp.Date))
            //    .GroupBy(date => date)
            //    .Select(g => new DateCount { DateStamp = g.Key, Count = g.Count() });

            //  return GenerateReport(dateList, "Politician Answers", "Answers", 30);
            //}

            private Control GenerateReport(string userName, DateTime startDate, DateTime endDate)
            {
                var dateList = LogDataChange.GetBillingDataByUserNameTableNameDateStampRange(
                    userName, "Answers", startDate, endDate).Select(row => row.DateStamp.Date)
                               .GroupBy(date => date)
                               .Select(g => new DateCount {
                    DateStamp = g.Key, Count = g.Count()
                });

                return(GenerateReport(dateList, "Politician Answers", "Answers", 30));
            }
Esempio n. 10
0
            //private Control GenerateReport(string userName, DateTime startDate, DateTime endDate)
            //{
            //  var table =
            //    LogOfficeOfficialChanges.GetBillingDataByUserNameDateStampRange(
            //      userName, startDate, endDate);
            //  var dateList = table.GroupBy(row => row.DateStamp.Date)
            //    .Select(
            //      group => new DateCount { DateStamp = group.Key, Count = group.Count() });

            //  return GenerateReport(dateList, "OfficesOfficials Changes", "Changes",
            //    15);
            //}

            private Control GenerateReport(string userName, DateTime startDate, DateTime endDate)
            {
                var dateList = LogDataChange.GetBillingDataByUserNameTableNameDateStampRange(
                    userName, "OfficesOfficials", startDate, endDate)
                               .Where(row => row.ColumnName != "*INSERT")
                               .Select(row => row.DateStamp.Date)
                               .GroupBy(date => date)
                               .Select(g => new DateCount {
                    DateStamp = g.Key, Count = g.Count()
                });

                return(GenerateReport(dateList, "OfficesOfficials Changes", "Changes", 10));
            }
Esempio n. 11
0
        private void AuditEntities()
        {
            // Each entity that inherits from auditable
            foreach (EntityEntry <Auditable> entry in ChangeTracker.Entries <Auditable>())
            {
                var now          = DateTime.UtcNow;
                var _appIdentity = this.GetService <AppIdentity>();

                if (entry.State == EntityState.Added)
                {
                    entry.Property("CreatedBy").CurrentValue = _appIdentity.Username;
                    entry.Property("CreatedAt").CurrentValue = now;
                }
                else if (entry.State == EntityState.Modified) // si la entidad fue actualizada
                {
                    entry.Property("CreatedBy").CurrentValue = entry.Property("CreatedBy").OriginalValue;
                    entry.Property("CreatedAt").CurrentValue = entry.Property("CreatedAt").OriginalValue;

                    var tableName = entry.Metadata.GetTableName();
                    var pk        = entry.OriginalValues[entry.Metadata.FindPrimaryKey().Properties.First()] ?? 0;

                    var changes = new List <string>();

                    foreach (var item in entry.Properties.Where(x => x.IsModified))
                    {
                        var columnName = item.Metadata.Name;
                        var oldValue   = item.OriginalValue == null ? "" : item.OriginalValue.ToString();
                        var newValue   = item.CurrentValue == null ? "" : item.CurrentValue.ToString();

                        var change = $"{columnName} : {oldValue} => {newValue}";
                        if (oldValue != newValue)
                        {
                            changes.Add(change);
                        }
                    }

                    if (changes.Count > 0)
                    {
                        var log = new LogDataChange
                        {
                            Table     = tableName,
                            Pk        = int.Parse(pk.ToString()),
                            Changes   = string.Join(Environment.NewLine, changes),
                            UpdatedBy = _appIdentity.Username,
                            UpdatedAt = now
                        };
                        entry.Context.Set <LogDataChange>().Add(log);
                    }
                }
            }
        }
Esempio n. 12
0
 internal static byte[] GetLoggedImageByDate(string politicianKey, DateTime date)
 {
     byte[] blob = null;
     //var originalTable = LogPoliticiansImagesOriginal
     //  .GetDataByPoliticianKeyProfileOriginalDate(politicianKey, date);
     //if (originalTable.Count == 1)
     //  blob = originalTable[0].ProfileOriginal;
     //else
     {
         var newOriginalsTable =
             LogDataChange.GetDataByTableNameColumnNameKeyValuesDateStamp(
                 "PoliticiansImagesBlobs", "ProfileOriginal", politicianKey, date);
         if (newOriginalsTable.Count == 1)
         {
             blob = Convert.FromBase64String(newOriginalsTable[0].NewValue);
         }
     }
     return(blob);
 }
Esempio n. 13
0
        public static LogDataChangeModel Map(LogDataChange _)
        {
            var result = new LogDataChangeModel
            {
                Id                     = _.ID,
                After                  = HidePasswordFromDeserialization.Hide(_.After),
                Before                 = HidePasswordFromDeserialization.Hide(_.Before),
                ComputerName           = _.ComputerName,
                EntryDate              = _.EntryDate,
                EntryUser              = _.EntryUser,
                IdEntryUser            = _.IDEntryUser,
                IpAddress              = _.IDAddress,
                IsMobileDevice         = _.IsMobileDevice,
                LogBrowserType         = _.IDLogBrowserTypeNavigation.Title,
                LogDataChangeStatus    = _.IDLogDataChangeStatusNavigation.Title,
                LogOperatingSystemType = _.IDLogOperatingSystemTypeNavigation.Title
            };

            return(result);
        }
            protected override void Log(string oldValue, string newValue)
            {
                switch (Page.AdminPageLevel)
                {
                case AdminPageLevel.State:
                    LogDataChange.LogUpdate(States.TableName, Column, oldValue, newValue,
                                            UserName, UserSecurityClass, DateTime.UtcNow, Page.StateCode);
                    break;

                case AdminPageLevel.County:
                    LogDataChange.LogUpdate(Counties.TableName, Column, oldValue, newValue,
                                            UserName, UserSecurityClass, DateTime.UtcNow, Page.StateCode,
                                            Page.CountyCode);
                    break;

                case AdminPageLevel.Local:
                    LogDataChange.LogUpdate(LocalDistricts.TableName, Column, oldValue,
                                            newValue, UserName, UserSecurityClass, DateTime.UtcNow,
                                            Page.StateCode, Page.CountyCode, Page.LocalCode);
                    break;
                }
            }
Esempio n. 15
0
        public void AddLogDataChange(byte[] before, byte[] after, DataChangeStatus action, string TableName)
        {
            var IdTable       = _logRepository.GetTableByName(TableName);
            var entryUser     = _userRepoService.GetUserByUsername(_contextAccessor.HttpContext.User?.Identity?.Name);
            var logDataChange = new LogDataChange
            {
                EntryDate                = DateTime.Now,
                IDEntryUser              = entryUser != null ? entryUser.ID : 999999,
                EntryUser                = entryUser != null ? entryUser.Account : "public",
                Before                   = before,
                After                    = after,
                IDTable                  = IdTable,
                ComputerName             = NetworkHelper.GetComputerName(),
                IDAddress                = NetworkHelper.GetIPAddress(),
                IDLogBrowserType         = NetworkHelper.GetBrowserTypeId(),
                IDLogOperatingSystemType = NetworkHelper.GetOperatingSystemTypeId(),
                IsMobileDevice           = NetworkHelper.IsMobileDevice(),
                IDLogDataChangeStatus    = (int)action
            };

            _logRepository.AddLogDataChange(logDataChange);
        }
Esempio n. 16
0
        protected void ButtonRevertToLog_ServerClick(object sender, EventArgs e)
        {
            try
            {
                var    politicianKey = LabelPoliticianKey.Text;
                string user;
                var    latestLogDate =
                    LogDataChange.GetSecondLatestProfileImageDate(politicianKey, out user);

                var logTime    = new DateTime(latestLogDate.Ticks);
                var loggedBlob = LatestLoggedImagePage.GetLoggedImageByDate(
                    politicianKey, logTime);
                if ((latestLogDate == DefaultDbDate) || (loggedBlob == null) ||
                    (loggedBlob.Length == 0))
                {
                    Msg.Text =
                        Fail("No log profile image for ID " + politicianKey + " was found.");
                }
                else
                {
                    var  now = DateTime.UtcNow;
                    Size originalSize;
                    ImageManager.UpdatePoliticianProfileImages(politicianKey,
                                                               new MemoryStream(loggedBlob), now, out originalSize);
                    CommonCacheInvalidation.ScheduleInvalidation("politicianimage",
                                                                 politicianKey);
                    LogPoliticiansImagesOriginal.Insert(politicianKey, loggedBlob, now,
                                                        UserSecurityClass, UserName, 0);
                    Msg.Text =
                        Ok("The profile image for ID " + politicianKey +
                           " was reverted to the most recent logged version.");
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
Esempio n. 17
0
 protected override void Log(string oldValue, string newValue)
 {
     LogDataChange.LogUpdate(VolunteersView.TableName, Column, oldValue, newValue,
                             UserName, UserSecurityClass, DateTime.UtcNow,
                             _Page.GetVolunteerToEdit());
 }
Esempio n. 18
0
            private bool UpdateManageCandidates(object newValue)
            {
                var electionKey   = _ThisControl.SafeGetElectionKey();
                var officeKey     = _ThisControl.SafeGetOfficeKey();
                var newCandidates = UpdateParse(newValue);

                // Get the current slate of candidate for this election/office
                var currentCandidatesTable =
                    ElectionsPoliticians.GetDataByElectionKeyOfficeKey(electionKey, officeKey);

                // Get the incumbent(s) for this office
                var incumbents =
                    Enumerable.Select(OfficesOfficials.GetPoliticianKeysData(officeKey),
                                      row => row.PoliticianKey)
                    .ToList();

                // If we process a row, we delete it from this list. What's left needs
                // to be deleted from the DB.
                var rowsToDelete = Enumerable.Select(currentCandidatesTable, row => row)
                                   .ToList();

                var orderOnBallot = 0;
                var federalCode   = Offices.GetOfficeClass(officeKey)
                                    .StateCodeProxy();
                var stateCode = Elections.GetStateCodeFromKey(electionKey);

                if (StateCache.IsValidFederalCode(stateCode, false))
                {
                    stateCode = string.Empty;
                }
                var countyCode         = Elections.GetCountyCodeFromKey(electionKey);
                var localCode          = Elections.GetLocalCodeFromKey(electionKey);
                var electionKeyFederal = string.IsNullOrWhiteSpace(federalCode)
          ? string.Empty
          : Elections.GetFederalElectionKeyFromKey(electionKey, federalCode);
                var electionKeyState  = Elections.GetStateElectionKeyFromKey(electionKey);
                var electionKeyCounty = Elections.GetCountyElectionKeyFromKey(electionKey);
                var electionKeyLocal  = Elections.GetLocalElectionKeyFromKey(electionKey);

                foreach (var candidate in newCandidates)
                {
                    orderOnBallot += 10;
                    var currentRow =
                        currentCandidatesTable.FirstOrDefault(
                            row => row.PoliticianKey.IsEqIgnoreCase(candidate.PoliticianKey));
                    if (currentRow == null)
                    {
                        // new candidate, add
                        LogDataChange.LogInsert(ElectionsPoliticians.TableName,
                                                candidate.RunningMateKey, DateTime.UtcNow, electionKey, officeKey,
                                                candidate.PoliticianKey);
                        currentCandidatesTable.AddRow(electionKey, officeKey,
                                                      candidate.PoliticianKey, candidate.RunningMateKey, electionKeyState,
                                                      electionKeyFederal, electionKeyCounty, electionKeyLocal, stateCode,
                                                      countyCode, localCode, string.Empty, orderOnBallot, false,
                                                      incumbents.Contains(candidate.PoliticianKey), false);
                    }
                    else
                    {
                        // existing candidate, update if necessary
                        if (currentRow.RunningMateKey.IsNeIgnoreCase(candidate.RunningMateKey))
                        {
                            LogDataChange.LogUpdate(ElectionsPoliticians.Column.RunningMateKey,
                                                    currentRow.RunningMateKey, candidate.RunningMateKey,
                                                    DateTime.UtcNow, electionKey, officeKey, candidate.PoliticianKey);
                            currentRow.RunningMateKey = candidate.RunningMateKey;
                        }
                        if (currentRow.OrderOnBallot != orderOnBallot)
                        {
                            LogDataChange.LogUpdate(ElectionsPoliticians.Column.OrderOnBallot,
                                                    currentRow.OrderOnBallot, orderOnBallot, DateTime.UtcNow,
                                                    electionKey, officeKey, candidate.PoliticianKey);
                            currentRow.OrderOnBallot = orderOnBallot;
                        }
                        rowsToDelete.Remove(currentRow);
                    }
                }

                foreach (var row in rowsToDelete)
                {
                    LogDataChange.LogDelete(ElectionsPoliticians.TableName, DateTime.UtcNow,
                                            electionKey, officeKey, row.PoliticianKey);
                    row.Delete();
                }

                // Update if any changes
                var candidateListChanged =
                    currentCandidatesTable.FirstOrDefault(
                        row => row.RowState != DataRowState.Unchanged) != null;

                if (candidateListChanged)
                {
                    ElectionsPoliticians.UpdateTable(currentCandidatesTable);
                }

                LoadControl();
                return(candidateListChanged);
            }
Esempio n. 19
0
            private bool UpdateManageIncumbents(object newValue)
            {
                var officeKey     = _ThisControl.SafeGetOfficeKey();
                var newIncumbents = UpdateParse(newValue);

                // Get the current slate of incumbents for this office
                var currentIncumbentsTable = OfficesOfficials.GetDataByOfficeKey(officeKey);

                // If we process a row, we delete it from this list. What's left needs
                // to be deleted from the DB.
                var rowsToDelete = Enumerable.Select(currentIncumbentsTable, row => row)
                                   .ToList();

                var stateCode  = Offices.GetStateCodeFromKey(officeKey);
                var countyCode = Offices.GetCountyCodeFromKey(officeKey);
                var localCode  = Offices.GetLocalCodeFromKey(officeKey);

                foreach (var incumbent in newIncumbents)
                {
                    var currentRow =
                        currentIncumbentsTable.FirstOrDefault(
                            row => row.PoliticianKey.IsEqIgnoreCase(incumbent.PoliticianKey));
                    if (currentRow == null)
                    {
                        // new incumbent, add
                        LogDataChange.LogInsert(OfficesOfficials.TableName,
                                                incumbent.RunningMateKey, DateTime.UtcNow, officeKey,
                                                incumbent.PoliticianKey);
                        currentIncumbentsTable.AddRow(officeKey, incumbent.PoliticianKey,
                                                      incumbent.RunningMateKey, stateCode, countyCode, localCode,
                                                      Offices.GetDistrictCode(officeKey), /*String.Empty, VotePage.DefaultDbDate,*/
                                                      DateTime.UtcNow, SecurePage.AdminSecurityClass, VotePage.UserName);
                    }
                    else
                    {
                        // existing incumbent, update if necessary
                        if (currentRow.RunningMateKey.IsNeIgnoreCase(incumbent.RunningMateKey))
                        {
                            LogDataChange.LogUpdate(OfficesOfficials.Column.RunningMateKey,
                                                    currentRow.RunningMateKey, incumbent.RunningMateKey,
                                                    DateTime.UtcNow, officeKey, incumbent.PoliticianKey);
                            currentRow.RunningMateKey = incumbent.RunningMateKey;
                        }
                        rowsToDelete.Remove(currentRow);
                    }
                }

                foreach (var row in rowsToDelete)
                {
                    LogDataChange.LogDelete(OfficesOfficials.TableName, DateTime.UtcNow,
                                            officeKey, row.PoliticianKey);
                    row.Delete();
                }

                // Update if any changes
                var incumbentListChanged =
                    currentIncumbentsTable.FirstOrDefault(
                        row => row.RowState != DataRowState.Unchanged) != null;

                if (incumbentListChanged)
                {
                    OfficesOfficials.UpdateTable(currentIncumbentsTable);
                }

                LoadControl();
                return(incumbentListChanged);
            }
Esempio n. 20
0
 protected static void LogElectionsOfficesInsert(string electionKey, string officeKey)
 {
     LogDataChange.LogInsert(ElectionsOffices.TableName, UserName, UserSecurityClass,
                             DateTime.UtcNow, electionKey, officeKey);
 }
Esempio n. 21
0
            protected override bool Update(object newValue)
            {
                //Parse the value from the UI tree
                if (!(newValue is string valueStr))
                {
                    return(false);
                }
                var offices = valueStr.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                              .Select(officeStr =>
                {
                    var officeSplit = officeStr.Split('=');
                    var isRunoff    = officeSplit[1].StartsWith("*", StringComparison.Ordinal);
                    if (isRunoff)
                    {
                        officeSplit[1] = officeSplit[1].Substring(1);
                    }
                    return(new
                    {
                        OfficeKey = officeSplit[0],
                        IsRunoff = isRunoff,
                        Ids = officeSplit[1].Split(',')
                    });
                });

                var electionKey = Page.GetElectionKey();
                var table       = ElectionsPoliticians.GetWinnersData(electionKey);

                foreach (var o in offices)
                {
                    var office      = o;
                    var politicians = table
                                      .Where(row => row.OfficeKey().IsEqIgnoreCase(office.OfficeKey)).ToList();
                    foreach (var politician in politicians)
                    {
                        if (office.IsRunoff)
                        {
                            var advance = office.Ids.Contains(politician.PoliticianKey,
                                                              StringComparer.OrdinalIgnoreCase);
                            if (politician.AdvanceToRunoff != advance)
                            {
                                LogDataChange.LogUpdate(ElectionsPoliticians.Column.AdvanceToRunoff,
                                                        politician.AdvanceToRunoff, advance, DateTime.UtcNow, electionKey,
                                                        politician.OfficeKey, politician.PoliticianKey);
                            }
                            politician.AdvanceToRunoff = advance;
                            politician.IsWinner        = false;
                        }
                        else // non-runoff
                        {
                            var isWinner = office.Ids.Contains(politician.PoliticianKey,
                                                               StringComparer.OrdinalIgnoreCase);
                            if (politician.IsWinner != isWinner)
                            {
                                LogDataChange.LogUpdate(ElectionsPoliticians.Column.IsWinner,
                                                        politician.IsWinner, isWinner, DateTime.UtcNow, electionKey,
                                                        politician.OfficeKey, politician.PoliticianKey);
                            }
                            politician.IsWinner        = isWinner;
                            politician.AdvanceToRunoff = false;
                        }
                    }
                }

                // Update if any changes
                var winnersChanged =
                    table.FirstOrDefault(row => row.RowState != DataRowState.Unchanged) != null;

                if (winnersChanged)
                {
                    ElectionsPoliticians.UpdateTable(table,
                                                     ElectionsPoliticiansTable.ColumnSet.Winners);
                }

                LoadControl();
                return(winnersChanged);
            }
Esempio n. 22
0
 private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
         var politicianKey = PoliticianKeyTextBox.Text.Trim();
         if (IsNullOrEmpty(politicianKey))
         {
             throw new VoteException("Politician Key is missing");
         }
         if (IsNullOrEmpty(FolderTextBox.Text.Trim()))
         {
             throw new VoteException("Save Folder is missing");
         }
         var folder = new DirectoryInfo(FolderTextBox.Text.Trim());
         if (!folder.Exists)
         {
             throw new VoteException("Save Folder does not exist");
         }
         var newOriginalsTable =
             LogDataChange.GetDataByTableNameColumnNameKeyValues(
                 PoliticiansImagesBlobs.TableName,
                 PoliticiansImagesBlobs.GetColumnName(
                     PoliticiansImagesBlobs.Column.ProfileOriginal), politicianKey, 0);
         var newHeadshotsTable =
             LogDataChange.GetDataByTableNameColumnNameKeyValues(
                 PoliticiansImagesBlobs.TableName,
                 PoliticiansImagesBlobs.GetColumnName(
                     PoliticiansImagesBlobs.Column.Headshot100), politicianKey, 0);
         var images = new List <ImageInfo>();
         images.AddRange(newOriginalsTable.Where(row => row.NewValue != null)
                         .Select(row => new ImageInfo
         {
             ImageType = "Profile",
             Date      = row.DateStamp,
             User      = row.UserName,
             Blob      = Convert.FromBase64String(row.NewValue)
         }));
         images.AddRange(newHeadshotsTable.Where(row => row.NewValue != null)
                         .Select(row => new ImageInfo
         {
             ImageType = "Headshot",
             Date      = row.DateStamp,
             User      = row.UserName,
             Blob      = Convert.FromBase64String(row.NewValue)
         }));
         if (images.Count == 0)
         {
             throw new VoteException("No logged images found for this Politician Key");
         }
         folder.CreateSubdirectory(politicianKey);
         AppendStatusText("Found {0} images:", images.Count);
         foreach (var imageInfo in images)
         {
             var memoryStream = new MemoryStream(imageInfo.Blob);
             var image        = Image.FromStream(memoryStream);
             var contentType  = ImageManager.GetContentType(image);
             var extension    = $".{contentType.Replace("image/", "")}";
             var filename     =
                 $"{imageInfo.ImageType}_{imageInfo.Date:yyyy-MM-dd-HH-mm-ss}_{imageInfo.User}{extension}";
             var path = Path.Combine(folder.FullName, politicianKey, filename);
             File.WriteAllBytes(path, imageInfo.Blob);
             AppendStatusText(filename);
         }
         AppendStatusText(Empty);
     }
     catch (VoteException ex)
     {
         AppendStatusText(ex.Message);
     }
     catch (Exception ex)
     {
         AppendStatusText(ex.ToString());
     }
 }
 protected override void Log(string oldValue, string newValue) =>
 LogDataChange.LogUpdate(Referendums.TableName, Column, oldValue, newValue,
                         UserName, UserSecurityClass, DateTime.UtcNow, Page.GetElectionKey(),
                         Page.GetBallotMeasureKey());
Esempio n. 24
0
            protected override bool Update(object newValue)
            {
                //Parse the value from the UI tree
                var valueStr = newValue as string;

                if (valueStr == null)
                {
                    return(false);
                }
                var offices = valueStr.Split(new[] { '|' },
                                             StringSplitOptions.RemoveEmptyEntries)
                              .Select(officeStr =>
                {
                    var selected    = officeStr[0] == '*';
                    var officeSplit = officeStr.Substring(selected ? 1 : 0)
                                      .Split('=');
                    var isRunoff = officeSplit[1].StartsWith("*", StringComparison.Ordinal);
                    if (isRunoff)
                    {
                        officeSplit[1] = officeSplit[1].Substring(1);
                    }
                    return
                    (new
                    {
                        Selected = selected,
                        OfficeKey = officeSplit[0],
                        IsRunoff = isRunoff,
                        Ids = officeSplit[1].Split(',')
                    });
                });

                var electionKey = Page.GetElectionKey();
                var table       = ElectionsPoliticians.GetWinnersData(electionKey);

                foreach (var o in offices)
                {
                    var office      = o;
                    var politicians = table.Where(row => row.OfficeKey()
                                                  .IsEqIgnoreCase(office.OfficeKey))
                                      .ToList();
                    foreach (var politician in politicians)
                    {
                        if (office.IsRunoff)
                        {
                            var advance = office.Ids.Contains(politician.PoliticianKey,
                                                              StringComparer.OrdinalIgnoreCase);
                            if (politician.AdvanceToRunoff != advance)
                            {
                                LogDataChange.LogUpdate(
                                    ElectionsPoliticians.Column.AdvanceToRunoff,
                                    politician.AdvanceToRunoff, advance, DateTime.UtcNow, electionKey,
                                    politician.OfficeKey, politician.PoliticianKey);
                            }
                            politician.AdvanceToRunoff = advance;
                            politician.IsWinner        = false;
                        }
                        else // non-runoff
                        {
                            var isWinner = office.Ids.Contains(politician.PoliticianKey,
                                                               StringComparer.OrdinalIgnoreCase);
                            if (politician.IsWinner != isWinner)
                            {
                                LogDataChange.LogUpdate(ElectionsPoliticians.Column.IsWinner,
                                                        politician.IsWinner, isWinner, DateTime.UtcNow, electionKey,
                                                        politician.OfficeKey, politician.PoliticianKey);
                            }
                            politician.IsWinner        = isWinner;
                            politician.AdvanceToRunoff = false;
                        }
                    }
                    if (office.Selected)
                    {
                        // Update incumbents
                        var positions           = Offices.GetPositionsDataByOfficeKey(office.OfficeKey)[0];
                        var incumbents          = OfficesOfficials.GetData(office.OfficeKey);
                        var politicianKeysToAdd = new List <string>(office.Ids.Where(id => id != "vacant"));
                        foreach (var incumbent in incumbents)
                        {
                            var index =
                                politicianKeysToAdd.FindIndex(
                                    key => key.IsEqIgnoreCase(incumbent.PoliticianKey));
                            if (index >= 0)
                            {
                                politicianKeysToAdd.RemoveAt(index);
                            }
                            // we don't remove old incumbents for offices with
                            // Incumbents > ElectionPositions
                            else if (positions.ElectionPositions == positions.Incumbents)
                            {
                                incumbent.Delete();
                            }
                        }
                        foreach (var keyToAdd in politicianKeysToAdd)
                        {
                            var politician =
                                politicians.FirstOrDefault(
                                    row => row.PoliticianKey.IsEqIgnoreCase(keyToAdd));
                            var runningMateKey = politician == null
                ? string.Empty
                : politician.RunningMateKey;
                            incumbents.AddRow(officeKey: office.OfficeKey,
                                              politicianKey: keyToAdd, runningMateKey: runningMateKey,
                                              stateCode: Offices.GetStateCodeFromKey(office.OfficeKey),
                                              countyCode: Offices.GetCountyCodeFromKey(office.OfficeKey),
                                              localCode: Offices.GetLocalCodeFromKey(office.OfficeKey),
                                              districtCode: string.Empty,
                                              //LDSVersion: String.Empty, LDSUpdateDate: DefaultDbDate,
                                              dataLastUpdated: DateTime.UtcNow,
                                              userSecurity: UserSecurityClass, userName: UserName);
                            LogDataChange.LogInsert(OfficesOfficials.TableName, DateTime.UtcNow,
                                                    office.OfficeKey, keyToAdd);
                        }

                        // Update if any changes
                        var incumbentsChanged =
                            incumbents.FirstOrDefault(
                                row => row.RowState != DataRowState.Unchanged) != null;
                        if (incumbentsChanged)
                        {
                            OfficesOfficials.UpdateTable(incumbents);
                        }
                    }
                }

                // Update if any changes
                var winnersChanged =
                    table.FirstOrDefault(row => row.RowState != DataRowState.Unchanged) !=
                    null;

                if (winnersChanged)
                {
                    ElectionsPoliticians.UpdateTable(table,
                                                     ElectionsPoliticiansTable.ColumnSet.Winners);
                }

                LoadControl();
                return(winnersChanged);
            }
Esempio n. 25
0
            protected override bool Update(object newValue)
            {
                //Parse the value from the UI tree
                if (!(newValue is string valueStr))
                {
                    return(false);
                }
                var offices = valueStr.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                              .Select(officeStr =>
                {
                    var selected    = officeStr[0] == '*';
                    var officeSplit = officeStr.Substring(selected ? 1 : 0).Split('=');
                    var isRunoff    = officeSplit[1].StartsWith("*", StringComparison.Ordinal);
                    if (isRunoff)
                    {
                        officeSplit[1] = officeSplit[1].Substring(1);
                    }
                    return(new
                    {
                        Selected = selected,
                        OfficeKey = officeSplit[0],
                        IsRunoff = isRunoff,
                        Ids = officeSplit[1].Split(',')
                    });
                });

                var electionKey = Page.GetElectionKey();
                var table       = ElectionsPoliticians.GetWinnersData(electionKey);

                foreach (var o in offices)
                {
                    var office      = o;
                    var politicians = table
                                      .Where(row => row.OfficeKey().IsEqIgnoreCase(office.OfficeKey)).ToList();
                    foreach (var politician in politicians)
                    {
                        if (office.IsRunoff)
                        {
                            var advance = office.Ids.Contains(politician.PoliticianKey,
                                                              StringComparer.OrdinalIgnoreCase);
                            if (politician.AdvanceToRunoff != advance)
                            {
                                LogDataChange.LogUpdate(ElectionsPoliticians.Column.AdvanceToRunoff,
                                                        politician.AdvanceToRunoff, advance, DateTime.UtcNow, electionKey,
                                                        politician.OfficeKey, politician.PoliticianKey);
                            }
                            politician.AdvanceToRunoff = advance;
                            politician.IsWinner        = false;
                        }
                        else // non-runoff
                        {
                            var isWinner = office.Ids.Contains(politician.PoliticianKey,
                                                               StringComparer.OrdinalIgnoreCase);
                            if (politician.IsWinner != isWinner)
                            {
                                LogDataChange.LogUpdate(ElectionsPoliticians.Column.IsWinner,
                                                        politician.IsWinner, isWinner, DateTime.UtcNow, electionKey,
                                                        politician.OfficeKey, politician.PoliticianKey);
                            }
                            politician.IsWinner        = isWinner;
                            politician.AdvanceToRunoff = false;
                        }
                    }
                    if (office.Selected)
                    {
                        var keys = politicians.Select(p =>
                                                      (politicianKey: p.PoliticianKey, runningMateKey: p.RunningMateKey)).ToList();
                        OfficesOfficials.UpdateIncumbents(office.OfficeKey, office.Ids, keys, UserSecurityClass,
                                                          UserName);
                        //// Update incumbents
                        //var positions = Offices.GetPositionsDataByOfficeKey(office.OfficeKey)[0];
                        //var incumbents = OfficesOfficials.GetData(office.OfficeKey);
                        //var politicianKeysToAdd =
                        //  new List<string>(
                        //    office.Ids.Where(id => id != "vacant" && id != Empty));
                        //foreach (var incumbent in incumbents)
                        //{
                        //  var index =
                        //    politicianKeysToAdd.FindIndex(
                        //      key => key.IsEqIgnoreCase(incumbent.PoliticianKey));
                        //  if (index >= 0) politicianKeysToAdd.RemoveAt(index);
                        //  // we don't remove old incumbents for offices with
                        //  // Incumbents > ElectionPositions
                        //  else if (positions.ElectionPositions == positions.Incumbents)
                        //    incumbent.Delete();
                        //}
                        //foreach (var keyToAdd in politicianKeysToAdd)
                        //{
                        //  var politician =
                        //    politicians.FirstOrDefault(
                        //      row => row.PoliticianKey.IsEqIgnoreCase(keyToAdd));
                        //  var runningMateKey = politician == null
                        //    ? Empty
                        //    : politician.RunningMateKey;
                        //  incumbents.AddRow(office.OfficeKey, keyToAdd, runningMateKey,
                        //    Offices.GetStateCodeFromKey(office.OfficeKey),
                        //    Offices.GetCountyCodeFromKey(office.OfficeKey),
                        //    Offices.GetLocalKeyFromKey(office.OfficeKey), Empty, DateTime.UtcNow,
                        //    UserSecurityClass, UserName);
                        //  LogDataChange.LogInsert(OfficesOfficials.TableName, DateTime.UtcNow,
                        //    office.OfficeKey, keyToAdd);
                        //}

                        //// Update if any changes
                        //var incumbentsChanged =
                        //  incumbents.FirstOrDefault(row => row.RowState != DataRowState.Unchanged) !=
                        //  null;
                        //if (incumbentsChanged) OfficesOfficials.UpdateTable(incumbents);
                    }
                }

                // Update if any changes
                var winnersChanged =
                    table.FirstOrDefault(row => row.RowState != DataRowState.Unchanged) != null;

                if (winnersChanged)
                {
                    ElectionsPoliticians.UpdateTable(table,
                                                     ElectionsPoliticiansTable.ColumnSet.Winners);
                }

                LoadControl();
                return(winnersChanged);
            }
        private void DoConsolidation()
        {
            try
            {
                var    selectedIndex = ConsolidateSelectedIndex.Value;
                string selectedKey;
                string unselectedKey;
                switch (selectedIndex)
                {
                case "1":
                    selectedKey   = ConsolidateKey1.Value;
                    unselectedKey = ConsolidateKey2.Value;
                    break;

                case "2":
                    selectedKey   = ConsolidateKey2.Value;
                    unselectedKey = ConsolidateKey1.Value;
                    break;

                default:
                    throw new VoteException("Index not 1 or 2");
                }

                //throw new VoteException("An error");

                // Politicians
                var selectedPolitician   = Politicians.GetData(selectedKey);
                var unselectedPolitician = Politicians.GetData(unselectedKey);
                if (selectedPolitician.Count != 1)
                {
                    throw new VoteException("Politician " + selectedPolitician + " not found");
                }
                if (unselectedPolitician.Count != 1)
                {
                    throw new VoteException("Politician " + unselectedKey + " not found");
                }
                var selectedData = UpdatePoliticians(selectedIndex, selectedPolitician, unselectedPolitician);

                // PoliticiansImagesData and PoliticiansImagesBlobs
                var selectedImagesData    = PoliticiansImagesData.GetData(selectedKey);
                var unselectedImagesData  = PoliticiansImagesData.GetData(unselectedKey);
                var selectedImagesBlobs   = PoliticiansImagesBlobs.GetData(selectedKey);
                var unselectedImagesBlobs = PoliticiansImagesBlobs.GetData(unselectedKey);
                UpdateImages(selectedIndex, selectedData, selectedKey, selectedImagesData,
                             selectedImagesBlobs, unselectedImagesData, unselectedImagesBlobs);

                // Answers
                var selectedAnswers   = Answers.GetActiveDataByPoliticianKey(selectedKey);
                var unselectedAnswers = Answers.GetDataByPoliticianKey(unselectedKey);
                UpdateAnswers(selectedKey, selectedAnswers, unselectedAnswers);

                // ElectionsIncumbentsRemoved
                var selectedIncumbentsRemoved =
                    ElectionsIncumbentsRemoved.GetDataByPoliticianKey(selectedKey);
                var unselectedIncumbentsRemoved =
                    ElectionsIncumbentsRemoved.GetDataByPoliticianKey(unselectedKey);
                UpdateIncumbentsRemoved(selectedKey, unselectedIncumbentsRemoved, selectedIncumbentsRemoved);

                // ElectionsPoliticians
                var selectedElectionsPoliticians   = ElectionsPoliticians.GetDataByPoliticianKey(selectedKey);
                var unselectedElectionsPoliticians =
                    ElectionsPoliticians.GetDataByPoliticianKey(unselectedKey);
                UpdateElectionsPoliticians(selectedKey, unselectedElectionsPoliticians,
                                           selectedElectionsPoliticians);

                // OfficesOfficials
                var selectedOfficesOfficials   = OfficesOfficials.GetDataByPoliticianKey(selectedKey);
                var unselectedOfficesOfficials = OfficesOfficials.GetDataByPoliticianKey(unselectedKey);
                UpdateOfficesOfficials(selectedKey, unselectedOfficesOfficials, selectedOfficesOfficials);

                // Update everything as one transaction, politicians last
                PoliticiansImagesData.UpdateTable(selectedImagesData);
                PoliticiansImagesData.UpdateTable(unselectedImagesData);
                PoliticiansImagesBlobs.UpdateTable(selectedImagesBlobs);
                PoliticiansImagesBlobs.UpdateTable(unselectedImagesBlobs);
                Answers.UpdateTable(selectedAnswers);
                Answers.UpdateTable(unselectedAnswers);
                ElectionsIncumbentsRemoved.UpdateTable(unselectedIncumbentsRemoved);
                ElectionsPoliticians.UpdateTable(unselectedElectionsPoliticians);
                OfficesOfficials.UpdateTable(unselectedOfficesOfficials);
                Politicians.UpdateTable(selectedPolitician);
                Politicians.UpdateTable(unselectedPolitician);

                // Log
                LogDataChange.LogUpdate("*ConsolidatePoliticians", "*Various", unselectedKey, selectedKey,
                                        VotePage.UserName, SecurePage.UserSecurityClass, DateTime.UtcNow, selectedKey);

                // After the main update, refresh the LiveOfficeKey, LiveOfficeStatus and LiveElectionKey
                var view = PoliticiansLiveOfficeKeyView.GetData(selectedKey);
                if (view.Count == 1)
                {
                    var keyAndStatus =
                        PoliticianOfficeStatus.FromLiveOfficeKeyAndStatus(
                            view[0].LiveOfficeKeyAndStatus);
                    selectedPolitician[0].LiveOfficeKey    = keyAndStatus.OfficeKey;
                    selectedPolitician[0].LiveOfficeStatus = keyAndStatus.PoliticianStatus.ToString();
                    selectedPolitician[0].LiveElectionKey  = keyAndStatus.ElectionKey;
                    Politicians.UpdateTable(selectedPolitician);
                }
                ConsolidateReloaded.Value = "ok";
            }
            catch (Exception ex)
            {
                FeedbackConsolidate.AddError("There was an unexpected error: " + ex.Message);
            }
        }
Esempio n. 27
0
        protected void ButtonAddNewCandidate_OnClick(object sender, EventArgs e)
        {
            bool validateDuplicates;

            bool.TryParse(AddCandidateValidateDuplicates.GetValue(),
                          out validateDuplicates);

            AddCandidateDuplicatesHtml.Controls.Clear();
            _AddNewCandidateSubTabInfo.ClearValidationErrors();
            AddCandidateNewId.SetValue(string.Empty);

            // No actual updating here, just validation and reformatting
            _AddNewCandidateSubTabInfo.Update(FeedbackAddNewCandidate, false);
            if (FeedbackAddNewCandidate.ValidationErrorCount > 0)
            {
                return;
            }

            var stateCode  = ControlAddNewCandidateStateCode.GetValue();
            var firstName  = ControlAddNewCandidateFName.GetValue();
            var middleName = ControlAddNewCandidateMName.GetValue();
            var nickname   = ControlAddNewCandidateNickname.GetValue();
            var lastName   = ControlAddNewCandidateLName.GetValue();
            var suffix     = ControlAddNewCandidateSuffix.GetValue();

            var formattedName = Politicians.FormatName(firstName, middleName, nickname,
                                                       lastName, suffix);

            if (validateDuplicates)
            {
                var duplicatesHtml = Politicians.GetCandidateList(lastName, null, stateCode,
                                                                  null, true);
                AddCandidateDuplicatesHtml.Controls.Add(duplicatesHtml);
                if (duplicatesHtml.Controls.Count > 0)
                {
                    // Set up the duplicates dialog
                    AddCandidateFormattedName.SetValue(formattedName);
                    AddCandidateStateName.SetValue(StateCache.GetStateName(stateCode));
                    FeedbackAddNewCandidate.PostValidationError(ControlAddNewCandidateLName,
                                                                "Potential duplicate politician");
                    return;
                }
            }

            var newPoliticianKey = Politicians.GetUniqueKey(stateCode, lastName,
                                                            firstName, middleName, suffix);

            AddCandidateNewId.SetValue(newPoliticianKey);

            // If it's a primary, get the party key from the election
            //var partyKey = "X";
            var partyKey    = string.Empty; // mantis 508
            var electionKey = SafeGetElectionKey();

            if (Elections.IsPrimaryElection(electionKey))
            {
                partyKey = stateCode + Elections.GetNationalPartyCodeFromKey(electionKey);
            }

            Politicians.AddPolitician(newPoliticianKey, firstName, middleName, nickname,
                                      lastName, suffix, SafeGetOfficeKey(), partyKey, SecurePage.CreateUniquePassword());

            LogDataChange.LogInsert(Politicians.TableName, VotePage.UserName, SecurePage.UserSecurityClass,
                                    DateTime.UtcNow, newPoliticianKey);

            ClearAddNewCandidate();

            FeedbackAddNewCandidate.AddInfo("Politician " + formattedName + " was added.");
            if (Mode == DataMode.AddPoliticians)
            {
                FeedbackAddNewCandidate.AddInfo(new HtmlAnchor
                {
                    InnerText = "Intro Page",
                    HRef      = UrlManager.GetIntroPageUri(newPoliticianKey).ToString(),
                    Target    = "Politician"
                }.RenderToString());
                FeedbackAddNewCandidate.AddInfo(new HtmlAnchor
                {
                    InnerText = "Politician Admin Page",
                    HRef      = SecureAdminPage.GetPoliticianPageUrl(newPoliticianKey),
                    Target    = "Politician"
                }.RenderToString());
            }
        }
Esempio n. 28
0
 protected static void LogElectionsDataChange(string electionKey, string column,
                                              string oldValue, string newValue)
 {
     LogDataChange.LogUpdate(Elections.TableName, column, oldValue, newValue,
                             UserName, UserSecurityClass, DateTime.UtcNow, electionKey);
 }
 protected override void Log(string oldValue, string newValue) =>
 LogDataChange.LogUpdate(States.TableName, Column, oldValue, newValue,
                         UserName, UserSecurityClass, DateTime.UtcNow, Page.StateCode);
Esempio n. 30
0
 protected override void Log(string oldValue, string newValue) =>
 LogDataChange.LogUpdate(Offices.TableName, Column, oldValue, newValue,
                         UserName, UserSecurityClass, DateTime.UtcNow,
                         Page.GetOfficeKeyToEdit());