コード例 #1
0
 private void Clear_form()
 {
     modify               = false;
     SaveButton.Enabled   = false;
     DeleteButton.Enabled = false;
     FirstNameBox.Clear();
     MiddleNmeBox.Clear();
     LastNameBox.Clear();
     GenderBox.Clear();
     Address1Box.Clear();
     Address2Box.Clear();
     CityBox.Clear();
     StateBox.Clear();
     ZipCodeBox.Clear();
     EmailBox.Clear();
     PhoneNumberBox.Clear();
     ResultList.SelectedItems.Clear();
     DateReceivedPicker.Value = DateTime.Today;
     StartTimeBox.Clear();
     SaveTimeBox.Clear();
     BackNumBox.Clear();
 }
コード例 #2
0
        /// <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);
                    }
                });
            }
        }
コード例 #3
0
ファイル: EditPerson.ascx.cs プロジェクト: moayyaed/Rock
        protected void SavePersonDetails(Person person, RockContext rockContext)
        {
            person.NickName = tbNickName.Text;

            person.TitleValueId  = dvpTitle.SelectedValue.AsIntegerOrNull();
            person.FirstName     = tbFirstName.Text;
            person.MiddleName    = tbMiddleName.Text;
            person.LastName      = tbLastName.Text;
            person.SuffixValueId = dvpSuffix.SelectedValue.AsIntegerOrNull();

            person.Gender = rblGender.SelectedValueAsEnum <Gender>();
            person.SetBirthDate(bpBirthday.SelectedDate);
            person.GradeOffset = gpGrade.SelectedValue.AsIntegerOrNull();

            person.LoadAttributes();
            person.SetAttributeValue("Allergy", rtbAllergy.Text);

            var newPhoneNumbers = new List <PhoneNumber>();

            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;

                if (hfPhoneType != null && pnbPhone != null && cbUnlisted != null)
                {
                    var countryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                    var phoneNumber = PhoneNumber.CleanNumber(pnbPhone.Number);
                    if (!string.IsNullOrWhiteSpace(countryCode) && !string.IsNullOrWhiteSpace(phoneNumber))
                    {
                        newPhoneNumbers.Add(new PhoneNumber
                        {
                            NumberTypeValueId  = hfPhoneType.ValueAsInt(),
                            Number             = phoneNumber,
                            CountryCode        = countryCode,
                            IsMessagingEnabled = false,
                            IsUnlisted         = cbUnlisted.Checked
                        });
                    }
                }
            }

            foreach (PhoneNumber oldPhoneNumber in person.PhoneNumbers.ToList())
            {
                var matchingPhoneNumber = newPhoneNumbers.FirstOrDefault(pn => pn.NumberTypeValueId == oldPhoneNumber.NumberTypeValueId);
                if (matchingPhoneNumber != null)
                {
                    oldPhoneNumber.CountryCode = matchingPhoneNumber.CountryCode;
                    oldPhoneNumber.Number      = matchingPhoneNumber.Number;
                    oldPhoneNumber.IsUnlisted  = matchingPhoneNumber.IsUnlisted;
                    newPhoneNumbers.Remove(matchingPhoneNumber);
                }
                else
                {
                    person.PhoneNumbers.Remove(oldPhoneNumber);
                    new PhoneNumberService(rockContext).Delete(oldPhoneNumber);
                }
            }

            foreach (PhoneNumber newPhoneNumber in newPhoneNumbers)
            {
                person.PhoneNumbers.Add(newPhoneNumber);
            }
        }
