private IQueryable <Person> GetByFirstLastName(string firstName, string lastName, bool includeDeceased, bool includeBusinesses, RockContext rockContext, IQueryable <Person> people) { string fullname = !string.IsNullOrWhiteSpace(firstName) ? firstName + " " + lastName : lastName; var previousNamesQry = new PersonPreviousNameService(rockContext).Queryable(); var qry = people; if (includeBusinesses) { int recordTypeBusinessId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id; // if a we are including businesses, compare fullname against the Business Name (Person.LastName) qry = qry.Where(p => (p.RecordTypeValueId.HasValue && p.RecordTypeValueId.Value == recordTypeBusinessId && p.LastName.StartsWith(fullname)) || ((p.LastName.StartsWith(lastName) || previousNamesQry.Any(a => a.PersonAlias.PersonId == p.Id && a.LastName.StartsWith(lastName))) && (p.FirstName.StartsWith(firstName) || p.NickName.StartsWith(firstName)))); } else { qry = qry.Where(p => (p.LastName.StartsWith(lastName) || previousNamesQry.Any(a => a.PersonAlias.PersonId == p.Id && a.LastName.StartsWith(lastName))) && (p.FirstName.StartsWith(firstName) || p.NickName.StartsWith(firstName))); } return(qry); }
/// <summary> /// Loads the Person Previous Name data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadPersonPreviousName(CSVInstance csvData) { var lookupContext = new RockContext(); var importedPersonPreviousNames = new PersonPreviousNameService(lookupContext).Queryable().Count(p => p.ForeignKey != null); var personPreviousNames = new List <PersonPreviousName>(); var completedItems = 0; ReportProgress(0, string.Format("Verifying person previous name import ({0:N0} already imported).", importedPersonPreviousNames)); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { var previousPersonNameId = row[PreviousLastNameId] as string; var previousPersonName = row[PreviousLastName] as string; var previousPersonId = row[PreviousLastNamePersonId] as string; var personAliasKey = previousPersonId; var previousNamePersonKeys = GetPersonKeys(personAliasKey); if (previousNamePersonKeys != null) { var previousPersonAliasId = previousNamePersonKeys.PersonAliasId; var previousName = AddPersonPreviousName(lookupContext, previousPersonName, previousPersonAliasId, previousPersonNameId, false); if (previousName.Id == 0) { personPreviousNames.Add(previousName); } } completedItems++; if (completedItems % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} person previous names processed.", completedItems)); } if (completedItems % ReportingNumber < 1) { SavePersonPreviousNames(personPreviousNames); ReportPartialProgress(); personPreviousNames.Clear(); } } if (personPreviousNames.Any()) { SavePersonPreviousNames(personPreviousNames); } ReportProgress(100, string.Format("Finished person previous name import: {0:N0} previous names processed.", completedItems)); return(completedItems); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if (IsUserAuthorized(Rock.Security.Authorization.EDIT)) { var rockContext = new RockContext(); rockContext.WrapTransaction(() => { var personService = new PersonService(rockContext); var changes = new List <string>(); var person = personService.Get(Person.Id); int?orphanedPhotoId = null; if (person.PhotoId != imgPhoto.BinaryFileId) { orphanedPhotoId = person.PhotoId; person.PhotoId = imgPhoto.BinaryFileId; if (orphanedPhotoId.HasValue) { if (person.PhotoId.HasValue) { changes.Add("Modified the photo."); } else { changes.Add("Deleted the photo."); } } else if (person.PhotoId.HasValue) { changes.Add("Added a photo."); } } int?newTitleId = ddlTitle.SelectedValueAsInt(); History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(person.TitleValueId), DefinedValueCache.GetName(newTitleId)); person.TitleValueId = newTitleId; History.EvaluateChange(changes, "First Name", person.FirstName, tbFirstName.Text); person.FirstName = tbFirstName.Text; string nickName = string.IsNullOrWhiteSpace(tbNickName.Text) ? tbFirstName.Text : tbNickName.Text; History.EvaluateChange(changes, "Nick Name", person.NickName, nickName); person.NickName = tbNickName.Text; History.EvaluateChange(changes, "Middle Name", person.MiddleName, tbMiddleName.Text); person.MiddleName = tbMiddleName.Text; History.EvaluateChange(changes, "Last Name", person.LastName, tbLastName.Text); person.LastName = tbLastName.Text; int?newSuffixId = ddlSuffix.SelectedValueAsInt(); History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(person.SuffixValueId), DefinedValueCache.GetName(newSuffixId)); person.SuffixValueId = newSuffixId; var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; var birthday = bpBirthDay.SelectedDate; if (birthday.HasValue) { // If setting a future birthdate, subtract a century until birthdate is not greater than today. var today = RockDateTime.Today; while (birthday.Value.CompareTo(today) > 0) { birthday = birthday.Value.AddYears(-100); } person.BirthMonth = birthday.Value.Month; person.BirthDay = birthday.Value.Day; if (birthday.Value.Year != DateTime.MinValue.Year) { person.BirthYear = birthday.Value.Year; } else { person.BirthYear = null; } } else { person.SetBirthDate(null); } History.EvaluateChange(changes, "Birth Month", birthMonth, person.BirthMonth); History.EvaluateChange(changes, "Birth Day", birthDay, person.BirthDay); History.EvaluateChange(changes, "Birth Year", birthYear, person.BirthYear); int?graduationYear = null; if (ypGraduation.SelectedYear.HasValue) { graduationYear = ypGraduation.SelectedYear.Value; } History.EvaluateChange(changes, "Graduation Year", person.GraduationYear, graduationYear); person.GraduationYear = graduationYear; History.EvaluateChange(changes, "Anniversary Date", person.AnniversaryDate, dpAnniversaryDate.SelectedDate); person.AnniversaryDate = dpAnniversaryDate.SelectedDate; var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>(); History.EvaluateChange(changes, "Gender", person.Gender, newGender); person.Gender = newGender; int?newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId)); person.MaritalStatusValueId = newMaritalStatusId; int?newConnectionStatusId = ddlConnectionStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Connection Status", DefinedValueCache.GetName(person.ConnectionStatusValueId), DefinedValueCache.GetName(newConnectionStatusId)); person.ConnectionStatusValueId = newConnectionStatusId; var phoneNumberTypeIds = new List <int>(); bool smsSelected = false; foreach (RepeaterItem item in rContactInfo.Items) { HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField; PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl("cbUnlisted") as CheckBox; CheckBox cbSms = item.FindControl("cbSms") as CheckBox; if (hfPhoneType != null && pnbPhone != null && cbSms != null && cbUnlisted != null) { if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))) { int phoneNumberTypeId; if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId)) { var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId); string oldPhoneNumber = string.Empty; if (phoneNumber == null) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId }; person.PhoneNumbers.Add(phoneNumber); } else { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode); phoneNumber.Number = PhoneNumber.CleanNumber(pnbPhone.Number); // Only allow one number to have SMS selected if (smsSelected) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add(phoneNumberTypeId); History.EvaluateChange( changes, string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumberTypeId)), oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode); } } } } // Remove any blank numbers var phoneNumberService = new PhoneNumberService(rockContext); foreach (var phoneNumber in person.PhoneNumbers .Where(n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains(n.NumberTypeValueId.Value)) .ToList()) { History.EvaluateChange( changes, string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)), phoneNumber.ToString(), string.Empty); person.PhoneNumbers.Remove(phoneNumber); phoneNumberService.Delete(phoneNumber); } History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text); person.Email = tbEmail.Text.Trim(); History.EvaluateChange(changes, "Email Active", person.IsEmailActive, cbIsEmailActive.Checked); person.IsEmailActive = cbIsEmailActive.Checked; var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>(); History.EvaluateChange(changes, "Email Preference", person.EmailPreference, newEmailPreference); person.EmailPreference = newEmailPreference; int?newGivingGroupId = ddlGivingGroup.SelectedValueAsId(); if (person.GivingGroupId != newGivingGroupId) { string oldGivingGroupName = string.Empty; if (Person.GivingGroup != null) { oldGivingGroupName = GetFamilyNameWithFirstNames(Person.GivingGroup.Name, Person.GivingGroup.Members); } string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue(newGivingGroupId.Value.ToString()).Text : string.Empty; History.EvaluateChange(changes, "Giving Group", oldGivingGroupName, newGivingGroupName); } person.GivingGroupId = newGivingGroupId; int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(person.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId)); person.RecordStatusValueId = newRecordStatusId; int?newRecordStatusReasonId = null; if (person.RecordStatusValueId.HasValue && person.RecordStatusValueId.Value == DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id) { newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); } History.EvaluateChange(changes, "Inactive Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId)); person.RecordStatusReasonValueId = newRecordStatusReasonId; History.EvaluateChange(changes, "Inactive Reason Note", person.InactiveReasonNote, tbInactiveReasonNote.Text); person.InactiveReasonNote = tbInactiveReasonNote.Text.Trim(); // Save any Removed/Added Previous Names var personPreviousNameService = new PersonPreviousNameService(rockContext); var databasePreviousNames = personPreviousNameService.Queryable().Where(a => a.PersonAlias.PersonId == person.Id).ToList(); foreach (var deletedPreviousName in databasePreviousNames.Where(a => !PersonPreviousNamesState.Any(p => p.Guid == a.Guid))) { personPreviousNameService.Delete(deletedPreviousName); History.EvaluateChange( changes, "Previous Name", deletedPreviousName.ToString(), string.Empty); } foreach (var addedPreviousName in PersonPreviousNamesState.Where(a => !databasePreviousNames.Any(d => d.Guid == a.Guid))) { addedPreviousName.PersonAliasId = person.PrimaryAliasId.Value; personPreviousNameService.Add(addedPreviousName); History.EvaluateChange( changes, "Previous Name", string.Empty, addedPreviousName.ToString()); } if (person.IsValid) { if (rockContext.SaveChanges() > 0) { if (changes.Any()) { HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), Person.Id, changes); } if (orphanedPhotoId.HasValue) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(orphanedPhotoId.Value); if (binaryFile != null) { string errorMessage; if (binaryFileService.CanDelete(binaryFile, out errorMessage)) { binaryFileService.Delete(binaryFile); rockContext.SaveChanges(); } } } // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up if (imgPhoto.CropBinaryFileId.HasValue) { if (imgPhoto.CropBinaryFileId != person.PhotoId) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value); if (binaryFile != null && binaryFile.IsTemporary) { string errorMessage; if (binaryFileService.CanDelete(binaryFile, out errorMessage)) { binaryFileService.Delete(binaryFile); rockContext.SaveChanges(); } } } } } Response.Redirect(string.Format("~/Person/{0}", Person.Id), false); } }); } }
/// <summary> /// Deletes the family's addresses, phone numbers, photos, viewed records, and people. /// TODO: delete attendance codes for attendance data that's about to be deleted when /// we delete the person record. /// </summary> /// <param name="families">The families.</param> /// <param name="rockContext">The rock context.</param> private void DeleteExistingFamilyData( XElement families, RockContext rockContext ) { PersonService personService = new PersonService( rockContext ); PhoneNumberService phoneNumberService = new PhoneNumberService( rockContext ); PersonViewedService personViewedService = new PersonViewedService( rockContext ); PageViewService pageViewService = new PageViewService( rockContext ); BinaryFileService binaryFileService = new BinaryFileService( rockContext ); PersonAliasService personAliasService = new PersonAliasService( rockContext ); PersonDuplicateService personDuplicateService = new PersonDuplicateService( rockContext ); NoteService noteService = new NoteService( rockContext ); AuthService authService = new AuthService( rockContext ); CommunicationService communicationService = new CommunicationService( rockContext ); CommunicationRecipientService communicationRecipientService = new CommunicationRecipientService( rockContext ); FinancialBatchService financialBatchService = new FinancialBatchService( rockContext ); FinancialTransactionService financialTransactionService = new FinancialTransactionService( rockContext ); PersonPreviousNameService personPreviousNameService = new PersonPreviousNameService( rockContext ); ConnectionRequestService connectionRequestService = new ConnectionRequestService( rockContext ); ConnectionRequestActivityService connectionRequestActivityService = new ConnectionRequestActivityService( rockContext ); // delete the batch data List<int> imageIds = new List<int>(); foreach ( var batch in financialBatchService.Queryable().Where( b => b.Name.StartsWith( "SampleData" ) ) ) { imageIds.AddRange( batch.Transactions.SelectMany( t => t.Images ).Select( i => i.BinaryFileId ).ToList() ); financialTransactionService.DeleteRange( batch.Transactions ); financialBatchService.Delete( batch ); } // delete all transaction images foreach ( var image in binaryFileService.GetByIds( imageIds ) ) { binaryFileService.Delete( image ); } foreach ( var elemFamily in families.Elements( "family" ) ) { Guid guid = elemFamily.Attribute( "guid" ).Value.Trim().AsGuid(); GroupService groupService = new GroupService( rockContext ); Group family = groupService.Get( guid ); if ( family != null ) { var groupMemberService = new GroupMemberService( rockContext ); var members = groupMemberService.GetByGroupId( family.Id, true ); // delete the people records string errorMessage; List<int> photoIds = members.Select( m => m.Person ).Where( p => p.PhotoId != null ).Select( a => (int)a.PhotoId ).ToList(); foreach ( var person in members.Select( m => m.Person ) ) { person.GivingGroup = null; person.GivingGroupId = null; person.PhotoId = null; // delete phone numbers foreach ( var phone in phoneNumberService.GetByPersonId( person.Id ) ) { if ( phone != null ) { phoneNumberService.Delete( phone ); } } // delete communication recipient foreach ( var recipient in communicationRecipientService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id ) ) { communicationRecipientService.Delete( recipient ); } // delete communication foreach ( var communication in communicationService.Queryable().Where( c => c.SenderPersonAliasId == person.PrimaryAlias.Id ) ) { communicationService.Delete( communication ); } // delete person viewed records foreach ( var view in personViewedService.GetByTargetPersonId( person.Id ) ) { personViewedService.Delete( view ); } // delete page viewed records foreach ( var view in pageViewService.GetByPersonId( person.Id ) ) { pageViewService.Delete( view ); } // delete notes created by them or on their record. foreach ( var note in noteService.Queryable().Where ( n => n.CreatedByPersonAlias.PersonId == person.Id || (n.NoteType.EntityTypeId == _personEntityTypeId && n.EntityId == person.Id ) ) ) { noteService.Delete( note ); } // delete previous names on their records foreach ( var previousName in personPreviousNameService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id ) ) { personPreviousNameService.Delete( previousName ); } // delete any GroupMember records they have foreach ( var groupMember in groupMemberService.Queryable().Where( gm => gm.PersonId == person.Id ) ) { groupMemberService.Delete( groupMember ); } //// delete any Authorization data //foreach ( var auth in authService.Queryable().Where( a => a.PersonId == person.Id ) ) //{ // authService.Delete( auth ); //} // delete their aliases foreach ( var alias in personAliasService.Queryable().Where( a => a.PersonId == person.Id ) ) { foreach ( var duplicate in personDuplicateService.Queryable().Where( d => d.DuplicatePersonAliasId == alias.Id ) ) { personDuplicateService.Delete( duplicate ); } personAliasService.Delete( alias ); } // delete any connection requests tied to them foreach ( var request in connectionRequestService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id || r.ConnectorPersonAlias.PersonId == person.Id ) ) { connectionRequestActivityService.DeleteRange( request.ConnectionRequestActivities ); connectionRequestService.Delete( request ); } // Save these changes so the CanDelete passes the check... //rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( disablePrePostProcessing: true ); if ( personService.CanDelete( person, out errorMessage ) ) { personService.Delete( person ); //rockContext.ChangeTracker.DetectChanges(); //rockContext.SaveChanges( disablePrePostProcessing: true ); } else { throw new Exception( string.Format( "Trying to delete {0}, but: {1}", person.FullName, errorMessage ) ); } } //rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( disablePrePostProcessing: true ); // delete all member photos foreach ( var photo in binaryFileService.GetByIds( photoIds ) ) { binaryFileService.Delete( photo ); } DeleteGroupAndMemberData( family, rockContext ); } } }
/// <summary> /// Adds the name of the previous. /// </summary> /// <param name="personAliasId">The person alias identifier.</param> /// <param name="previousLastName">Last name of the previous.</param> /// <param name="rockContext">The rock context.</param> private void AddPreviousName( int personAliasId, string previousLastName, RockContext rockContext ) { var personPreviousNameService = new PersonPreviousNameService( rockContext ); var previousName = new PersonPreviousName() { LastName = previousLastName, PersonAliasId = personAliasId }; personPreviousNameService.Add( previousName ); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { if ( IsUserAuthorized( Rock.Security.Authorization.EDIT ) ) { var rockContext = new RockContext(); rockContext.WrapTransaction( () => { var personService = new PersonService( rockContext ); var changes = new List<string>(); var person = personService.Get( Person.Id ); int? orphanedPhotoId = null; if ( person.PhotoId != imgPhoto.BinaryFileId ) { orphanedPhotoId = person.PhotoId; person.PhotoId = imgPhoto.BinaryFileId; if ( orphanedPhotoId.HasValue ) { if ( person.PhotoId.HasValue ) { changes.Add( "Modified the photo." ); } else { changes.Add( "Deleted the photo." ); } } else if ( person.PhotoId.HasValue ) { changes.Add( "Added a photo." ); } } int? newTitleId = ddlTitle.SelectedValueAsInt(); History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) ); person.TitleValueId = newTitleId; History.EvaluateChange( changes, "First Name", person.FirstName, tbFirstName.Text ); person.FirstName = tbFirstName.Text; string nickName = string.IsNullOrWhiteSpace( tbNickName.Text ) ? tbFirstName.Text : tbNickName.Text; History.EvaluateChange( changes, "Nick Name", person.NickName, nickName ); person.NickName = tbNickName.Text; History.EvaluateChange( changes, "Middle Name", person.MiddleName, tbMiddleName.Text ); person.MiddleName = tbMiddleName.Text; History.EvaluateChange( changes, "Last Name", person.LastName, tbLastName.Text ); person.LastName = tbLastName.Text; int? newSuffixId = ddlSuffix.SelectedValueAsInt(); History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) ); person.SuffixValueId = newSuffixId; var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; var birthday = bpBirthDay.SelectedDate; if ( birthday.HasValue ) { // If setting a future birthdate, subtract a century until birthdate is not greater than today. var today = RockDateTime.Today; while ( birthday.Value.CompareTo( today ) > 0 ) { birthday = birthday.Value.AddYears( -100 ); } person.BirthMonth = birthday.Value.Month; person.BirthDay = birthday.Value.Day; if ( birthday.Value.Year != DateTime.MinValue.Year ) { person.BirthYear = birthday.Value.Year; } else { person.BirthYear = null; } } else { person.SetBirthDate( null ); } History.EvaluateChange( changes, "Birth Month", birthMonth, person.BirthMonth ); History.EvaluateChange( changes, "Birth Day", birthDay, person.BirthDay ); History.EvaluateChange( changes, "Birth Year", birthYear, person.BirthYear ); int? graduationYear = null; if ( ypGraduation.SelectedYear.HasValue ) { graduationYear = ypGraduation.SelectedYear.Value; } History.EvaluateChange( changes, "Graduation Year", person.GraduationYear, graduationYear ); person.GraduationYear = graduationYear; History.EvaluateChange( changes, "Anniversary Date", person.AnniversaryDate, dpAnniversaryDate.SelectedDate ); person.AnniversaryDate = dpAnniversaryDate.SelectedDate; var newGender = rblGender.SelectedValue.ConvertToEnum<Gender>(); History.EvaluateChange( changes, "Gender", person.Gender, newGender ); person.Gender = newGender; int? newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt(); History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) ); person.MaritalStatusValueId = newMaritalStatusId; int? newConnectionStatusId = ddlConnectionStatus.SelectedValueAsInt(); History.EvaluateChange( changes, "Connection Status", DefinedValueCache.GetName( person.ConnectionStatusValueId ), DefinedValueCache.GetName( newConnectionStatusId ) ); person.ConnectionStatusValueId = newConnectionStatusId; var phoneNumberTypeIds = new List<int>(); bool smsSelected = false; foreach ( RepeaterItem item in rContactInfo.Items ) { HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField; PhoneNumberBox pnbPhone = item.FindControl( "pnbPhone" ) as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl( "cbUnlisted" ) as CheckBox; CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox; if ( hfPhoneType != null && pnbPhone != null && cbSms != null && cbUnlisted != null ) { if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) ) { int phoneNumberTypeId; if ( int.TryParse( hfPhoneType.Value, out phoneNumberTypeId ) ) { var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberTypeId ); string oldPhoneNumber = string.Empty; if ( phoneNumber == null ) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId }; person.PhoneNumbers.Add( phoneNumber ); } else { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); // Only allow one number to have SMS selected if ( smsSelected ) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add( phoneNumberTypeId ); History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumberTypeId ) ), oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode ); } } } } // Remove any blank numbers var phoneNumberService = new PhoneNumberService( rockContext ); foreach ( var phoneNumber in person.PhoneNumbers .Where( n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains( n.NumberTypeValueId.Value ) ) .ToList() ) { History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumber.NumberTypeValueId ) ), phoneNumber.ToString(), string.Empty ); person.PhoneNumbers.Remove( phoneNumber ); phoneNumberService.Delete( phoneNumber ); } History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text ); person.Email = tbEmail.Text.Trim(); History.EvaluateChange( changes, "Email Active", person.IsEmailActive, cbIsEmailActive.Checked ); person.IsEmailActive = cbIsEmailActive.Checked; var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>(); History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference ); person.EmailPreference = newEmailPreference; int? newGivingGroupId = ddlGivingGroup.SelectedValueAsId(); if ( person.GivingGroupId != newGivingGroupId ) { string oldGivingGroupName = string.Empty; if ( Person.GivingGroup != null ) { oldGivingGroupName = GetFamilyNameWithFirstNames( Person.GivingGroup.Name, Person.GivingGroup.Members ); } string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue( newGivingGroupId.Value.ToString() ).Text : string.Empty; History.EvaluateChange( changes, "Giving Group", oldGivingGroupName, newGivingGroupName ); } person.GivingGroupId = newGivingGroupId; int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt(); History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( person.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) ); person.RecordStatusValueId = newRecordStatusId; int? newRecordStatusReasonId = null; if ( person.RecordStatusValueId.HasValue && person.RecordStatusValueId.Value == DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id ) { newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); } History.EvaluateChange( changes, "Inactive Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( newRecordStatusReasonId ) ); person.RecordStatusReasonValueId = newRecordStatusReasonId; History.EvaluateChange( changes, "Inactive Reason Note", person.InactiveReasonNote, tbInactiveReasonNote.Text ); person.InactiveReasonNote = tbInactiveReasonNote.Text.Trim(); // Save any Removed/Added Previous Names var personPreviousNameService = new PersonPreviousNameService( rockContext ); var databasePreviousNames = personPreviousNameService.Queryable().Where( a => a.PersonAlias.PersonId == person.Id ).ToList(); foreach ( var deletedPreviousName in databasePreviousNames.Where( a => !PersonPreviousNamesState.Any( p => p.Guid == a.Guid ) ) ) { personPreviousNameService.Delete( deletedPreviousName ); History.EvaluateChange( changes, "Previous Name", deletedPreviousName.ToString(), string.Empty ); } foreach ( var addedPreviousName in PersonPreviousNamesState.Where( a => !databasePreviousNames.Any( d => d.Guid == a.Guid ) ) ) { addedPreviousName.PersonAliasId = person.PrimaryAliasId.Value; personPreviousNameService.Add( addedPreviousName ); History.EvaluateChange( changes, "Previous Name", string.Empty, addedPreviousName.ToString() ); } if ( person.IsValid ) { if ( rockContext.SaveChanges() > 0 ) { if ( changes.Any() ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), Person.Id, changes ); } if ( orphanedPhotoId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( orphanedPhotoId.Value ); if ( binaryFile != null ) { string errorMessage; if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) ) { binaryFileService.Delete( binaryFile ); rockContext.SaveChanges(); } } } // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up if ( imgPhoto.CropBinaryFileId.HasValue ) { if ( imgPhoto.CropBinaryFileId != person.PhotoId ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( imgPhoto.CropBinaryFileId.Value ); if ( binaryFile != null && binaryFile.IsTemporary ) { string errorMessage; if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) ) { binaryFileService.Delete( binaryFile ); rockContext.SaveChanges(); } } } } } Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false ); } } ); } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if (IsUserAuthorized(Rock.Security.Authorization.EDIT)) { var rockContext = new RockContext(); rockContext.WrapTransaction(() => { var personService = new PersonService(rockContext); var changes = new List <string>(); var person = personService.Get(Person.Id); int?orphanedPhotoId = null; if (person.PhotoId != imgPhoto.BinaryFileId) { orphanedPhotoId = person.PhotoId; person.PhotoId = imgPhoto.BinaryFileId; if (orphanedPhotoId.HasValue) { if (person.PhotoId.HasValue) { changes.Add("Modified the photo."); } else { changes.Add("Deleted the photo."); } } else if (person.PhotoId.HasValue) { changes.Add("Added a photo."); } } int?newTitleId = ddlTitle.SelectedValueAsInt(); History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(person.TitleValueId), DefinedValueCache.GetName(newTitleId)); person.TitleValueId = newTitleId; History.EvaluateChange(changes, "First Name", person.FirstName, tbFirstName.Text); person.FirstName = tbFirstName.Text; string nickName = string.IsNullOrWhiteSpace(tbNickName.Text) ? tbFirstName.Text : tbNickName.Text; History.EvaluateChange(changes, "Nick Name", person.NickName, nickName); person.NickName = tbNickName.Text; History.EvaluateChange(changes, "Middle Name", person.MiddleName, tbMiddleName.Text); person.MiddleName = tbMiddleName.Text; History.EvaluateChange(changes, "Last Name", person.LastName, tbLastName.Text); person.LastName = tbLastName.Text; int?newSuffixId = ddlSuffix.SelectedValueAsInt(); History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(person.SuffixValueId), DefinedValueCache.GetName(newSuffixId)); person.SuffixValueId = newSuffixId; var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; var birthday = bpBirthDay.SelectedDate; if (birthday.HasValue) { person.BirthMonth = birthday.Value.Month; person.BirthDay = birthday.Value.Day; if (birthday.Value.Year != DateTime.MinValue.Year) { person.BirthYear = birthday.Value.Year; } else { person.BirthYear = null; } } else { person.SetBirthDate(null); } History.EvaluateChange(changes, "Birth Month", birthMonth, person.BirthMonth); History.EvaluateChange(changes, "Birth Day", birthDay, person.BirthDay); History.EvaluateChange(changes, "Birth Year", birthYear, person.BirthYear); int?graduationYear = null; if (ypGraduation.SelectedYear.HasValue) { graduationYear = ypGraduation.SelectedYear.Value; } History.EvaluateChange(changes, "Graduation Year", person.GraduationYear, graduationYear); person.GraduationYear = graduationYear; History.EvaluateChange(changes, "Anniversary Date", person.AnniversaryDate, dpAnniversaryDate.SelectedDate); person.AnniversaryDate = dpAnniversaryDate.SelectedDate; var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>(); History.EvaluateChange(changes, "Gender", person.Gender, newGender); person.Gender = newGender; int?newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId)); person.MaritalStatusValueId = newMaritalStatusId; int?newConnectionStatusId = ddlConnectionStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Connection Status", DefinedValueCache.GetName(person.ConnectionStatusValueId), DefinedValueCache.GetName(newConnectionStatusId)); person.ConnectionStatusValueId = newConnectionStatusId; var phoneNumberTypeIds = new List <int>(); bool smsSelected = false; foreach (RepeaterItem item in rContactInfo.Items) { HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField; PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl("cbUnlisted") as CheckBox; CheckBox cbSms = item.FindControl("cbSms") as CheckBox; if (hfPhoneType != null && pnbPhone != null && cbSms != null && cbUnlisted != null) { if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))) { int phoneNumberTypeId; if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId)) { var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId); string oldPhoneNumber = string.Empty; if (phoneNumber == null) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId }; person.PhoneNumbers.Add(phoneNumber); } else { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode); phoneNumber.Number = PhoneNumber.CleanNumber(pnbPhone.Number); // Only allow one number to have SMS selected if (smsSelected) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add(phoneNumberTypeId); History.EvaluateChange( changes, string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumberTypeId)), oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode); } } } } // Remove any blank numbers var phoneNumberService = new PhoneNumberService(rockContext); foreach (var phoneNumber in person.PhoneNumbers .Where(n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains(n.NumberTypeValueId.Value)) .ToList()) { History.EvaluateChange( changes, string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)), phoneNumber.ToString(), string.Empty); person.PhoneNumbers.Remove(phoneNumber); phoneNumberService.Delete(phoneNumber); } History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text); person.Email = tbEmail.Text.Trim(); History.EvaluateChange(changes, "Email Active", person.IsEmailActive, cbIsEmailActive.Checked); person.IsEmailActive = cbIsEmailActive.Checked; var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>(); History.EvaluateChange(changes, "Email Preference", person.EmailPreference, newEmailPreference); person.EmailPreference = newEmailPreference; var newCommunicationPreference = rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>(); History.EvaluateChange(changes, "Communication Preference", person.CommunicationPreference, newCommunicationPreference); person.CommunicationPreference = newCommunicationPreference; int?newGivingGroupId = ddlGivingGroup.SelectedValueAsId(); if (person.GivingGroupId != newGivingGroupId) { string oldGivingGroupName = string.Empty; if (Person.GivingGroup != null) { oldGivingGroupName = GetFamilyNameWithFirstNames(Person.GivingGroup.Name, Person.GivingGroup.Members); } string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue(newGivingGroupId.Value.ToString()).Text : string.Empty; History.EvaluateChange(changes, "Giving Group", oldGivingGroupName, newGivingGroupName); } // Save the Envelope Number attribute if it exists and has changed var personGivingEnvelopeAttribute = AttributeCache.Read(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid()); if (GlobalAttributesCache.Read().EnableGivingEnvelopeNumber&& personGivingEnvelopeAttribute != null) { if (person.Attributes == null) { person.LoadAttributes(rockContext); } var newEnvelopeNumber = tbGivingEnvelopeNumber.Text; var oldEnvelopeNumber = person.GetAttributeValue(personGivingEnvelopeAttribute.Key); if (newEnvelopeNumber != oldEnvelopeNumber) { // If they haven't already comfirmed about duplicate, see if the envelope number if assigned to somebody else if (!string.IsNullOrWhiteSpace(newEnvelopeNumber) && hfGivingEnvelopeNumberConfirmed.Value != newEnvelopeNumber) { var otherPersonIdsWithEnvelopeNumber = new AttributeValueService(rockContext).Queryable() .Where(a => a.AttributeId == personGivingEnvelopeAttribute.Id && a.Value == newEnvelopeNumber && a.EntityId != person.Id) .Select(a => a.EntityId); if (otherPersonIdsWithEnvelopeNumber.Any()) { var personList = new PersonService(rockContext).Queryable().Where(a => otherPersonIdsWithEnvelopeNumber.Contains(a.Id)).AsNoTracking().ToList(); string personListMessage = personList.Select(a => a.FullName).ToList().AsDelimited(", ", " and "); int maxCount = 5; if (personList.Count > maxCount) { var otherCount = personList.Count() - maxCount; personListMessage = personList.Select(a => a.FullName).Take(10).ToList().AsDelimited(", ") + " and " + otherCount.ToString() + " other " + "person".PluralizeIf(otherCount > 1); } string givingEnvelopeWarningText = string.Format( "The envelope #{0} is already assigned to {1}. Do you want to also assign this number to {2}?", newEnvelopeNumber, personListMessage, person.FullName); string givingEnvelopeWarningScriptFormat = @" Rock.dialogs.confirm('{0}', function (result) {{ if ( result ) {{ $('#{1}').val('{2}'); }} }})"; string givingEnvelopeWarningScript = string.Format( givingEnvelopeWarningScriptFormat, givingEnvelopeWarningText, hfGivingEnvelopeNumberConfirmed.ClientID, newEnvelopeNumber); ScriptManager.RegisterStartupScript(hfGivingEnvelopeNumberConfirmed, hfGivingEnvelopeNumberConfirmed.GetType(), "confirm-envelope-number", givingEnvelopeWarningScript, true); return; } } History.EvaluateChange(changes, "Giving Envelope Number", oldEnvelopeNumber, newEnvelopeNumber); person.SetAttributeValue(personGivingEnvelopeAttribute.Key, newEnvelopeNumber); } } person.GivingGroupId = newGivingGroupId; bool recordStatusChangedToOrFromInactive = false; var recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id; int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt(); // Is the person's record status changing? if (person.RecordStatusValueId.HasValue && person.RecordStatusValueId != newRecordStatusId) { // If it was inactive OR if the new status is inactive, flag this for use later below. if (person.RecordStatusValueId == recordStatusInactiveId || newRecordStatusId == recordStatusInactiveId) { recordStatusChangedToOrFromInactive = true; } } History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(person.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId)); person.RecordStatusValueId = newRecordStatusId; int?newRecordStatusReasonId = null; if (person.RecordStatusValueId.HasValue && person.RecordStatusValueId.Value == recordStatusInactiveId) { newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); } History.EvaluateChange(changes, "Inactive Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId)); person.RecordStatusReasonValueId = newRecordStatusReasonId; History.EvaluateChange(changes, "Inactive Reason Note", person.InactiveReasonNote, tbInactiveReasonNote.Text); person.InactiveReasonNote = tbInactiveReasonNote.Text.Trim(); // Save any Removed/Added Previous Names var personPreviousNameService = new PersonPreviousNameService(rockContext); var databasePreviousNames = personPreviousNameService.Queryable().Where(a => a.PersonAlias.PersonId == person.Id).ToList(); foreach (var deletedPreviousName in databasePreviousNames.Where(a => !PersonPreviousNamesState.Any(p => p.Guid == a.Guid))) { personPreviousNameService.Delete(deletedPreviousName); History.EvaluateChange( changes, "Previous Name", deletedPreviousName.ToString(), string.Empty); } foreach (var addedPreviousName in PersonPreviousNamesState.Where(a => !databasePreviousNames.Any(d => d.Guid == a.Guid))) { addedPreviousName.PersonAliasId = person.PrimaryAliasId.Value; personPreviousNameService.Add(addedPreviousName); History.EvaluateChange( changes, "Previous Name", string.Empty, addedPreviousName.ToString()); } if (person.IsValid) { var saveChangeResult = rockContext.SaveChanges(); // if AttributeValues where loaded and set (for example Giving Envelope Number), Save Attribute Values if (person.AttributeValues != null) { person.SaveAttributeValues(rockContext); } if (saveChangeResult > 0) { if (changes.Any()) { HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), Person.Id, changes); } if (orphanedPhotoId.HasValue) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(orphanedPhotoId.Value); if (binaryFile != null) { string errorMessage; if (binaryFileService.CanDelete(binaryFile, out errorMessage)) { binaryFileService.Delete(binaryFile); rockContext.SaveChanges(); } } } // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up if (imgPhoto.CropBinaryFileId.HasValue) { if (imgPhoto.CropBinaryFileId != person.PhotoId) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value); if (binaryFile != null && binaryFile.IsTemporary) { string errorMessage; if (binaryFileService.CanDelete(binaryFile, out errorMessage)) { binaryFileService.Delete(binaryFile); rockContext.SaveChanges(); } } } } // If the person's record status was changed to or from inactive, // we need to check if any of their families need to be activated or inactivated. if (recordStatusChangedToOrFromInactive) { foreach (var family in personService.GetFamilies(person.Id)) { // Are there any more members of the family who are NOT inactive? // If not, mark the whole family inactive. if (!family.Members.Where(m => m.Person.RecordStatusValueId != recordStatusInactiveId).Any()) { family.IsActive = false; } else { family.IsActive = true; } } rockContext.SaveChanges(); } } Response.Redirect(string.Format("~/Person/{0}", Person.Id), false); } }); } }
private IQueryable <Person> GetByFullName(string fullName, bool includeDeceased, bool includeBusinesses, bool allowFirstNameOnly, out bool reversed) { var rockContext = new RockContext(); var personService = new PersonService(rockContext); var allowedPersons = Utils.LineQuery.GetPeopleInLineFollowUps(personService, GetPerson(), rockContext, true); var firstNames = new List <string>(); var lastNames = new List <string>(); string singleName = string.Empty; fullName = fullName.Trim(); var nameParts = fullName.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (fullName.Contains(',')) { reversed = true; // only split by comma if there is a comma present (for example if 'Smith Jones, Sally' is the search, last name would be 'Smith Jones') nameParts = fullName.Split(',').ToList(); if (nameParts.Count >= 1) { lastNames.Add(nameParts[0].Trim()); } if (nameParts.Count >= 2) { firstNames.Add(nameParts[1].Trim()); } } else if (fullName.Contains(' ')) { reversed = false; for (int i = 1; i < nameParts.Count; i++) { firstNames.Add(nameParts.Take(i).ToList().AsDelimited(" ")); lastNames.Add(nameParts.Skip(i).ToList().AsDelimited(" ")); } } else { // no spaces, no commas reversed = true; singleName = fullName; } if (!string.IsNullOrWhiteSpace(singleName)) { int?personId = singleName.AsIntegerOrNull(); if (personId.HasValue) { return(allowedPersons .Where(p => p.Aliases.Any(a => a.AliasPersonId == personId.Value))); } Guid?personGuid = singleName.AsGuidOrNull(); if (personGuid.HasValue) { return(allowedPersons .Where(p => p.Aliases.Any(a => a.AliasPersonGuid == personGuid.Value))); } var previousNamesQry = new PersonPreviousNameService(rockContext).Queryable(); if (allowFirstNameOnly) { return(allowedPersons .Where(p => p.LastName.StartsWith(singleName) || p.FirstName.StartsWith(singleName) || p.NickName.StartsWith(singleName) || previousNamesQry.Any(a => a.PersonAlias.PersonId == p.Id && a.LastName.StartsWith(singleName)))); } return(allowedPersons .Where(p => p.LastName.StartsWith(singleName) || previousNamesQry.Any(a => a.PersonAlias.PersonId == p.Id && a.LastName.StartsWith(singleName)))); } if (firstNames.Any() && lastNames.Any()) { var qry = GetByFirstLastName(firstNames.Any() ? firstNames[0] : "", lastNames.Any() ? lastNames[0] : "", includeDeceased, includeBusinesses, rockContext, allowedPersons); for (var i = 1; i < firstNames.Count; i++) { qry = qry.Union(GetByFirstLastName(firstNames[i], lastNames[i], includeDeceased, includeBusinesses, rockContext, allowedPersons)); } // always include a search for just last name using the last two parts of name search if (nameParts.Count >= 2) { var lastName = string.Join(" ", nameParts.TakeLast(2)); qry = qry.Union(GetByLastName(lastName, includeDeceased, includeBusinesses, allowedPersons)); } return(qry); } // Blank string was used, return empty list return(new List <Person>().AsQueryable()); }
/// <summary> /// Returns a queryable collection of <see cref="Rock.Model.Person"/> entities by the person's full name. /// </summary> /// <param name="fullName">A <see cref="System.String"/> representing the full name to search by.</param> /// <param name="includeDeceased">A <see cref="System.Boolean"/> flag indicating if deceased individuals should be included in search results, if <c>true</c> then they will be /// included, otherwise <c>false</c>.</param> /// <param name="includeBusinesses">if set to <c>true</c> [include businesses].</param> /// <param name="allowFirstNameOnly">if set to true, a single value in fullName will also search for matching first names.</param> /// <param name="reversed">if set to <c>true</c> [reversed].</param> /// <returns> /// A queryable collection of <see cref="Rock.Model.Person"/> entities that match the search criteria. /// </returns> public IQueryable<Person> GetByFullName( string fullName, bool includeDeceased, bool includeBusinesses, bool allowFirstNameOnly, out bool reversed ) { string firstName = string.Empty; string lastName = string.Empty; string singleName = string.Empty; if ( fullName.Contains( ',' ) ) { reversed = true; // only split by comma if there is a comma present (for example if 'Smith Jones, Sally' is the search, last name would be 'Smith Jones') var nameParts = fullName.Split( ',' ); lastName = nameParts.Length >= 1 ? nameParts[0].Trim() : string.Empty; firstName = nameParts.Length >= 2 ? nameParts[1].Trim() : string.Empty; } else if ( fullName.Trim().Contains( ' ' ) ) { reversed = false; // if no comma, assume the search is in 'firstname lastname' format (note: 'firstname lastname1 lastname2' isn't supported yet) var names = fullName.Split( ' ' ); firstName = names.Length >= 1 ? names[0].Trim() : string.Empty; lastName = names.Length >= 2 ? names[1].Trim() : string.Empty; } else { // no spaces, no commas reversed = true; singleName = fullName.Trim(); } var previousNamesQry = new PersonPreviousNameService( this.Context as RockContext ).Queryable(); if ( !string.IsNullOrWhiteSpace( singleName ) ) { if ( allowFirstNameOnly ) { return Queryable( includeDeceased, includeBusinesses ) .Where( p => p.LastName.StartsWith( singleName ) || p.FirstName.StartsWith( singleName ) || p.NickName.StartsWith( singleName ) || previousNamesQry.Any( a => a.PersonAlias.PersonId == p.Id && a.LastName.StartsWith( singleName ) ) ); } else { return Queryable( includeDeceased, includeBusinesses ) .Where( p => p.LastName.StartsWith( singleName ) || previousNamesQry.Any( a => a.PersonAlias.PersonId == p.Id && a.LastName.StartsWith( singleName ) ) ); } } else { var qry = Queryable( includeDeceased, includeBusinesses ); if ( includeBusinesses ) { int recordTypeBusinessId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid() ).Id; // if a we are including businesses, compare fullname against the Business Name (Person.LastName) qry = qry.Where( p => ( p.RecordTypeValueId.HasValue && p.RecordTypeValueId.Value == recordTypeBusinessId && p.LastName.Contains( fullName ) ) || ( ( p.LastName.StartsWith( lastName ) || previousNamesQry.Any( a => a.PersonAlias.PersonId == p.Id && a.LastName.StartsWith( lastName ) ) ) && ( p.FirstName.StartsWith( firstName ) || p.NickName.StartsWith( firstName ) ) ) ); } else { qry = qry.Where( p => ( ( p.LastName.StartsWith( lastName ) || previousNamesQry.Any( a => a.PersonAlias.PersonId == p.Id && a.LastName.StartsWith( lastName ) ) ) && ( p.FirstName.StartsWith( firstName ) || p.NickName.StartsWith( firstName ) ) ) ); } return qry; } }