/// <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); } }); } }
/// <summary> /// Maps the authorizations to an attribute. /// </summary> /// <param name="tableData">The table data.</param> private void MapAuthorizations(IQueryable <Row> tableData) { var lookupContext = new RockContext(); var rockContext = new RockContext(); var categoryService = new CategoryService(lookupContext); var personService = new PersonService(lookupContext); var noteList = new List <Note>(); int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying Authorization import ({0:N0} found).", totalRows)); var attributeList = new AttributeService(lookupContext).Queryable().ToList(); int authorizationAttributeId = 0; if (attributeList.Find(a => a.Key == "PickupAuthorization") != null) { authorizationAttributeId = attributeList.Find(a => a.Key == "PickupAuthorization").Id; } var authorizationAttributeValueList = new List <AttributeValue>(); authorizationAttributeValueList = new AttributeValueService(rockContext).Queryable().Where(av => av.AttributeId == authorizationAttributeId).ToList(); int f1HouseholdIdAttributeId = attributeList.Find(a => a.Key == "F1HouseholdId").Id; //places all household attributes in a dictionary where the key is the personId and the houshold is the value. var householdDictionary = new AttributeValueService(lookupContext).Queryable() .Where(av => av.AttributeId == f1HouseholdIdAttributeId) .Select(av => new { PersonId = av.EntityId, HouseholdId = av.Value }) .ToDictionary(t => t.PersonId, t => t.HouseholdId); foreach (var row in tableData) { //var rockContext = new RockContext(); var categoryList = new CategoryService(rockContext).Queryable().ToList(); //check if category exists //If it doesn't (though it should), it will create a new category called Authorization if (categoryList.Find(c => c.Name == "Childhood Information") == null) { var entityType = new EntityTypeService(rockContext); //creates if category doesn't exist var newCategory = new Category(); newCategory.IsSystem = false; newCategory.EntityTypeId = entityType.Queryable().Where(e => e.Name == "Rock.Model.Attribute").Select(e => e.Id).FirstOrDefault(); newCategory.EntityTypeQualifierColumn = "EntityTypeId"; newCategory.EntityTypeQualifierValue = Convert.ToString(PersonEntityTypeId); newCategory.Name = "Authorization"; newCategory.Description = "Contains the pickup authorization"; //var newCategoryContext = new RockContext(); //newCategoryContext.WrapTransaction( () => //{ // newCategoryContext.Configuration.AutoDetectChangesEnabled = false; // newCategoryContext.Categories.Add( newCategory ); // newCategoryContext.SaveChanges( DisableAudit ); //} ); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Categories.Add(newCategory); rockContext.SaveChanges(DisableAudit); }); } attributeList = new AttributeService(lookupContext).Queryable().ToList(); //Check if Attribute exists //If it doesn't it creates the attribute if (attributeList.Find(a => a.Key == "PickupAuthorization") == null) { var fieldType = new FieldTypeService(rockContext); //var newAttributeList = new List<Rock.Model.Attribute>(); var fieldTypeId = fieldType.Queryable().Where(e => e.Name == "Memo").FirstOrDefault().Id; var category2 = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Childhood Information").FirstOrDefault(); var category3 = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Authorization").FirstOrDefault(); //Creates if attribute doesn't exist //The attribute is a memo attribute var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "PickupAuthorization"; newAttribute.Name = "Pickup Authorization"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Lists who is authorized to pickup this child along with their current phone number."; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; if (categoryList.Find(c => c.Name == "Childhood Information") != null) { newAttribute.Categories = new List <Category>(); newAttribute.Categories.Add(category2); } //If authorization category was create, this is where the attribute is set to that category. else { newAttribute.Categories = new List <Category>(); newAttribute.Categories.Add(category3); //Sets to Authorization Attribute Category. } //saves the attribute rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Attributes.Add(newAttribute); rockContext.SaveChanges(DisableAudit); }); } //Adding to the person's attributes int? householdId = row["HouseholdID"] as int?; string personName = row["PersonName"] as string; DateTime?authorizationDate = row["AuthorizationDate"] as DateTime?; attributeList = new AttributeService(rockContext).Queryable().ToList(); //Gets the Attribute Id for Pickup Authorization. authorizationAttributeId = attributeList.Find(a => a.Key == "PickupAuthorization").Id; //since F1 authorization applies to the household id and not individual I have to apply it to all members in that household. //Value in F1 is a text entry and not a person select. Discuss with staff that we need to break away from this and start using known relationships for authorization foreach (var household in householdDictionary.Where(h => h.Value == Convert.ToString(householdId))) { //checks if a record already exists in the list if (authorizationAttributeValueList.Find(a => a.AttributeId == authorizationAttributeId && a.EntityId == household.Key) == null) { var person = new PersonService(rockContext).Queryable().Where(p => p.Id == household.Key).FirstOrDefault(); //trying to keep from adding this attribute to adult records if (person != null && (person.Age <= 18 || person.Age == null)) { //creates new attribute record if it does not exist. var newAuthorizationAttribute = new AttributeValue(); newAuthorizationAttribute.IsSystem = false; newAuthorizationAttribute.AttributeId = authorizationAttributeId; newAuthorizationAttribute.EntityId = household.Key; //the key is the person ID newAuthorizationAttribute.Value = personName + ", "; //text field newAuthorizationAttribute.CreatedDateTime = authorizationDate; //adds the new record to the list authorizationAttributeValueList.Add(newAuthorizationAttribute); } } //if a record already exists else { //adds to the current value. authorizationAttributeValueList.Find(a => a.AttributeId == authorizationAttributeId && a.EntityId == household.Key).Value = personName + ", "; } } completed++; if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} authorizations imported ({1}% complete).", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { //rockContext.WrapTransaction( () => // { // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.AttributeValues.AddRange( authorizationAttributeValueList ); // rockContext.SaveChanges( DisableAudit ); //I get can't insert duplicate entry error // } ); ReportPartialProgress(); } } if (authorizationAttributeValueList.Any()) { //var rockContext = new RockContext(); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.AttributeValues.AddRange(authorizationAttributeValueList); rockContext.SaveChanges(DisableAudit); }); } ReportProgress(100, string.Format("Finished authorization import: {0:N0} notes imported.", completed)); }