コード例 #4
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            RockContext rockContext           = new RockContext();
            var         person                = GetPerson();
            var         personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));
            var         changeRequest         = new ChangeRequest
            {
                EntityTypeId     = personAliasEntityType.Id,
                EntityId         = person.PrimaryAliasId ?? 0,
                RequestorAliasId = CurrentPersonAliasId ?? 0,
                RequestorComment = tbComments.Text
            };

            changeRequest.EvaluatePropertyChange(person, "PhotoId", iuPhoto.BinaryFileId);
            changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
            changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
            changeRequest.EvaluatePropertyChange(person, "MiddleName", tbMiddleName.Text);
            changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);
            changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

            var families = person.GetFamilies();

            if (families.Count() == 1)
            {
                var groupMember = person.PrimaryFamily.Members.Where(gm => gm.PersonId == person.Id).FirstOrDefault();
                if (groupMember != null)
                {
                    GroupTypeRole        groupTypeRole        = null;
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    if (ddlFamilyRole.SelectedValue == "A")
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid());
                    }
                    else if (ddlFamilyRole.SelectedValue == "C")
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid());
                    }
                    changeRequest.EvaluatePropertyChange(groupMember, "GroupRole", groupTypeRole, true);
                }
            }

            //Evaluate PhoneNumbers
            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)
                {
                    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 && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                        {
                            phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                            changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNullOrWhiteSpace())   // delete number
                        {
                            var phoneComment = string.Format("{0}: {1}.", phoneNumber.NumberTypeValue.Value, phoneNumber.NumberFormatted);
                            changeRequest.DeleteEntity(phoneNumber, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                        {
                            changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                        }

                        if (hfPhoneType.Value.AsInteger() == DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()))
                        {
                            var validationInfo = ValidateMobilePhoneNumber(PhoneNumber.CleanNumber(pnbPhone.Number));
                            if (validationInfo.IsNotNullOrWhiteSpace())
                            {
                                changeRequest.RequestorComment += "<h4>Dynamically Generated Warnings:</h4>" + validationInfo;
                            }
                        }
                    }
                }
            }

            changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text);
            changeRequest.EvaluatePropertyChange(person, "IsEmailActive", cbIsEmailActive.Checked);
            changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>());
            changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>());


            var birthday = bpBirthday.SelectedDate;

            if (birthday.HasValue)
            {
                changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month);
                changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day);
                if (birthday.Value.Year != DateTime.MinValue.Year)
                {
                    changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year);
                }
                else
                {
                    int?year = null;
                    changeRequest.EvaluatePropertyChange(person, "BirthYear", year);
                }
            }

            changeRequest.EvaluatePropertyChange(person, "Gender", ddlGender.SelectedValueAsEnum <Gender>());
            changeRequest.EvaluatePropertyChange(person, "MaritalStatusValue", DefinedValueCache.Get(ddlMaritalStatus.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "AnniversaryDate", dpAnniversaryDate.SelectedDate);
            changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);

            var groupEntity         = EntityTypeCache.Get(typeof(Group));
            var groupLocationEntity = EntityTypeCache.Get(typeof(GroupLocation));
            var family = person.GetFamily();

            var familyChangeRequest = new ChangeRequest()
            {
                EntityTypeId     = groupEntity.Id,
                EntityId         = family.Id,
                RequestorAliasId = CurrentPersonAliasId ?? 0
            };

            familyChangeRequest.EvaluatePropertyChange(family, "Campus", CampusCache.Get(ddlCampus.SelectedValueAsInt() ?? 0));

            var      currentLocation = person.GetHomeLocation();
            Location location        = new Location
            {
                Street1    = acAddress.Street1,
                Street2    = acAddress.Street2,
                City       = acAddress.City,
                State      = acAddress.State,
                PostalCode = acAddress.PostalCode,
            };
            var globalAttributesCache = GlobalAttributesCache.Get();

            location.Country = globalAttributesCache.OrganizationCountry;
            location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

            if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) ||
                (currentLocation != null && currentLocation.Street1 != location.Street1))
            {
                LocationService locationService = new LocationService(rockContext);
                locationService.Add(location);
                rockContext.SaveChanges();

                var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                var homeLocationType     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

                GroupLocation groupLocation = new GroupLocation
                {
                    CreatedByPersonAliasId  = CurrentPersonAliasId,
                    ModifiedByPersonAliasId = CurrentPersonAliasId,
                    GroupId    = family.Id,
                    LocationId = location.Id,
                    GroupLocationTypeValueId = homeLocationType.Id,
                    IsMailingLocation        = true,
                    IsMappedLocation         = true
                };

                var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString());

                var homelocations = family.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id);
                foreach (var homelocation in homelocations)
                {
                    familyChangeRequest.EvaluatePropertyChange(
                        homelocation,
                        "GroupLocationTypeValue",
                        previousLocationType,
                        true,
                        homelocation.Location.ToString());

                    familyChangeRequest.EvaluatePropertyChange(
                        homelocation,
                        "IsMailingLocation",
                        false,
                        true,
                        homelocation.Location.ToString());
                }
            }

            //Adding a new family member
            if (pAddPerson.SelectedValue.HasValue)
            {
                PersonService personService = new PersonService(rockContext);
                var           insertPerson  = personService.Get(pAddPerson.SelectedValue.Value);
                if (insertPerson != null)
                {
                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                    var familyGroupTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

                    //Remove all other group members
                    if (cbRemovePerson.Checked)
                    {
                        var members = groupMemberService.Queryable()
                                      .Where(m => m.PersonId == pAddPerson.SelectedValue.Value && m.Group.GroupTypeId == familyGroupTypeId);
                        foreach (var member in members)
                        {
                            var comment = string.Format("Removed {0} from {1}", insertPerson.FullName, member.Group.Name);
                            familyChangeRequest.DeleteEntity(member, true, comment);
                        }
                    }

                    var personFamilies = person.GetFamilies().ToList();

                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);

                    var roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;
                    if (insertPerson.Age.HasValue && insertPerson.Age.Value < 18)
                    {
                        roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id;
                    }

                    foreach (var personFamily in personFamilies)
                    {
                        //Make a new group member
                        GroupMember familyMember = new GroupMember
                        {
                            PersonId          = pAddPerson.SelectedValue.Value,
                            GroupId           = personFamily.Id,
                            GroupMemberStatus = GroupMemberStatus.Active,
                            Guid        = Guid.NewGuid(),
                            GroupRoleId = roleId
                        };
                        var insertComment = string.Format("Added {0} to {1}", insertPerson.FullName, personFamily.Name);
                        familyChangeRequest.AddEntity(familyMember, rockContext, true, insertComment);
                    }
                }
            }

            bool          autoApply = CanAutoApply(person);
            List <string> errors;

            if (changeRequest.ChangeRecords.Any() ||
                (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace()))
            {
                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(changeRequest);
                rockContext.SaveChanges();
                if (autoApply)
                {
                    changeRequest.CompleteChanges(rockContext, out errors);
                }

                changeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (familyChangeRequest.ChangeRecords.Any())
            {
                familyChangeRequest.RequestorComment = tbComments.Text;
                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(familyChangeRequest);
                rockContext.SaveChanges();
                if (autoApply)
                {
                    familyChangeRequest.CompleteChanges(rockContext, out errors);
                }
                familyChangeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (autoApply)
            {
                NavigateToPerson();
            }
            else
            {
                pnlMain.Visible     = false;
                pnlNoPerson.Visible = false;
                pnlDone.Visible     = true;
            }
        }
コード例 #5
0
        /// <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 (GetAttributeValue(AttributeKeys.DisplayTerms).AsBoolean() && !cbTOS.Checked)
            {
                nbTOS.Visible = true;
                return;
            }

            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);

            var person = GetPerson(personService);

            var personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));

            if (person.Id != 0)
            {
                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };


                if (person.PhotoId != imgPhoto.BinaryFileId)
                {
                    changeRequest.EvaluatePropertyChange(person, "PhotoId", imgPhoto.BinaryFileId);
                    if (person.Photo != null)
                    {
                        changeRequest.EvaluatePropertyChange(person.Photo, "IsTemporary", true, true);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
                changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
                changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
                changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);
                changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

                var birthMonth = person.BirthMonth;
                var birthDay   = person.BirthDay;
                var birthYear  = person.BirthYear;

                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date is not greater than today.
                    var today = RockDateTime.Today;
                    while (birthday.Value.CompareTo(today) > 0)
                    {
                        birthday = birthday.Value.AddYears(-100);
                    }

                    changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month);
                    changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day);

                    if (birthday.Value.Year != DateTime.MinValue.Year)
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year);
                    }
                    else
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", ( int? )null);
                    }
                }

                if (ddlGradePicker.Visible)
                {
                    changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);
                }
                changeRequest.EvaluatePropertyChange(person, "Gender", rblGender.SelectedValue.ConvertToEnum <Gender>());

                var primaryFamilyMembers = person.GetFamilyMembers(true).Where(m => m.PersonId == person.Id).ToList();
                foreach (var member in primaryFamilyMembers)
                {
                    changeRequest.EvaluatePropertyChange(member, "GroupRoleId", rblRole.SelectedValue.AsInteger(), true);
                }

                var primaryFamily       = person.GetFamily(rockContext);
                var familyChangeRequest = new ChangeRequest
                {
                    EntityTypeId     = EntityTypeCache.Get(typeof(Group)).Id,
                    EntityId         = primaryFamily.Id,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };

                // update campus
                bool showCampus = GetAttributeValue("ShowCampusSelector").AsBoolean();
                if (showCampus)
                {
                    // Only update campus for adults
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    var adultGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();
                    var adultRole = groupTypeRoleService.Get(adultGuid);
                    if (rblRole.SelectedValue.AsInteger() == adultRole.Id)
                    {
                        familyChangeRequest.EvaluatePropertyChange(primaryFamily, "CampusId", cpCampus.SelectedCampusId);
                    }
                }

                //Evaluate PhoneNumbers
                bool showPhoneNumbers = GetAttributeValue("ShowPhoneNumbers").AsBoolean();
                if (showPhoneNumbers)
                {
                    var  phoneNumberTypeIds = new List <int>();
                    var  phoneNumbersScreen = new List <PhoneNumber>();
                    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)
                        {
                            int phoneNumberTypeId;
                            if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                            {
                                var    phoneNumberList = person.PhoneNumbers.Where(n => n.NumberTypeValueId == phoneNumberTypeId).ToList();
                                var    phoneNumber     = phoneNumberList.FirstOrDefault(pn => pn.Number == PhoneNumber.CleanNumber(pnbPhone.Number));
                                string oldPhoneNumber  = string.Empty;

                                if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                                {
                                    phoneNumber = new PhoneNumber
                                    {
                                        PersonId           = person.Id,
                                        NumberTypeValueId  = phoneNumberTypeId,
                                        CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                        IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                        Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                                    };
                                    var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                                    changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                                else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                                {
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                            }
                        }
                    }
                    //Remove old phone numbers or changed
                    var phoneNumbersToRemove = person.PhoneNumbers
                                               .Where(n => !phoneNumbersScreen.Any(n2 => n2.Number == n.Number && n2.NumberTypeValueId == n.NumberTypeValueId)).ToList();

                    foreach (var number in phoneNumbersToRemove)
                    {
                        var phoneComment = string.Format("{0}: {1}.", number.NumberTypeValue.Value, number.NumberFormatted);
                        changeRequest.DeleteEntity(number, true, phoneComment);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text.Trim());
                changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>());
                changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>());

                // if they used the ImageEditor, and cropped it, the non-cropped 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();
                            }
                        }
                    }
                }


                // save family information
                if (pnlAddress.Visible)
                {
                    var      currentLocation = person.GetHomeLocation();
                    Location location        = new Location
                    {
                        Street1    = acAddress.Street1,
                        Street2    = acAddress.Street2,
                        City       = acAddress.City,
                        State      = acAddress.State,
                        PostalCode = acAddress.PostalCode,
                    };
                    var globalAttributesCache = GlobalAttributesCache.Get();
                    location.Country = globalAttributesCache.OrganizationCountry;
                    location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

                    if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) ||
                        (currentLocation != null && currentLocation.Street1 != location.Street1))
                    {
                        LocationService locationService = new LocationService(rockContext);
                        locationService.Add(location);
                        rockContext.SaveChanges();

                        var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                        var homeLocationType     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

                        GroupLocation groupLocation = new GroupLocation
                        {
                            CreatedByPersonAliasId  = CurrentPersonAliasId,
                            ModifiedByPersonAliasId = CurrentPersonAliasId,
                            GroupId    = primaryFamily.Id,
                            LocationId = location.Id,
                            GroupLocationTypeValueId = homeLocationType.Id,
                            IsMailingLocation        = true,
                            IsMappedLocation         = true
                        };

                        var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString());

                        var homelocations = primaryFamily.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id);
                        foreach (var homelocation in homelocations)
                        {
                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "GroupLocationTypeValue",
                                previousLocationType,
                                true,
                                homelocation.Location.ToString());

                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "IsMailingLocation",
                                false,
                                true,
                                homelocation.Location.ToString());
                        }
                    }
                }

                // Handle both Child and Adult attributes together here
                var attributeGuids = GetAttributeValue(AttributeKeys.PersonAttributesAdult).SplitDelimitedValues().AsGuidList();
                attributeGuids.AddRange(GetAttributeValue(AttributeKeys.PersonAttributesChild).SplitDelimitedValues().AsGuidList());
                if (attributeGuids.Count > 0)
                {
                    person.LoadAttributes();
                    Helper.GetEditValues(phAttributes, person);
                    changeRequest.EvaluateAttributes(person);
                }

                List <string> errors;

                if (changeRequest.ChangeRecords.Any() ||
                    (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace()))
                {
                    changeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(changeRequest);
                    rockContext.SaveChanges();

                    changeRequest.CompleteChanges(rockContext, out errors);
                }

                if (familyChangeRequest.ChangeRecords.Any())
                {
                    familyChangeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(familyChangeRequest);
                    rockContext.SaveChanges();
                    familyChangeRequest.CompleteChanges(rockContext, out errors);
                }
            }
            else
            {
                var primaryFamily = CurrentPerson.GetFamily(rockContext);

                person.PhotoId = imgPhoto.BinaryFileId;

                if (imgPhoto.BinaryFileId.HasValue)
                {
                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                    var binaryFile = binaryFileService.Get(imgPhoto.BinaryFileId.Value);
                    binaryFile.IsTemporary = false;
                }

                person.FirstName     = tbFirstName.Text;
                person.NickName      = tbNickName.Text;
                person.LastName      = tbLastName.Text;
                person.TitleValueId  = ddlTitle.SelectedValue.AsIntegerOrNull();
                person.SuffixValueId = ddlSuffix.SelectedValue.AsIntegerOrNull();
                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date 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;
                    }
                }

                person.Gender          = rblGender.SelectedValue.ConvertToEnum <Gender>();
                person.Email           = tbEmail.Text;
                person.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();

                if (ddlGradePicker.Visible)
                {
                    person.GraduationYear = ypGraduation.SelectedYear;
                }


                GroupMember groupMember = new GroupMember
                {
                    PersonId    = person.Id,
                    GroupId     = primaryFamily.Id,
                    GroupRoleId = rblRole.SelectedValue.AsInteger()
                };

                PersonService.AddPersonToFamily(person, true, primaryFamily.Id, rblRole.SelectedValue.AsInteger(), rockContext);

                PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);

                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 &&
                        pnbPhone.Number.IsNotNullOrWhiteSpace())
                    {
                        int phoneNumberTypeId;
                        if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                        {
                            var phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            phoneNumberService.Add(phoneNumber);
                        }
                    }
                }
                rockContext.SaveChanges();

                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0,
                    RequestorComment = "Added as new person from My Account."
                };

                if (tbComments.Text.IsNotNullOrWhiteSpace())
                {
                    changeRequest.RequestorComment += "<br><br>Comment: " + tbComments.Text;
                }

                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(changeRequest);
                rockContext.SaveChanges();

                List <string> errors;
                changeRequest.CompleteChanges(rockContext, out errors);
            }

            NavigateToParentPage();
        }
コード例 #6
0
        /// <summary>
        /// Creates the person.
        /// </summary>
        /// <returns></returns>
        private Person CreatePerson()
        {
            var rockContext = new RockContext();

            DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read(GetAttributeValue("ConnectionStatus").AsGuid());
            DefinedValueCache dvcRecordStatus     = DefinedValueCache.Read(GetAttributeValue("RecordStatus").AsGuid());

            Person person = new Person();

            person.FirstName         = tbFirstName.Text;
            person.LastName          = tbLastName.Text;
            person.Email             = tbEmail.Text;
            person.IsEmailActive     = true;
            person.EmailPreference   = EmailPreference.EmailAllowed;
            person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
            if (dvcConnectionStatus != null)
            {
                person.ConnectionStatusValueId = dvcConnectionStatus.Id;
            }

            if (dvcRecordStatus != null)
            {
                person.RecordStatusValueId = dvcRecordStatus.Id;
            }

            switch (ddlGender.SelectedValue)
            {
            case "M":
                person.Gender = Gender.Male;
                break;

            case "F":
                person.Gender = Gender.Female;
                break;

            default:
                person.Gender = Gender.Unknown;
                break;
            }

            var birthday = bdaypBirthDay.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;
                }
            }

            bool smsSelected = false;

            foreach (RepeaterItem item in rPhoneNumbers.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 (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                {
                    int phoneNumberTypeId;
                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                    {
                        var phoneNumber = new PhoneNumber {
                            NumberTypeValueId = phoneNumberTypeId
                        };
                        person.PhoneNumbers.Add(phoneNumber);
                        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;
                    }
                }
            }

            PersonService.SaveNewPerson(person, rockContext, null, false);

            // save address
            if (pnlAddress.Visible)
            {
                if (acAddress.IsValid && !string.IsNullOrWhiteSpace(acAddress.Street1) && !string.IsNullOrWhiteSpace(acAddress.City) && !string.IsNullOrWhiteSpace(acAddress.PostalCode))
                {
                    Guid locationTypeGuid = GetAttributeValue("LocationType").AsGuid();
                    if (locationTypeGuid != Guid.Empty)
                    {
                        Guid                 familyGroupTypeGuid  = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                        GroupService         groupService         = new GroupService(rockContext);
                        GroupLocationService groupLocationService = new GroupLocationService(rockContext);
                        var family = groupService.Queryable().Where(g => g.GroupType.Guid == familyGroupTypeGuid && g.Members.Any(m => m.PersonId == person.Id)).FirstOrDefault();

                        var groupLocation = new GroupLocation();
                        groupLocation.GroupId = family.Id;
                        groupLocationService.Add(groupLocation);

                        var location = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                        groupLocation.Location = location;

                        groupLocation.GroupLocationTypeValueId = DefinedValueCache.Read(locationTypeGuid).Id;
                        groupLocation.IsMailingLocation        = true;
                        groupLocation.IsMappedLocation         = true;

                        rockContext.SaveChanges();
                    }
                }
            }

            return(person);
        }
コード例 #7
0
        /// <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)
        {
            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);

                var changes = new List <string>();

                var person = personService.Get(CurrentPersonId ?? 0);
                if (person != null)
                {
                    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;

                    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);

                    var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                    History.EvaluateChange(changes, "Gender", person.Gender, newGender);
                    person.Gender = newGender;

                    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();

                    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)
                                {
                                    // marked the old images as IsTemporary so they will get cleaned up later
                                    binaryFile.IsTemporary = true;
                                    rockContext.SaveChanges();
                                }
                            }
                        }

                        NavigateToParentPage();
                    }
                }
            });
        }
コード例 #8
0
        /// <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)
        {
            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);

                var changes = new List <string>();

                var person = personService.Get(CurrentPersonId ?? 0);
                if (person != null)
                {
                    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;

                    History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text);
                    person.NickName = tbNickName.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);

                    var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                    History.EvaluateChange(changes, "Gender", person.Gender, newGender);
                    person.Gender = newGender;

                    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();

                    var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();
                    History.EvaluateChange(changes, "Email Preference", person.EmailPreference, newEmailPreference);
                    person.EmailPreference = newEmailPreference;

                    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)
                                {
                                    // marked the old images as IsTemporary so they will get cleaned up later
                                    binaryFile.IsTemporary = true;
                                    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();
                                        }
                                    }
                                }
                            }
                        }

                        // save address
                        if (pnlAddress.Visible)
                        {
                            Guid?familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();
                            if (familyGroupTypeGuid.HasValue)
                            {
                                var familyGroup = new GroupService(rockContext).Queryable()
                                                  .Where(f => f.GroupType.Guid == familyGroupTypeGuid.Value &&
                                                         f.Members.Any(m => m.PersonId == person.Id))
                                                  .FirstOrDefault();
                                if (familyGroup != null)
                                {
                                    Guid?addressTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull();
                                    if (addressTypeGuid.HasValue)
                                    {
                                        var groupLocationService = new GroupLocationService(rockContext);

                                        var dvHomeAddressType = DefinedValueCache.Read(addressTypeGuid.Value);
                                        var familyAddress     = groupLocationService.Queryable().Where(l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id).FirstOrDefault();
                                        if (familyAddress != null && string.IsNullOrWhiteSpace(acAddress.Street1))
                                        {
                                            // delete the current address
                                            History.EvaluateChange(changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty);
                                            groupLocationService.Delete(familyAddress);
                                            rockContext.SaveChanges();
                                        }
                                        else
                                        {
                                            if (!string.IsNullOrWhiteSpace(acAddress.Street1))
                                            {
                                                if (familyAddress == null)
                                                {
                                                    familyAddress = new GroupLocation();
                                                    groupLocationService.Add(familyAddress);
                                                    familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id;
                                                    familyAddress.GroupId           = familyGroup.Id;
                                                    familyAddress.IsMailingLocation = true;
                                                    familyAddress.IsMappedLocation  = true;
                                                }
                                                else if (hfStreet1.Value != string.Empty)
                                                {
                                                    // user clicked move so create a previous address
                                                    var previousAddress = new GroupLocation();
                                                    groupLocationService.Add(previousAddress);

                                                    var previousAddressValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                                                    if (previousAddressValue != null)
                                                    {
                                                        previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                                        previousAddress.GroupId = familyGroup.Id;

                                                        Location previousAddressLocation   = new Location();
                                                        previousAddressLocation.Street1    = hfStreet1.Value;
                                                        previousAddressLocation.Street2    = hfStreet2.Value;
                                                        previousAddressLocation.City       = hfCity.Value;
                                                        previousAddressLocation.State      = hfState.Value;
                                                        previousAddressLocation.PostalCode = hfPostalCode.Value;
                                                        previousAddressLocation.Country    = hfCountry.Value;

                                                        previousAddress.Location = previousAddressLocation;
                                                    }
                                                }

                                                familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                                                familyAddress.IsMappedLocation  = cbIsPhysicalAddress.Checked;

                                                var updatedHomeAddress = new Location();
                                                acAddress.GetValues(updatedHomeAddress);

                                                History.EvaluateChange(changes, dvHomeAddressType.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString());

                                                familyAddress.Location = updatedHomeAddress;
                                                rockContext.SaveChanges();
                                            }
                                        }

                                        HistoryService.SaveChanges(
                                            rockContext,
                                            typeof(Person),
                                            Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                            person.Id,
                                            changes);
                                    }
                                }
                            }
                        }

                        NavigateToParentPage();
                    }
                }
            });
        }
コード例 #9
0
        protected void lbSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                var rockContext = new RockContext();

                rockContext.WrapTransaction(() =>
                {
                    if (person != null)
                    {
                        var personService = new PersonService(rockContext);

                        var changes = new List <string>();

                        var personSave = personService.Get(person.Id);
                        personSave.LoadAttributes();


                        int?newTitleId = dvpTitle.SelectedValueAsInt();
                        History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(personSave.TitleValueId), DefinedValueCache.GetName(newTitleId));
                        personSave.TitleValueId = newTitleId;

                        History.EvaluateChange(changes, "First Name", personSave.FirstName, tbFirstName.Text);
                        personSave.FirstName = tbFirstName.Text;

                        string nickName = string.IsNullOrWhiteSpace(tbNickName.Text) ? tbFirstName.Text : tbNickName.Text;
                        History.EvaluateChange(changes, "Nick Name", personSave.NickName, nickName);
                        personSave.NickName = tbNickName.Text;

                        History.EvaluateChange(changes, "Middle Name", personSave.MiddleName, tbMiddleName.Text);
                        personSave.MiddleName = tbMiddleName.Text;

                        History.EvaluateChange(changes, "Last Name", personSave.LastName, tbLastName.Text);
                        personSave.LastName = tbLastName.Text;

                        int?newSuffixId = dvpSuffix.SelectedValueAsInt();
                        History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(personSave.SuffixValueId), DefinedValueCache.GetName(newSuffixId));
                        personSave.SuffixValueId = newSuffixId;

                        var birthMonth = personSave.BirthMonth;
                        var birthDay   = personSave.BirthDay;
                        var birthYear  = personSave.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);
                            }

                            personSave.BirthMonth = birthday.Value.Month;
                            personSave.BirthDay   = birthday.Value.Day;
                            if (birthday.Value.Year != DateTime.MinValue.Year)
                            {
                                personSave.BirthYear = birthday.Value.Year;
                            }
                            else
                            {
                                personSave.BirthYear = null;
                            }
                        }
                        else
                        {
                            personSave.SetBirthDate(null);
                        }

                        History.EvaluateChange(changes, "Birth Month", birthMonth, personSave.BirthMonth);
                        History.EvaluateChange(changes, "Birth Day", birthDay, personSave.BirthDay);
                        History.EvaluateChange(changes, "Birth Year", birthYear, personSave.BirthYear);


                        DateTime gradeTransitionDate = GlobalAttributesCache.Read().GetValue("GradeTransitionDate").AsDateTime() ?? new DateTime(RockDateTime.Now.Year, 6, 1);

                        // add a year if the next graduation mm/dd won't happen until next year
                        int gradeOffsetRefactor = (RockDateTime.Now < gradeTransitionDate) ? 0 : 1;


                        int?graduationYear = null;
                        if (gpGrade.SelectedValue.AsIntegerOrNull() != null)
                        {
                            graduationYear = gradeTransitionDate.Year + gradeOffsetRefactor + gpGrade.SelectedValue.AsIntegerOrNull();
                        }

                        History.EvaluateChange(changes, "Graduation Year", person.GraduationYear, graduationYear);
                        personSave.GraduationYear = graduationYear;

                        var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                        History.EvaluateChange(changes, "Gender", personSave.Gender, newGender);
                        personSave.Gender = newGender;

                        personSave.SetAttributeValue("Allergy", rtbAllergy.Text);

                        var phoneNumberTypeIds = new List <int>();

                        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;

                            if (hfPhoneType != null &&
                                pnbPhone != null &&
                                cbUnlisted != null)
                            {
                                if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                                {
                                    int phoneNumberTypeId;
                                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                                    {
                                        var phoneNumber       = personSave.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                                        string oldPhoneNumber = string.Empty;
                                        if (phoneNumber == null)
                                        {
                                            phoneNumber = new PhoneNumber {
                                                NumberTypeValueId = phoneNumberTypeId
                                            };
                                            personSave.PhoneNumbers.Add(phoneNumber);
                                        }
                                        else
                                        {
                                            oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                        }

                                        phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                                        phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                                        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 personSave.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);

                            personSave.PhoneNumbers.Remove(phoneNumber);
                            phoneNumberService.Delete(phoneNumber);
                        }

                        History.EvaluateChange(changes, "Email", personSave.Email, ebEmail.Text);
                        personSave.Email = ebEmail.Text.Trim();

                        if (personSave.IsValid)
                        {
                            personSave.SaveAttributeValues();

                            if (rockContext.SaveChanges() > 0)
                            {
                                if (changes.Any())
                                {
                                    HistoryService.SaveChanges(
                                        rockContext,
                                        typeof(Person),
                                        Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                        person.Id,
                                        changes);
                                }
                            }

                            if (!String.IsNullOrWhiteSpace(GetAttributeValue("PersonDetailsPage")))
                            {
                                NavigateToLinkedPage("PersonDetailsPage", new Dictionary <string, string>()
                                {
                                    { "PersonId", person.Id.ToString() }
                                });
                            }
                            else
                            {
                                NavigateToCurrentPage(new Dictionary <string, string>()
                                {
                                    { "PersonId", person.Id.ToString() }
                                });
                            }
                        }
                    }
                });
            }
        }
コード例 #10
0
ファイル: EditPerson.ascx.cs プロジェクト: philltran/Rock
        /// <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);
                    }
                });
            }
        }
コード例 #11
0
        /// <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)
        {
            Rock.Data.RockTransactionScope.WrapTransaction(() =>
            {
                var rockContext   = new RockContext();
                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.BirthDate = 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);

                DateTime?graduationDate = null;
                if (ypGraduation.SelectedYear.HasValue)
                {
                    graduationDate = new DateTime(ypGraduation.SelectedYear.Value, _gradeTransitionDate.Month, _gradeTransitionDate.Day);
                }
                History.EvaluateChange(changes, "Anniversary Date", person.GraduationDate, graduationDate);
                person.GraduationDate = graduationDate;

                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 = rblMaritalStatus.SelectedValueAsInt();
                History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId));
                person.MaritalStatusValueId = newMaritalStatusId;

                int?newConnectionStatusId = rblStatus.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 ?? true), 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 = person.GivingGroup != null ? person.GivingGroup.Name : string.Empty;
                    string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue(newGivingGroupId.Value.ToString()).Text : string.Empty;
                    History.EvaluateChange(changes, "Giving Group", oldGivingGroupName, newGivingGroupName);
                }

                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, "Record Status Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId));
                person.RecordStatusReasonValueId = newRecordStatusReasonId;

                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)
                            {
                                // marked the old images as IsTemporary so they will get cleaned up later
                                binaryFile.IsTemporary = true;
                                rockContext.SaveChanges();
                            }
                        }

                        Response.Redirect(string.Format("~/Person/{0}", Person.Id), false);
                    }
                }
            });
        }
コード例 #12
0
        /// <summary>
        /// Gets the person control for this field's <see cref="PersonFieldType"/>
        /// </summary>
        /// <param name="setValue">if set to <c>true</c> [set value].</param>
        /// <param name="fieldValue">The field value.</param>
        /// <param name="familyMemberSelected">if set to <c>true</c> [family member selected].</param>
        /// <param name="validationGroup">The validation group.</param>
        /// <returns></returns>
        public Control GetPersonControl(bool setValue, object fieldValue, bool familyMemberSelected, string validationGroup)
        {
            RegistrationTemplateFormField field = this;
            Control personFieldControl          = null;

            switch (field.PersonFieldType)
            {
            case RegistrationPersonFieldType.FirstName:
                var tbFirstName = new RockTextBox
                {
                    ID              = "tbFirstName",
                    Label           = "First Name",
                    Required        = field.IsRequired,
                    CssClass        = "js-first-name",
                    ValidationGroup = validationGroup,
                    Enabled         = !familyMemberSelected,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                personFieldControl = tbFirstName;
                break;

            case RegistrationPersonFieldType.LastName:
                var tbLastName = new RockTextBox
                {
                    ID              = "tbLastName",
                    Label           = "Last Name",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    Enabled         = !familyMemberSelected,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                personFieldControl = tbLastName;
                break;

            case RegistrationPersonFieldType.MiddleName:
                var tbMiddleName = new RockTextBox
                {
                    ID              = "tbMiddleName",
                    Label           = "Middle Name",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    Enabled         = !familyMemberSelected,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                // Enable the middle name field if it is currently disabled but required and there is no value.
                if (!tbMiddleName.Enabled && tbMiddleName.Required && tbMiddleName.Text.IsNullOrWhiteSpace())
                {
                    tbMiddleName.Enabled = true;
                }

                personFieldControl = tbMiddleName;
                break;

            case RegistrationPersonFieldType.Campus:
                var cpHomeCampus = new CampusPicker
                {
                    ID               = "cpHomeCampus",
                    Label            = "Campus",
                    Required         = field.IsRequired,
                    ValidationGroup  = validationGroup,
                    Campuses         = CampusCache.All(false),
                    SelectedCampusId = setValue && fieldValue != null?fieldValue.ToString().AsIntegerOrNull() : null
                };

                personFieldControl = cpHomeCampus;
                break;

            case RegistrationPersonFieldType.Address:
                var acAddress = new AddressControl
                {
                    ID    = "acAddress",
                    Label = "Address",
                    UseStateAbbreviation   = true,
                    UseCountryAbbreviation = false,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup
                };

                if (setValue && fieldValue != null)
                {
                    acAddress.SetValues(fieldValue as Location);
                }

                personFieldControl = acAddress;
                break;

            case RegistrationPersonFieldType.Email:
                var tbEmail = new EmailBox
                {
                    ID              = "tbEmail",
                    Label           = "Email",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                personFieldControl = tbEmail;
                break;

            case RegistrationPersonFieldType.Birthdate:
                var bpBirthday = new BirthdayPicker
                {
                    ID              = "bpBirthday",
                    Label           = "Birthday",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    SelectedDate    = setValue && fieldValue != null ? fieldValue as DateTime? : null
                };

                personFieldControl = bpBirthday;
                break;

            case RegistrationPersonFieldType.Grade:
                var gpGrade = new GradePicker
                {
                    ID                    = "gpGrade",
                    Label                 = "Grade",
                    Required              = field.IsRequired,
                    ValidationGroup       = validationGroup,
                    UseAbbreviation       = true,
                    UseGradeOffsetAsValue = true,
                    CssClass              = "input-width-md"
                };

                personFieldControl = gpGrade;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().AsIntegerOrNull();
                    gpGrade.SetValue(Person.GradeOffsetFromGraduationYear(value));
                }

                break;

            case RegistrationPersonFieldType.Gender:
                var ddlGender = new RockDropDownList
                {
                    ID              = "ddlGender",
                    Label           = "Gender",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                };

                ddlGender.BindToEnum <Gender>(true, new Gender[1] {
                    Gender.Unknown
                });

                personFieldControl = ddlGender;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().ConvertToEnumOrNull <Gender>() ?? Gender.Unknown;
                    ddlGender.SetValue(value.ConvertToInt());
                }

                break;

            case RegistrationPersonFieldType.MaritalStatus:
                var dvpMaritalStatus = new DefinedValuePicker
                {
                    ID              = "dvpMaritalStatus",
                    Label           = "Marital Status",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup
                };

                dvpMaritalStatus.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS.AsGuid()).Id;
                personFieldControl             = dvpMaritalStatus;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().AsInteger();
                    dvpMaritalStatus.SetValue(value);
                }

                break;

            case RegistrationPersonFieldType.AnniversaryDate:
                var dppAnniversaryDate = new DatePartsPicker
                {
                    ID              = "dppAnniversaryDate",
                    Label           = "Anniversary Date",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    SelectedDate    = setValue && fieldValue != null ? fieldValue as DateTime? : null
                };

                personFieldControl = dppAnniversaryDate;
                break;

            case RegistrationPersonFieldType.MobilePhone:
                var dvMobilePhone = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE);
                if (dvMobilePhone == null)
                {
                    break;
                }

                var ppMobile = new PhoneNumberBox
                {
                    ID              = "ppMobile",
                    Label           = dvMobilePhone.Value,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    CountryCode     = PhoneNumber.DefaultCountryCode()
                };

                var mobilePhoneNumber = setValue && fieldValue != null ? fieldValue as PhoneNumber : null;
                ppMobile.CountryCode = mobilePhoneNumber != null ? mobilePhoneNumber.CountryCode : string.Empty;
                ppMobile.Number      = mobilePhoneNumber != null?mobilePhoneNumber.ToString() : string.Empty;

                personFieldControl = ppMobile;
                break;

            case RegistrationPersonFieldType.HomePhone:
                var dvHomePhone = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME);
                if (dvHomePhone == null)
                {
                    break;
                }

                var ppHome = new PhoneNumberBox
                {
                    ID              = "ppHome",
                    Label           = dvHomePhone.Value,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    CountryCode     = PhoneNumber.DefaultCountryCode()
                };

                var homePhoneNumber = setValue && fieldValue != null ? fieldValue as PhoneNumber : null;
                ppHome.CountryCode = homePhoneNumber != null ? homePhoneNumber.CountryCode : string.Empty;
                ppHome.Number      = homePhoneNumber != null?homePhoneNumber.ToString() : string.Empty;

                personFieldControl = ppHome;
                break;

            case RegistrationPersonFieldType.WorkPhone:
                var dvWorkPhone = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK);
                if (dvWorkPhone == null)
                {
                    break;
                }

                var ppWork = new PhoneNumberBox
                {
                    ID              = "ppWork",
                    Label           = dvWorkPhone.Value,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    CountryCode     = PhoneNumber.DefaultCountryCode()
                };

                var workPhoneNumber = setValue && fieldValue != null ? fieldValue as PhoneNumber : null;
                ppWork.CountryCode = workPhoneNumber != null ? workPhoneNumber.CountryCode : string.Empty;
                ppWork.Number      = workPhoneNumber != null?workPhoneNumber.ToString() : string.Empty;

                personFieldControl = ppWork;
                break;

            case RegistrationPersonFieldType.ConnectionStatus:
                var dvpConnectionStatus = new DefinedValuePicker
                {
                    ID              = "dvpConnectionStatus",
                    Label           = "Connection Status",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup
                };

                dvpConnectionStatus.DefinedTypeId = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS)).Id;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().AsInteger();
                    dvpConnectionStatus.SetValue(value);
                }

                personFieldControl = dvpConnectionStatus;
                break;
            }

            return(personFieldControl);
        }
コード例 #13
0
        /// <summary>
        /// Handles the Click event of the btnSave control. Perform a save operation on
        /// the person being edited and then navigate to the return page.
        /// </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)
        {
            RockContext rockContext           = new RockContext();
            Person      person                = new PersonService(rockContext).Get(TargetPersonId);
            Guid        emailWorkflowTypeGuid = Guid.Empty;

            rockContext.WrapTransaction(() =>
            {
                var changes = new List <string>();

                //
                // Process the nick name.
                //
                if (GetAttributeValue("EditNickName").AsBoolean(true))
                {
                    History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text.Trim());
                    person.NickName = tbNickName.Text.Trim();
                }

                //
                // Process the gender.
                //
                var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                History.EvaluateChange(changes, "Gender", person.Gender, newGender);
                person.Gender = newGender;

                //
                // Process the birthday.
                //
                if (GetAttributeValue("EditBirthday").AsBoolean(true))
                {
                    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);
                }

                //
                // Process the grade / graduation year.
                //
                if (GetAttributeValue("EditGrade").AsBoolean(true))
                {
                    int?graduationYear = null;
                    if (ypGraduation.SelectedYear.HasValue)
                    {
                        graduationYear = ypGraduation.SelectedYear.Value;
                    }

                    History.EvaluateChange(changes, "Graduation Year", person.GraduationYear, graduationYear);
                    person.GraduationYear = graduationYear;
                }

                //
                // Process the marital status and anniversary date.
                //
                if (GetAttributeValue("EditMaritalStatus").AsBoolean(true))
                {
                    int?newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId));
                    person.MaritalStatusValueId = newMaritalStatusId;

                    History.EvaluateChange(changes, "Anniversary Date", person.AnniversaryDate, dpAnniversaryDate.SelectedDate);
                    person.AnniversaryDate = dpAnniversaryDate.SelectedDate;
                }

                //
                // Process the e-mail address.
                //
                if (GetAttributeValue("EditEmail").AsBoolean(true))
                {
                    emailWorkflowTypeGuid = GetAttributeValue("EmailChangeWorkflow").AsGuid();

                    if (emailWorkflowTypeGuid == Guid.Empty)
                    {
                        History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text.Trim());
                        person.Email = tbEmail.Text.Trim();
                    }
                }

                //
                // Process all the phone numbers for this person.
                //
                bool smsSelected       = false;
                var phoneNumberTypeIds = new List <int>();
                foreach (RepeaterItem item in rContactInfo.Items)
                {
                    HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                    PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox;
                    CheckBox cbSms          = item.FindControl("cbSms") as CheckBox;

                    if (hfPhoneType != null &&
                        pnbPhone != null &&
                        cbSms != 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;
                                }

                                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);
                }

                //
                // If the person is valid then save the person and begin
                // working on the family (address).
                //
                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);

                            changes.Clear();
                        }
                    }

                    //
                    // Save the family address information.
                    //
                    if (pnlAddress.Visible)
                    {
                        Guid?familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();
                        if (familyGroupTypeGuid.HasValue)
                        {
                            var familyGroup = new GroupService(rockContext).Queryable()
                                              .Where(f => f.GroupType.Guid == familyGroupTypeGuid.Value &&
                                                     f.Members.Any(m => m.PersonId == person.Id))
                                              .FirstOrDefault();
                            if (familyGroup != null)
                            {
                                Guid?addressTypeGuid = GetAttributeValue("AddressType").AsGuidOrNull();
                                if (addressTypeGuid.HasValue)
                                {
                                    var groupLocationService = new GroupLocationService(rockContext);

                                    var addressTypeDv = DefinedValueCache.Read(addressTypeGuid.Value);
                                    var familyAddress = groupLocationService.Queryable().Where(l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == addressTypeDv.Id).FirstOrDefault();
                                    if (familyAddress != null && string.IsNullOrWhiteSpace(acAddress.Street1))
                                    {
                                        // delete the current address
                                        History.EvaluateChange(changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty);
                                        groupLocationService.Delete(familyAddress);
                                        rockContext.SaveChanges();
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrWhiteSpace(acAddress.Street1))
                                        {
                                            var previousAddressValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());

                                            if (familyAddress == null)
                                            {
                                                familyAddress = new GroupLocation();
                                                groupLocationService.Add(familyAddress);
                                                familyAddress.GroupLocationTypeValueId = addressTypeDv.Id;
                                                familyAddress.GroupId           = familyGroup.Id;
                                                familyAddress.IsMailingLocation = true;
                                                familyAddress.IsMappedLocation  = true;
                                            }
                                            else if (addressTypeDv.Guid == Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid() && previousAddressValue != null)
                                            {
                                                var isChanged = familyAddress.Location.Street1 != acAddress.Street1 ||
                                                                familyAddress.Location.Street2 != acAddress.Street2 ||
                                                                familyAddress.Location.City != acAddress.City ||
                                                                familyAddress.Location.State != acAddress.State ||
                                                                familyAddress.Location.PostalCode != acAddress.PostalCode;

                                                var hasPrevious = groupLocationService
                                                                  .Queryable("Location")
                                                                  .Where(l => l.GroupLocationTypeValueId == previousAddressValue.Id && l.GroupId == familyGroup.Id)
                                                                  .Where(l => l.Location.Street1 == familyAddress.Location.Street1)
                                                                  .Where(l => l.Location.Street2 == familyAddress.Location.Street2)
                                                                  .Where(l => l.Location.City == familyAddress.Location.City)
                                                                  .Where(l => l.Location.State == familyAddress.Location.State)
                                                                  .Where(l => l.Location.PostalCode == familyAddress.Location.PostalCode)
                                                                  .Where(l => l.Location.Country == familyAddress.Location.Country)
                                                                  .Any();

                                                //
                                                // Only save the previous address if it has actually changed and there is not
                                                // already a matching previous address.
                                                //
                                                if (isChanged && !hasPrevious)
                                                {
                                                    var previousAddress = new GroupLocation();
                                                    groupLocationService.Add(previousAddress);

                                                    previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                                    previousAddress.GroupId = familyGroup.Id;

                                                    Location previousAddressLocation   = new Location();
                                                    previousAddressLocation.Street1    = familyAddress.Location.Street1;
                                                    previousAddressLocation.Street2    = familyAddress.Location.Street2;
                                                    previousAddressLocation.City       = familyAddress.Location.City;
                                                    previousAddressLocation.State      = familyAddress.Location.State;
                                                    previousAddressLocation.PostalCode = familyAddress.Location.PostalCode;
                                                    previousAddressLocation.Country    = familyAddress.Location.Country;

                                                    previousAddress.Location = previousAddressLocation;
                                                }
                                            }

                                            familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                                            familyAddress.IsMappedLocation  = cbIsPhysicalAddress.Checked;

                                            var updatedHomeAddress = new Location();
                                            acAddress.GetValues(updatedHomeAddress);

                                            History.EvaluateChange(changes, addressTypeDv.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString());

                                            familyAddress.Location = updatedHomeAddress;
                                            rockContext.SaveChanges();
                                        }
                                    }

                                    HistoryService.SaveChanges(
                                        rockContext,
                                        typeof(Person),
                                        Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                        person.Id,
                                        changes);
                                }
                            }
                        }
                    }
                }
            });

            if (emailWorkflowTypeGuid != Guid.Empty)
            {
                LaunchEmailWorkflow(emailWorkflowTypeGuid, person, tbEmail.Text.Trim());
            }

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("SuccessTemplate")))
            {
                pnlEdit.Visible    = false;
                pnlSuccess.Visible = true;

                nbSuccess.Text = GetAttributeValue("SuccessTemplate").ResolveMergeFields(new Dictionary <string, object>());
            }
            else
            {
                NavigateToParentPage();
            }
        }