/// <summary> /// Determines whether this is a new group member (just added) or if either Person or Role is different than what is stored in the database /// </summary> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public bool IsNewOrChangedGroupMember(RockContext rockContext) { if (this.Id == 0) { // new group member return(true); } else { var groupMemberService = new GroupMemberService(rockContext); var databaseGroupMemberRecord = groupMemberService.Get(this.Id); // existing groupmember record, but person or role was changed var hasChanged = this.PersonId != databaseGroupMemberRecord.PersonId || this.GroupRoleId != databaseGroupMemberRecord.GroupRoleId; if (!hasChanged) { var entry = rockContext.Entry(this); if (entry != null) { hasChanged = rockContext.Entry(this).Property("PersonId")?.IsModified == true || rockContext.Entry(this).Property("GroupRoleId")?.IsModified == true; } } return(hasChanged); } }
/// <summary> /// Determines whether this is an existing record but the GroupMemberStatus or GroupRoleId was modified since loaded from the database /// </summary> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public bool IsStatusOrRoleModified(RockContext rockContext) { if (this.Id == 0) { // new group member return(false); } else { var groupMemberService = new GroupMemberService(rockContext); var databaseGroupMemberRecord = groupMemberService.Get(this.Id); if (databaseGroupMemberRecord == null) { return(false); } // existing groupmember record, but person or role was changed var hasChanged = ((this.GroupMemberStatus != databaseGroupMemberRecord.GroupMemberStatus) || (this.GroupRoleId != databaseGroupMemberRecord.GroupRoleId)); if (!hasChanged) { var entry = rockContext.Entry(this); if (entry != null) { hasChanged = rockContext.Entry(this).Property("GroupMemberStatus")?.IsModified == true || rockContext.Entry(this).Property("GroupRoleId")?.IsModified == true; } } return(hasChanged); } }
/// <summary> /// Determines whether this is a new group member (just added) or if either Person or Role is different than what is stored in the database /// </summary> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public bool IsNewOrChangedGroupMember(RockContext rockContext) { if (this.Id == 0) { // new group member return(true); } else { var groupMemberService = new GroupMemberService(rockContext); var databaseGroupMemberRecord = groupMemberService.Get(this.Id); // existing groupmember record, but person or role was changed return((this.PersonId != databaseGroupMemberRecord.PersonId) || (this.GroupRoleId != databaseGroupMemberRecord.GroupRoleId)); } }
/// <summary> /// Determines whether this is a new group member (just added), if either Person or Role is different than what is stored in the database, if person is restored from archived, or their status is getting changed to Active /// </summary> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public bool IsNewOrChangedGroupMember(RockContext rockContext) { if (this.Id == 0) { // new group member return(true); } else { var groupMemberService = new GroupMemberService(rockContext); var databaseGroupMemberRecord = groupMemberService.Get(this.Id); // existing group member record, but person or role or archive status was changed, or active status is getting changed to true var hasChanged = this.PersonId != databaseGroupMemberRecord.PersonId || this.GroupRoleId != databaseGroupMemberRecord.GroupRoleId || (databaseGroupMemberRecord.IsArchived && databaseGroupMemberRecord.IsArchived != this.IsArchived) || (databaseGroupMemberRecord.GroupMemberStatus != GroupMemberStatus.Active && this.GroupMemberStatus == GroupMemberStatus.Active); if (!hasChanged) { // no change detected by comparing to the database record, so check if the ChangeTracker detects that these fields were modified var entry = rockContext.Entry(this); if (entry != null && entry.State != EntityState.Detached) { var originalStatus = ( GroupMemberStatus? )rockContext.Entry(this).OriginalValues["GroupMemberStatus"]; var newStatus = ( GroupMemberStatus? )rockContext.Entry(this).CurrentValues["GroupMemberStatus"]; hasChanged = rockContext.Entry(this).Property("PersonId")?.IsModified == true || rockContext.Entry(this).Property("GroupRoleId")?.IsModified == true || (rockContext.Entry(this).Property("IsArchived")?.IsModified == true && !rockContext.Entry(this).Property("IsArchived").ToStringSafe().AsBoolean()) || (originalStatus != GroupMemberStatus.Active && newStatus == GroupMemberStatus.Active); } } return(hasChanged); } }
/// <summary> /// Deletes the group member. /// </summary> /// <param name="groupMemberId">The group member identifier.</param> private void DeleteGroupMember( int groupMemberId ) { RockContext rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); var groupMember = groupMemberService.Get( groupMemberId ); if ( groupMember != null ) { groupMemberService.Delete( groupMember ); } rockContext.SaveChanges(); }
/// <summary> /// Restores the view-state information from a previous user control request that was saved by the <see cref="M:System.Web.UI.UserControl.SaveViewState" /> method. /// </summary> /// <param name="savedState">An <see cref="T:System.Object" /> that represents the user control state to be restored.</param> protected override void LoadViewState( object savedState ) { base.LoadViewState( savedState ); if ( IsEditingGroup == true ) { Group group = new GroupService( new RockContext() ).Get( _groupId ); group.LoadAttributes(); phAttributes.Controls.Clear(); Rock.Attribute.Helper.AddEditControls( group, phAttributes, false, BlockValidationGroup ); } if ( IsEditingGroupMember == true ) { RockContext rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); var groupMember = groupMemberService.Get( this.CurrentGroupMemberId ); if ( groupMember == null ) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = _groupId; groupMember.Group = new GroupService( rockContext ).Get( groupMember.GroupId ); groupMember.GroupRoleId = groupMember.Group.GroupType.DefaultGroupRoleId ?? 0; groupMember.GroupMemberStatus = GroupMemberStatus.Active; } // set attributes groupMember.LoadAttributes(); phGroupMemberAttributes.Controls.Clear(); Rock.Attribute.Helper.AddEditControls( groupMember, phGroupMemberAttributes, true, string.Empty, true ); } }
/// <summary> /// Handles the Click event of the btnSaveGroupMember 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 btnSaveGroupMember_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); GroupTypeRole role = new GroupTypeRoleService( rockContext ).Get( ddlGroupRole.SelectedValueAsInt() ?? 0 ); var groupMember = groupMemberService.Get( this.CurrentGroupMemberId ); if ( this.CurrentGroupMemberId == 0 ) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = _groupId; // check to see if the person is alread a member of the gorup/role var existingGroupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId( _groupId, ppGroupMemberPerson.SelectedValue ?? 0, ddlGroupRole.SelectedValueAsId() ?? 0 ); if ( existingGroupMember != null ) { // if so, don't add and show error message var person = new PersonService( rockContext ).Get( (int)ppGroupMemberPerson.PersonId ); nbGroupMemberErrorMessage.Title = "Person Already In Group"; nbGroupMemberErrorMessage.Text = string.Format( "{0} already belongs to the {1} role for this {2}, and cannot be added again with the same role.", person.FullName, ddlGroupRole.SelectedItem.Text, role.GroupType.GroupTerm, RockPage.PageId, existingGroupMember.Id ); return; } } groupMember.PersonId = ppGroupMemberPerson.PersonId.Value; groupMember.GroupRoleId = role.Id; // set their status. If HideInactiveGroupMemberStatus is True, and they are already Inactive, keep their status as Inactive; bool hideGroupMemberInactiveStatus = this.GetAttributeValue( "HideInactiveGroupMemberStatus" ).AsBooleanOrNull() ?? false; var selectedStatus = rblStatus.SelectedValueAsEnumOrNull<GroupMemberStatus>(); if ( !selectedStatus.HasValue ) { if ( hideGroupMemberInactiveStatus ) { selectedStatus = GroupMemberStatus.Inactive; } else { selectedStatus = GroupMemberStatus.Active; } } groupMember.GroupMemberStatus = selectedStatus.Value; groupMember.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phAttributes, groupMember ); if ( !Page.IsValid ) { return; } // if the groupMember IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass. // So, make sure a message is displayed in the validation summary cvEditGroupMember.IsValid = groupMember.IsValid; if ( !cvEditGroupMember.IsValid ) { cvEditGroupMember.ErrorMessage = groupMember.ValidationResults.Select( a => a.ErrorMessage ).ToList().AsDelimited( "<br />" ); return; } // using WrapTransaction because there are two Saves rockContext.WrapTransaction( () => { if ( groupMember.Id.Equals( 0 ) ) { groupMemberService.Add( groupMember ); } rockContext.SaveChanges(); groupMember.SaveAttributeValues( rockContext ); } ); Group group = new GroupService( rockContext ).Get( groupMember.GroupId ); if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) { Rock.Security.Role.Flush( group.Id ); } pnlEditGroupMember.Visible = false; pnlGroupView.Visible = true; DisplayViewGroup(); this.IsEditingGroupMember = false; }
protected void btnSaveGroupMember_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); GroupTypeRole role = new GroupTypeRoleService( rockContext ).Get( ddlGroupRole.SelectedValueAsInt() ?? 0 ); var groupMember = groupMemberService.Get( this.CurrentGroupMemberId ); if ( this.CurrentGroupMemberId == 0 ) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = _groupId; // check to see if the person is alread a member of the gorup/role var existingGroupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId( _groupId, ppGroupMemberPerson.SelectedValue ?? 0, ddlGroupRole.SelectedValueAsId() ?? 0 ); if ( existingGroupMember != null ) { // if so, don't add and show error message var person = new PersonService( rockContext ).Get( (int)ppGroupMemberPerson.PersonId ); nbGroupMemberErrorMessage.Title = "Person Already In Group"; nbGroupMemberErrorMessage.Text = string.Format( "{0} already belongs to the {1} role for this {2}, and cannot be added again with the same role.", person.FullName, ddlGroupRole.SelectedItem.Text, role.GroupType.GroupTerm, RockPage.PageId, existingGroupMember.Id ); return; } } groupMember.PersonId = ppGroupMemberPerson.PersonId.Value; groupMember.GroupRoleId = role.Id; groupMember.GroupMemberStatus = rblStatus.SelectedValueAsEnum<GroupMemberStatus>(); groupMember.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phAttributes, groupMember ); // using WrapTransaction because there are two Saves rockContext.WrapTransaction( () => { if ( groupMember.Id.Equals( 0 ) ) { groupMemberService.Add( groupMember ); } rockContext.SaveChanges(); groupMember.SaveAttributeValues( rockContext ); } ); Group group = new GroupService( rockContext ).Get( groupMember.GroupId ); if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) { Rock.Security.Role.Flush( group.Id ); Rock.Security.Authorization.Flush(); } pnlEditGroupMember.Visible = false; pnlGroupView.Visible = true; DisplayViewGroup(); this.IsEditingGroupMember = false; }
/// <summary> /// Handles the SaveClick event of the mdPlaceElsewhere 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 mdPlaceElsewhere_SaveClick( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { var groupService = new GroupService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); var groupMember = groupMemberService.Get( hfPlaceElsewhereGroupMemberId.Value.AsInteger() ); if ( groupMember != null ) { string errorMessage; if ( !groupMemberService.CanDelete( groupMember, out errorMessage ) ) { nbPlaceElsewhereWarning.Text = errorMessage; return; } var trigger = _group.GetGroupMemberWorkflowTriggers().FirstOrDefault( a => a.Id == hfPlaceElsewhereTriggerId.Value.AsInteger() ); if ( trigger != null ) { // create a transaction for the selected trigger var transaction = new Rock.Transactions.GroupMemberPlacedElsewhereTransaction( groupMember, tbPlaceElsewhereNote.Text, trigger ); // delete the group member from the current group groupMemberService.Delete( groupMember ); rockContext.SaveChanges(); // queue up the transaction Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction ); } } mdPlaceElsewhere.Hide(); mdPlaceElsewhere.Visible = false; BindGroupMembersGrid(); } }
/// <summary> /// Handles the Click event of the btnCancel 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 btnCancel_Click( object sender, EventArgs e ) { if ( hfGroupMemberId.Value.Equals( "0" ) ) { // Cancelling on Add. Dictionary<string, string> qryString = new Dictionary<string, string>(); qryString["GroupId"] = hfGroupId.Value; NavigateToParentPage( qryString ); } else { // Cancelling on Edit. Return to Details GroupMemberService groupMemberService = new GroupMemberService( new RockContext() ); GroupMember groupMember = groupMemberService.Get( int.Parse( hfGroupMemberId.Value ) ); Dictionary<string, string> qryString = new Dictionary<string, string>(); qryString["GroupId"] = groupMember.GroupId.ToString(); NavigateToParentPage( qryString ); } }
protected void btnMoveRegistration_Click( object sender, EventArgs e ) { // set the new registration id using ( var rockContext = new RockContext() ) { var registrationService = new RegistrationService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); var registration = registrationService.Get( Registration.Id ); registration.RegistrationInstanceId = ddlNewRegistrationInstance.SelectedValue.AsInteger(); // Move registrants to new group int? groupId = ddlMoveGroup.SelectedValueAsInt(); if ( groupId.HasValue ) { registration.GroupId = groupId; rockContext.SaveChanges(); var group = new GroupService( rockContext ).Get( groupId.Value ); if ( group != null ) { int? groupRoleId = null; var template = registration.RegistrationInstance.RegistrationTemplate; if ( group.GroupTypeId == template.GroupTypeId && template.GroupMemberRoleId.HasValue ) { groupRoleId = template.GroupMemberRoleId.Value; } if ( !groupRoleId.HasValue ) { groupRoleId = group.GroupType.DefaultGroupRoleId; } if ( !groupRoleId.HasValue ) { groupRoleId = group.GroupType.Roles.OrderBy( r => r.Order ).Select( r => r.Id ).FirstOrDefault(); } if ( groupRoleId.HasValue ) { foreach ( var registrant in registration.Registrants.Where( r => r.PersonAlias != null ) ) { var newGroupMembers = groupMemberService.GetByGroupIdAndPersonId( groupId.Value, registrant.PersonAlias.PersonId ); if ( !newGroupMembers.Any() ) { // Get any existing group member attribute values var existingAttributeValues = new Dictionary<string, string>(); if ( registrant.GroupMemberId.HasValue ) { var existingGroupMember = groupMemberService.Get( registrant.GroupMemberId.Value ); if ( existingGroupMember != null ) { existingGroupMember.LoadAttributes( rockContext ); foreach ( var attributeValue in existingGroupMember.AttributeValues ) { existingAttributeValues.Add( attributeValue.Key, attributeValue.Value.Value ); } } registrant.GroupMember = null; groupMemberService.Delete( existingGroupMember ); } var newGroupMember = new GroupMember(); groupMemberService.Add( newGroupMember ); newGroupMember.Group = group; newGroupMember.PersonId = registrant.PersonAlias.PersonId; newGroupMember.GroupRoleId = groupRoleId.Value; rockContext.SaveChanges(); newGroupMember = groupMemberService.Get( newGroupMember.Id ); newGroupMember.LoadAttributes(); foreach( var attr in newGroupMember.Attributes ) { if ( existingAttributeValues.ContainsKey( attr.Key ) ) { newGroupMember.SetAttributeValue( attr.Key, existingAttributeValues[attr.Key] ); } } newGroupMember.SaveAttributeValues( rockContext ); registrant.GroupMember = newGroupMember; rockContext.SaveChanges(); } } } } } // Reload registration Registration = GetRegistration( Registration.Id ); lWizardInstanceName.Text = Registration.RegistrationInstance.Name; ShowReadonlyDetails( Registration ); } mdMoveRegistration.Hide(); }
private void SaveGroupMember() { if ( Page.IsValid ) { var rockContext = new RockContext(); // Verify valid group var groupService = new GroupService( rockContext ); var group = groupService.Get( hfGroupId.ValueAsInt() ); if ( group == null ) { nbErrorMessage.Title = "Please select a Role"; return; } // Check to see if a person was selected int? personId = ppGroupMemberPerson.PersonId; int? personAliasId = ppGroupMemberPerson.PersonAliasId; if ( !personId.HasValue || !personAliasId.HasValue ) { nbErrorMessage.Title = "Please select a Person"; return; } // check to see if the user selected a role var role = new GroupTypeRoleService( rockContext ).Get( ddlGroupRole.SelectedValueAsInt() ?? 0 ); if ( role == null ) { nbErrorMessage.Title = "Please select a Role"; return; } var groupMemberService = new GroupMemberService( rockContext ); var groupMemberRequirementService = new GroupMemberRequirementService( rockContext ); GroupMember groupMember; int groupMemberId = int.Parse( hfGroupMemberId.Value ); // if adding a new group member if ( groupMemberId.Equals( 0 ) ) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = group.Id; } else { // load existing group member groupMember = groupMemberService.Get( groupMemberId ); } groupMember.PersonId = personId.Value; groupMember.GroupRoleId = role.Id; groupMember.Note = tbNote.Text; groupMember.GroupMemberStatus = rblStatus.SelectedValueAsEnum<GroupMemberStatus>(); if ( cbIsNotified.Visible ) { groupMember.IsNotified = cbIsNotified.Checked; } if ( pnlRequirements.Visible ) { foreach ( var checkboxItem in cblManualRequirements.Items.OfType<ListItem>() ) { int groupRequirementId = checkboxItem.Value.AsInteger(); var groupMemberRequirement = groupMember.GroupMemberRequirements.FirstOrDefault( a => a.GroupRequirementId == groupRequirementId ); bool metRequirement = checkboxItem.Selected; if ( metRequirement ) { if ( groupMemberRequirement == null ) { groupMemberRequirement = new GroupMemberRequirement(); groupMemberRequirement.GroupRequirementId = groupRequirementId; groupMember.GroupMemberRequirements.Add( groupMemberRequirement ); } // set the RequirementMetDateTime if it hasn't been set already groupMemberRequirement.RequirementMetDateTime = groupMemberRequirement.RequirementMetDateTime ?? RockDateTime.Now; groupMemberRequirement.LastRequirementCheckDateTime = RockDateTime.Now; } else { if ( groupMemberRequirement != null ) { // doesn't meets the requirement groupMemberRequirement.RequirementMetDateTime = null; groupMemberRequirement.LastRequirementCheckDateTime = RockDateTime.Now; } } } } if ( group.RequiredSignatureDocumentTemplate != null ) { var person = new PersonService( rockContext ).Get( personId.Value ); var documentService = new SignatureDocumentService( rockContext ); var binaryFileService = new BinaryFileService( rockContext ); SignatureDocument document = null; int? signatureDocumentId = hfSignedDocumentId.Value.AsIntegerOrNull(); int? binaryFileId = fuSignedDocument.BinaryFileId; if ( signatureDocumentId.HasValue ) { document = documentService.Get( signatureDocumentId.Value ); } if ( document == null && binaryFileId.HasValue ) { document = new SignatureDocument(); document.SignatureDocumentTemplateId = group.RequiredSignatureDocumentTemplate.Id; document.AppliesToPersonAliasId = personAliasId.Value; document.AssignedToPersonAliasId = personAliasId.Value; document.Name = string.Format( "{0}_{1}", group.Name.RemoveSpecialCharacters(), ( person != null ? person.FullName.RemoveSpecialCharacters() : string.Empty ) ); document.Status = SignatureDocumentStatus.Signed; document.LastStatusDate = RockDateTime.Now; documentService.Add( document ); } if ( document != null ) { int? origBinaryFileId = document.BinaryFileId; document.BinaryFileId = binaryFileId; if ( origBinaryFileId.HasValue && origBinaryFileId.Value != document.BinaryFileId ) { // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up var oldBinaryFile = binaryFileService.Get( origBinaryFileId.Value ); if ( oldBinaryFile != null && !oldBinaryFile.IsTemporary ) { oldBinaryFile.IsTemporary = true; } } // ensure the IsTemporary is set to false on binaryFile associated with this document if ( document.BinaryFileId.HasValue ) { var binaryFile = binaryFileService.Get( document.BinaryFileId.Value ); if ( binaryFile != null && binaryFile.IsTemporary ) { binaryFile.IsTemporary = false; } } } } groupMember.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phAttributes, groupMember ); if ( !Page.IsValid ) { return; } // if the groupMember IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass. // So, make sure a message is displayed in the validation summary cvGroupMember.IsValid = groupMember.IsValid; if ( !cvGroupMember.IsValid ) { cvGroupMember.ErrorMessage = groupMember.ValidationResults.Select( a => a.ErrorMessage ).ToList().AsDelimited( "<br />" ); return; } // using WrapTransaction because there are three Saves rockContext.WrapTransaction( () => { if ( groupMember.Id.Equals( 0 ) ) { groupMemberService.Add( groupMember ); } rockContext.SaveChanges(); groupMember.SaveAttributeValues( rockContext ); } ); groupMember.CalculateRequirements( rockContext, true ); if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) { Rock.Security.Role.Flush( group.Id ); } } }
/// <summary> /// Handles the Click event of the btnMoveGroupMember 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 btnMoveGroupMember_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); var groupMemberService = new GroupMemberService( rockContext ); var groupMember = groupMemberService.Get( hfGroupMemberId.Value.AsInteger() ); groupMember.LoadAttributes(); int destGroupId = gpMoveGroupMember.SelectedValue.AsInteger(); var destGroup = new GroupService( rockContext ).Get( destGroupId ); var destGroupMember = groupMemberService.Queryable().Where( a => a.GroupId == destGroupId && a.PersonId == groupMember.PersonId && a.GroupRoleId == grpMoveGroupMember.GroupRoleId ).FirstOrDefault(); if ( destGroupMember != null ) { nbMoveGroupMemberWarning.Visible = true; nbMoveGroupMemberWarning.Text = string.Format( "{0} is already in {1}", groupMember.Person, destGroupMember.Group ); return; } if ( !grpMoveGroupMember.GroupRoleId.HasValue ) { nbMoveGroupMemberWarning.Visible = true; nbMoveGroupMemberWarning.Text = string.Format( "Please select a Group Role" ); return; } string canDeleteWarning; if ( !groupMemberService.CanDelete( groupMember, out canDeleteWarning ) ) { nbMoveGroupMemberWarning.Visible = true; nbMoveGroupMemberWarning.Text = string.Format( "Unable to remove {0} from {1}: {2}", groupMember.Person, groupMember.Group, canDeleteWarning ); return; } destGroupMember = new GroupMember(); destGroupMember.GroupId = destGroupId; destGroupMember.GroupRoleId = grpMoveGroupMember.GroupRoleId.Value; destGroupMember.PersonId = groupMember.PersonId; destGroupMember.LoadAttributes(); foreach ( var attribute in groupMember.Attributes ) { if ( destGroupMember.Attributes.Any( a => a.Key == attribute.Key && a.Value.FieldTypeId == attribute.Value.FieldTypeId ) ) { destGroupMember.SetAttributeValue( attribute.Key, groupMember.GetAttributeValue( attribute.Key ) ); } } rockContext.WrapTransaction( () => { groupMemberService.Add( destGroupMember ); rockContext.SaveChanges(); destGroupMember.SaveAttributeValues( rockContext ); // move any Note records that were associated with the old groupMember to the new groupMember record if ( cbMoveGroupMemberMoveNotes.Checked ) { destGroupMember.Note = groupMember.Note; int groupMemberEntityTypeId = EntityTypeCache.GetId<Rock.Model.GroupMember>().Value; var noteService = new NoteService( rockContext ); var groupMemberNotes = noteService.Queryable().Where( a => a.NoteType.EntityTypeId == groupMemberEntityTypeId && a.EntityId == groupMember.Id ); foreach ( var note in groupMemberNotes ) { note.EntityId = destGroupMember.Id; } rockContext.SaveChanges(); } groupMemberService.Delete( groupMember ); rockContext.SaveChanges(); destGroupMember.CalculateRequirements( rockContext, true ); } ); var queryString = new Dictionary<string, string>(); queryString.Add( "GroupMemberId", destGroupMember.Id.ToString() ); this.NavigateToPage( this.RockPage.Guid, queryString ); }
/// <summary> /// Handles the ItemCommand event of the rGroupMembers control. /// </summary> /// <param name="source">The source of the event.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param> protected void rGroupMembers_ItemCommand( object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e ) { if ( CanEdit ) { int groupMemberId = e.CommandArgument.ToString().AsIntegerOrNull() ?? 0; if ( groupMemberId != 0 ) { var rockContext = new RockContext(); var service = new GroupMemberService( rockContext ); var groupMember = service.Get( groupMemberId ); if ( groupMember != null ) { if ( e.CommandName == "EditRole" ) { ShowModal( groupMember.Person, groupMember.GroupRoleId, groupMemberId ); } else if ( e.CommandName == "RemoveRole" ) { if ( IsKnownRelationships ) { var inverseGroupMember = service.GetInverseRelationship( groupMember, false ); if ( inverseGroupMember != null ) { service.Delete( inverseGroupMember ); } } service.Delete( groupMember ); rockContext.SaveChanges(); BindData(); } } } } }
private void DisplayEditGroupMember( int groupMemberId ) { // persist the group member id for use in partial postbacks this.CurrentGroupMemberId = groupMemberId; pnlGroupEdit.Visible = false; pnlGroupView.Visible = false; pnlEditGroupMember.Visible = true; RockContext rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); var groupMember = groupMemberService.Get( groupMemberId ); if ( groupMember == null ) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = _groupId; groupMember.Group = new GroupService( rockContext ).Get( groupMember.GroupId ); groupMember.GroupRoleId = groupMember.Group.GroupType.DefaultGroupRoleId ?? 0; groupMember.GroupMemberStatus = GroupMemberStatus.Active; } // load dropdowns LoadGroupMemberDropDowns( _groupId ); // set values ppGroupMemberPerson.SetValue( groupMember.Person ); ddlGroupRole.SetValue( groupMember.GroupRoleId ); rblStatus.SetValue( (int)groupMember.GroupMemberStatus ); // set attributes groupMember.LoadAttributes(); phGroupMemberAttributes.Controls.Clear(); Rock.Attribute.Helper.AddEditControls( groupMember, phGroupMemberAttributes, true, "", true ); this.IsEditingGroupMember = true; }
/// <summary> /// Displays the edit group member. /// </summary> /// <param name="groupMemberId">The group member identifier.</param> private void DisplayEditGroupMember( int groupMemberId ) { // persist the group member id for use in partial postbacks this.CurrentGroupMemberId = groupMemberId; pnlGroupEdit.Visible = false; pnlGroupView.Visible = false; pnlEditGroupMember.Visible = true; RockContext rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); var groupMember = groupMemberService.Get( groupMemberId ); if ( groupMember == null ) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = _groupId; groupMember.Group = new GroupService( rockContext ).Get( groupMember.GroupId ); groupMember.GroupRoleId = groupMember.Group.GroupType.DefaultGroupRoleId ?? 0; groupMember.GroupMemberStatus = GroupMemberStatus.Active; } // load dropdowns LoadGroupMemberDropDowns( _groupId ); // set values ppGroupMemberPerson.SetValue( groupMember.Person ); ddlGroupRole.SetValue( groupMember.GroupRoleId ); rblStatus.SetValue( (int)groupMember.GroupMemberStatus ); bool hideGroupMemberInactiveStatus = this.GetAttributeValue( "HideInactiveGroupMemberStatus" ).AsBooleanOrNull() ?? false; if ( hideGroupMemberInactiveStatus ) { var inactiveItem = rblStatus.Items.FindByValue( ( (int)GroupMemberStatus.Inactive ).ToString() ); if ( inactiveItem != null ) { rblStatus.Items.Remove( inactiveItem ); } } // set attributes groupMember.LoadAttributes(); phGroupMemberAttributes.Controls.Clear(); Rock.Attribute.Helper.AddEditControls( groupMember, phGroupMemberAttributes, true, string.Empty, true ); this.IsEditingGroupMember = true; }
/// <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 ( Page.IsValid ) { var rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); GroupMemberRequirementService groupMemberRequirementService = new GroupMemberRequirementService( rockContext ); GroupMember groupMember; int groupMemberId = int.Parse( hfGroupMemberId.Value ); GroupTypeRole role = new GroupTypeRoleService( rockContext ).Get( ddlGroupRole.SelectedValueAsInt() ?? 0 ); // check to see if the user selected a role if ( role == null ) { nbErrorMessage.Title = "Please select a Role"; return; } // if adding a new group member if ( groupMemberId.Equals( 0 ) ) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = hfGroupId.ValueAsInt(); } else { // load existing group member groupMember = groupMemberService.Get( groupMemberId ); } groupMember.PersonId = ppGroupMemberPerson.PersonId.Value; groupMember.GroupRoleId = role.Id; groupMember.Note = tbNote.Text; groupMember.GroupMemberStatus = rblStatus.SelectedValueAsEnum<GroupMemberStatus>(); if ( cbIsNotified.Visible ) { groupMember.IsNotified = cbIsNotified.Checked; } if ( pnlRequirements.Visible ) { foreach ( var checkboxItem in cblManualRequirements.Items.OfType<ListItem>() ) { int groupRequirementId = checkboxItem.Value.AsInteger(); var groupMemberRequirement = groupMember.GroupMemberRequirements.FirstOrDefault( a => a.GroupRequirementId == groupRequirementId ); bool metRequirement = checkboxItem.Selected; if ( metRequirement ) { if ( groupMemberRequirement == null ) { groupMemberRequirement = new GroupMemberRequirement(); groupMemberRequirement.GroupRequirementId = groupRequirementId; groupMember.GroupMemberRequirements.Add( groupMemberRequirement ); } // set the RequirementMetDateTime if it hasn't been set already groupMemberRequirement.RequirementMetDateTime = groupMemberRequirement.RequirementMetDateTime ?? RockDateTime.Now; groupMemberRequirement.LastRequirementCheckDateTime = RockDateTime.Now; } else { if ( groupMemberRequirement != null ) { // doesn't meets the requirement groupMemberRequirement.RequirementMetDateTime = null; groupMemberRequirement.LastRequirementCheckDateTime = RockDateTime.Now; } } } } groupMember.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phAttributes, groupMember ); if ( !Page.IsValid ) { return; } // if the groupMember IsValue is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass. // So, make sure a message is displayed in the validation summary cvGroupMember.IsValid = groupMember.IsValid; if ( !cvGroupMember.IsValid ) { cvGroupMember.ErrorMessage = groupMember.ValidationResults.Select( a => a.ErrorMessage ).ToList().AsDelimited( "<br />" ); return; } // using WrapTransaction because there are three Saves rockContext.WrapTransaction( () => { if ( groupMember.Id.Equals( 0 ) ) { groupMemberService.Add( groupMember ); } rockContext.SaveChanges(); groupMember.SaveAttributeValues( rockContext ); } ); groupMember.CalculateRequirements( rockContext, true ); Group group = new GroupService( rockContext ).Get( groupMember.GroupId ); if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) { Rock.Security.Role.Flush( group.Id ); Rock.Security.Authorization.Flush(); } } Dictionary<string, string> qryString = new Dictionary<string, string>(); qryString["GroupId"] = hfGroupId.Value; NavigateToParentPage( qryString ); }
/// <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 ) { ClearErrorMessage(); if ( Page.IsValid ) { var rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); GroupMember groupMember; int groupMemberId = int.Parse( hfGroupMemberId.Value ); GroupTypeRole role = new GroupTypeRoleService( rockContext ).Get( ddlGroupRole.SelectedValueAsInt() ?? 0 ); // check to see if the user selected a role if ( role == null ) { nbErrorMessage.Title = "Please select a Role"; return; } // if adding a new group member if ( groupMemberId.Equals( 0 ) ) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = hfGroupId.ValueAsInt(); // check to see if the person is alread a member of the gorup/role var existingGroupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId( hfGroupId.ValueAsInt(), ppGroupMemberPerson.SelectedValue ?? 0, ddlGroupRole.SelectedValueAsId() ?? 0 ); if ( existingGroupMember != null ) { // if so, don't add and show error message var person = new PersonService( rockContext ).Get( (int)ppGroupMemberPerson.PersonId ); nbErrorMessage.Title = "Person already added"; nbErrorMessage.Text = string.Format( "{0} already belongs to the {1} role for this {2}, and cannot be added again with the same role. <a href=\"/page/{3}?groupMemberId={4}\">Click here</a> to view existing membership.", person.FullName, ddlGroupRole.SelectedItem.Text, role.GroupType.GroupTerm, RockPage.PageId, existingGroupMember.Id ); return; } } else { // load existing group member groupMember = groupMemberService.Get( groupMemberId ); } int memberCountInRole = new GroupMemberService( rockContext ).Queryable() .Where( m => m.GroupId == groupMember.GroupId && m.GroupRoleId == role.Id && m.GroupMemberStatus == GroupMemberStatus.Active ) .Count(); bool roleMembershipAboveMax = false; // if adding new active group member.. if ( groupMemberId.Equals( 0 ) && rblStatus.SelectedValueAsEnum<GroupMemberStatus>() == GroupMemberStatus.Active ) { // verify that active count has not exceeded the max if ( role.MaxCount != null && ( memberCountInRole + 1 ) > role.MaxCount ) { roleMembershipAboveMax = true; } } else if ( groupMemberId > 0 && ( groupMember.GroupRoleId != role.Id || groupMember.GroupMemberStatus != rblStatus.SelectedValueAsEnum<GroupMemberStatus>() ) && rblStatus.SelectedValueAsEnum<GroupMemberStatus>() == GroupMemberStatus.Active ) { // if existing group member changing role or status.. // verify that active count has not exceeded the max if ( role.MaxCount != null && ( memberCountInRole + 1 ) > role.MaxCount ) { roleMembershipAboveMax = true; } } // show error if above max.. do not proceed if ( roleMembershipAboveMax ) { var person = new PersonService( rockContext ).Get( (int)ppGroupMemberPerson.PersonId ); nbErrorMessage.Title = string.Format( "Maximum {0} Exceeded", role.Name.Pluralize() ); nbErrorMessage.Text = string.Format( "<br />The number of {0} for this {1} is at or above its maximum allowed limit of {2:N0} active {3}.", role.Name.Pluralize(), role.GroupType.GroupTerm, role.MaxCount, role.MaxCount == 1 ? role.GroupType.GroupMemberTerm : role.GroupType.GroupMemberTerm.Pluralize() ); return; } groupMember.PersonId = ppGroupMemberPerson.PersonId.Value; groupMember.GroupRoleId = role.Id; groupMember.GroupMemberStatus = rblStatus.SelectedValueAsEnum<GroupMemberStatus>(); groupMember.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phAttributes, groupMember ); if ( !Page.IsValid ) { return; } if ( !groupMember.IsValid ) { return; } // using WrapTransaction because there are two Saves RockTransactionScope.WrapTransaction( () => { if ( groupMember.Id.Equals( 0 ) ) { groupMemberService.Add( groupMember ); } groupMember.SaveAttributeValues( rockContext ); rockContext.SaveChanges(); } ); Group group = new GroupService( rockContext ).Get( groupMember.GroupId ); if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) { Rock.Security.Role.Flush( group.Id ); Rock.Security.Authorization.Flush(); } } Dictionary<string, string> qryString = new Dictionary<string, string>(); qryString["GroupId"] = hfGroupId.Value; NavigateToParentPage( qryString ); }
/// <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 ( Page.IsValid ) { var rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); GroupMember groupMember; int groupMemberId = int.Parse( hfGroupMemberId.Value ); GroupTypeRole role = new GroupTypeRoleService( rockContext ).Get( ddlGroupRole.SelectedValueAsInt() ?? 0 ); // check to see if the user selected a role if ( role == null ) { nbErrorMessage.Title = "Please select a Role"; return; } // if adding a new group member if ( groupMemberId.Equals( 0 ) ) { groupMember = new GroupMember { Id = 0 }; groupMember.GroupId = hfGroupId.ValueAsInt(); } else { // load existing group member groupMember = groupMemberService.Get( groupMemberId ); } groupMember.PersonId = ppGroupMemberPerson.PersonId.Value; groupMember.GroupRoleId = role.Id; groupMember.GroupMemberStatus = rblStatus.SelectedValueAsEnum<GroupMemberStatus>(); groupMember.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phAttributes, groupMember ); if ( !Page.IsValid ) { return; } cvGroupMember.IsValid = groupMember.IsValid; if ( !cvGroupMember.IsValid ) { cvGroupMember.ErrorMessage = groupMember.ValidationResults.Select( a => a.ErrorMessage ).ToList().AsDelimited( "<br />" ); return; } // using WrapTransaction because there are two Saves rockContext.WrapTransaction( () => { if ( groupMember.Id.Equals( 0 ) ) { groupMemberService.Add( groupMember ); } rockContext.SaveChanges(); groupMember.SaveAttributeValues( rockContext ); } ); Group group = new GroupService( rockContext ).Get( groupMember.GroupId ); if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) { Rock.Security.Role.Flush( group.Id ); Rock.Security.Authorization.Flush(); } } Dictionary<string, string> qryString = new Dictionary<string, string>(); qryString["GroupId"] = hfGroupId.Value; NavigateToParentPage( qryString ); }
void rGroupMembers_ItemCommand( object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e ) { int groupMemberId = int.MinValue; if ( int.TryParse( e.CommandArgument.ToString(), out groupMemberId ) ) { var rockContext = new RockContext(); var service = new GroupMemberService( rockContext ); var groupMember = service.Get( groupMemberId ); if ( groupMember != null ) { if ( e.CommandName == "EditRole" ) { ShowModal(groupMember.Person, groupMember.GroupRoleId, groupMemberId); } else if ( e.CommandName == "RemoveRole" ) { if ( IsKnownRelationships ) { var inverseGroupMember = service.GetInverseRelationship( groupMember, false, CurrentPersonAlias ); if ( inverseGroupMember != null ) { service.Delete( inverseGroupMember ); } } service.Delete( groupMember ); rockContext.SaveChanges(); BindData(); } } } }
/// <summary> /// Handles the Click event of the DeleteGroupMember control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs" /> instance containing the event data.</param> protected void DeleteGroupMember_Click( object sender, Rock.Web.UI.Controls.RowEventArgs e ) { RockContext rockContext = new RockContext(); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); GroupMember groupMember = groupMemberService.Get( e.RowKeyId ); if ( groupMember != null ) { string errorMessage; if ( !groupMemberService.CanDelete( groupMember, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } int groupId = groupMember.GroupId; groupMemberService.Delete( groupMember ); rockContext.SaveChanges(); Group group = new GroupService( rockContext ).Get( groupId ); if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) { // person removed from SecurityRole, Flush Rock.Security.Role.Flush( group.Id ); Rock.Security.Authorization.Flush(); } } BindGroupMembersGrid(); }
/// <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 ( string.IsNullOrWhiteSpace( txtFirstName.Text ) || string.IsNullOrWhiteSpace( txtLastName.Text ) || string.IsNullOrWhiteSpace( txtEmail.Text ) ) { ShowError( "Missing Information", "Please enter a value for First Name, Last Name, and Email" ); } else { var rockContext = new RockContext(); var person = GetPerson( rockContext ); if ( person != null ) { Guid? groupGuid = GetAttributeValue( "Group" ).AsGuidOrNull(); if ( groupGuid.HasValue ) { var groupService = new GroupService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); var group = groupService.Get( groupGuid.Value ); if ( group != null && group.GroupType.DefaultGroupRoleId.HasValue ) { string linkedPage = GetAttributeValue( "ConfirmationPage" ); if ( !string.IsNullOrWhiteSpace( linkedPage ) ) { var member = group.Members.Where( m => m.PersonId == person.Id ).FirstOrDefault(); // If person has not registered or confirmed their registration if ( member == null || member.GroupMemberStatus != GroupMemberStatus.Active ) { Guid confirmationEmailTemplateGuid = Guid.Empty; if ( !Guid.TryParse( GetAttributeValue( "ConfirmationEmail" ), out confirmationEmailTemplateGuid ) ) { confirmationEmailTemplateGuid = Guid.Empty; } if ( member == null ) { member = new GroupMember(); member.GroupId = group.Id; member.PersonId = person.Id; member.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value; // If a confirmation email is configured, set status to Pending otherwise set it to active member.GroupMemberStatus = confirmationEmailTemplateGuid != Guid.Empty ? GroupMemberStatus.Pending : GroupMemberStatus.Active; groupMemberService.Add( member ); rockContext.SaveChanges(); member = groupMemberService.Get( member.Id ); } // Send the confirmation if ( confirmationEmailTemplateGuid != Guid.Empty ) { var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson ); mergeFields.Add( "Member", member ); var pageParams = new Dictionary<string, string>(); pageParams.Add( "gm", member.UrlEncodedKey ); var pageReference = new Rock.Web.PageReference( linkedPage, pageParams ); mergeFields.Add( "ConfirmationPage", pageReference.BuildUrl() ); var recipients = new List<RecipientData>(); recipients.Add( new RecipientData( person.Email, mergeFields ) ); Email.Send( confirmationEmailTemplateGuid, recipients, ResolveRockUrl( "~/" ), ResolveRockUrl( "~~/" ) ); } ShowSuccess( GetAttributeValue( "SuccessMessage" ) ); } else { var pageParams = new Dictionary<string, string>(); pageParams.Add( "gm", member.UrlEncodedKey ); var pageReference = new Rock.Web.PageReference( linkedPage, pageParams ); Response.Redirect( pageReference.BuildUrl(), false ); } } else { ShowError( "Configuration Error", "Invalid Confirmation Page setting" ); } } else { ShowError( "Configuration Error", "The configured group does not exist, or it's group type does not have a default role configured." ); } } else { ShowError( "Configuration Error", "Invalid Group setting" ); } } } }
/// <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 ) { // confirmation was disabled by btnSave on client-side. So if returning without a redirect, // it should be enabled. If returning with a redirect, the control won't be updated to reflect // confirmation being enabled, so it's ok to enable it here confirmExit.Enabled = true; if ( Page.IsValid ) { confirmExit.Enabled = true; RockTransactionScope.WrapTransaction( () => { var rockContext = new RockContext(); var familyService = new GroupService( rockContext ); var familyMemberService = new GroupMemberService( rockContext ); var personService = new PersonService( rockContext ); var historyService = new HistoryService( rockContext ); var familyChanges = new List<string>(); // SAVE FAMILY _family = familyService.Get( _family.Id ); History.EvaluateChange( familyChanges, "Family Name", _family.Name, tbFamilyName.Text ); _family.Name = tbFamilyName.Text; int? campusId = cpCampus.SelectedValueAsInt(); if ( _family.CampusId != campusId ) { History.EvaluateChange( familyChanges, "Campus", _family.CampusId.HasValue ? CampusCache.Read( _family.CampusId.Value ).Name : string.Empty, campusId.HasValue ? CampusCache.Read( campusId.Value ).Name : string.Empty ); _family.CampusId = campusId; } var familyGroupTypeId = _family.GroupTypeId; rockContext.SaveChanges(); // SAVE FAMILY MEMBERS int? recordStatusValueID = ddlRecordStatus.SelectedValueAsInt(); int? reasonValueId = ddlReason.SelectedValueAsInt(); var newFamilies = new List<Group>(); foreach ( var familyMember in FamilyMembers ) { var memberChanges = new List<string>(); var demographicChanges = new List<string>(); var role = familyRoles.Where( r => r.Guid.Equals( familyMember.RoleGuid ) ).FirstOrDefault(); if ( role == null ) { role = familyRoles.FirstOrDefault(); } bool isChild = role != null && role.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ); // People added to family (new or from other family) if ( !familyMember.ExistingFamilyMember ) { var groupMember = new GroupMember(); if ( familyMember.Id == -1 ) { // added new person demographicChanges.Add( "Created" ); var person = new Person(); person.FirstName = familyMember.FirstName; person.NickName = familyMember.NickName; History.EvaluateChange( demographicChanges, "First Name", string.Empty, person.FirstName ); person.LastName = familyMember.LastName; History.EvaluateChange( demographicChanges, "Last Name", string.Empty, person.LastName ); person.Gender = familyMember.Gender; History.EvaluateChange( demographicChanges, "Gender", null, person.Gender ); person.BirthDate = familyMember.BirthDate; History.EvaluateChange( demographicChanges, "Birth Date", null, person.BirthDate ); if ( !isChild ) { person.GivingGroupId = _family.Id; History.EvaluateChange( demographicChanges, "Giving Group", string.Empty, _family.Name ); } person.EmailPreference = EmailPreference.EmailAllowed; groupMember.Person = person; } else { // added from other family groupMember.Person = personService.Get( familyMember.Id ); } if ( recordStatusValueID > 0 ) { History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) ); groupMember.Person.RecordStatusValueId = recordStatusValueID; History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) ); groupMember.Person.RecordStatusReasonValueId = reasonValueId; } groupMember.GroupId = _family.Id; if ( role != null ) { History.EvaluateChange( memberChanges, "Role", string.Empty, role.Name ); groupMember.GroupRoleId = role.Id; } if ( groupMember.Person != null ) { familyMemberService.Add( groupMember ); rockContext.SaveChanges(); familyMember.Id = groupMember.Person.Id; } } else { // existing family members var groupMember = familyMemberService.Queryable( "Person" ).Where( m => m.PersonId == familyMember.Id && m.Group.GroupTypeId == familyGroupTypeId && m.GroupId == _family.Id ).FirstOrDefault(); if ( groupMember != null ) { if ( familyMember.Removed ) { var newFamilyChanges = new List<string>(); // Family member was removed and should be created in their own new family var newFamily = new Group(); newFamily.Name = familyMember.LastName + " Family"; History.EvaluateChange( newFamilyChanges, "Family", string.Empty, newFamily.Name ); newFamily.GroupTypeId = familyGroupTypeId; if ( _family.CampusId.HasValue ) { History.EvaluateChange( newFamilyChanges, "Campus", string.Empty, CampusCache.Read( _family.CampusId.Value ).Name ); } newFamily.CampusId = _family.CampusId; familyService.Add( newFamily ); rockContext.SaveChanges(); // If person's previous giving group was this family, set it to their new family id if ( groupMember.Person.GivingGroup != null && groupMember.Person.GivingGroupId == _family.Id ) { History.EvaluateChange( demographicChanges, "Giving Group", groupMember.Person.GivingGroup.Name, _family.Name ); groupMember.Person.GivingGroupId = newFamily.Id; } groupMember.Group = newFamily; rockContext.SaveChanges(); var newMemberChanges = new List<string>(); History.EvaluateChange( newMemberChanges, "Role", string.Empty, groupMember.GroupRole.Name ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), groupMember.Person.Id, newFamilyChanges, newFamily.Name, typeof( Group ), newFamily.Id ); newFamilies.Add( newFamily ); History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole.Name, string.Empty ); } else { // Existing member was not remvoved if ( role != null ) { History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole != null ? groupMember.GroupRole.Name : string.Empty, role.Name ); groupMember.GroupRoleId = role.Id; if ( recordStatusValueID > 0 ) { History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) ); groupMember.Person.RecordStatusValueId = recordStatusValueID; History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) ); groupMember.Person.RecordStatusReasonValueId = reasonValueId; } rockContext.SaveChanges(); } } } } // Remove anyone that was moved from another family if ( familyMember.RemoveFromOtherFamilies ) { var otherFamilies = familyMemberService.Queryable() .Where( m => m.PersonId == familyMember.Id && m.Group.GroupTypeId == familyGroupTypeId && m.GroupId != _family.Id ) .ToList(); foreach ( var otherFamilyMember in otherFamilies ) { var fm = familyMemberService.Get( otherFamilyMember.Id ); // If the person's giving group id was the family they are being removed from, update it to this new family's id if ( fm.Person.GivingGroupId == fm.GroupId ) { var person = personService.Get( fm.PersonId ); History.EvaluateChange( demographicChanges, "Giving Group", person.GivingGroup.Name, _family.Name ); person.GivingGroupId = _family.Id; rockContext.SaveChanges(); } var oldMemberChanges = new List<string>(); History.EvaluateChange( oldMemberChanges, "Role", fm.GroupRole.Name, string.Empty ); History.EvaluateChange( oldMemberChanges, "Family", fm.Group.Name, string.Empty ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.Person.Id, oldMemberChanges, fm.Group.Name, typeof( Group ), fm.Group.Id ); familyMemberService.Delete( fm ); rockContext.SaveChanges(); var f = familyService.Queryable() .Where( g => g.Id == otherFamilyMember.GroupId && !g.Members.Any() ) .FirstOrDefault(); if ( f != null ) { familyService.Delete( f ); rockContext.SaveChanges(); } } } HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), familyMember.Id, demographicChanges ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), familyMember.Id, memberChanges, _family.Name, typeof( Group ), _family.Id ); } // SAVE LOCATIONS var groupLocationService = new GroupLocationService( rockContext ); // delete any group locations that were removed var remainingLocationIds = FamilyAddresses.Where( a => a.Id > 0 ).Select( a => a.Id ).ToList(); foreach ( var removedLocation in groupLocationService.Queryable( "GroupLocationTypeValue,Location" ) .Where( l => l.GroupId == _family.Id && !remainingLocationIds.Contains( l.Id ) ) ) { History.EvaluateChange( familyChanges, removedLocation.GroupLocationTypeValue.Name + " Location", removedLocation.Location.ToString(), string.Empty ); groupLocationService.Delete( removedLocation ); } rockContext.SaveChanges(); foreach ( var familyAddress in FamilyAddresses ) { Location updatedAddress = null; if ( familyAddress.LocationIsDirty ) { updatedAddress = new LocationService( rockContext ).Get( familyAddress.Street1, familyAddress.Street2, familyAddress.City, familyAddress.State, familyAddress.Zip ); } GroupLocation groupLocation = null; if ( familyAddress.Id > 0 ) { groupLocation = groupLocationService.Get( familyAddress.Id ); } if ( groupLocation == null ) { groupLocation = new GroupLocation(); groupLocation.GroupId = _family.Id; groupLocationService.Add( groupLocation ); } History.EvaluateChange( familyChanges, "Location Type", groupLocation.GroupLocationTypeValueId.HasValue ? DefinedValueCache.Read( groupLocation.GroupLocationTypeValueId.Value ).Name : string.Empty, familyAddress.LocationTypeName ); groupLocation.GroupLocationTypeValueId = familyAddress.LocationTypeId; History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Is Mailing", groupLocation.IsMailingLocation.ToString(), familyAddress.IsMailing.ToString() ); groupLocation.IsMailingLocation = familyAddress.IsMailing; History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Is Map Location", groupLocation.IsMappedLocation.ToString(), familyAddress.IsLocation.ToString() ); groupLocation.IsMappedLocation = familyAddress.IsLocation; if ( updatedAddress != null ) { History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Location", groupLocation.Location != null ? groupLocation.Location.ToString() : "", updatedAddress.ToString() ); groupLocation.Location = updatedAddress; } rockContext.SaveChanges(); // Add the same locations to any new families created by removing an existing family member if ( newFamilies.Any() ) { //reload grouplocation for access to child properties groupLocation = groupLocationService.Get( groupLocation.Id ); foreach ( var newFamily in newFamilies ) { var newFamilyLocation = new GroupLocation(); newFamilyLocation.GroupId = newFamily.Id; newFamilyLocation.LocationId = groupLocation.LocationId; newFamilyLocation.GroupLocationTypeValueId = groupLocation.GroupLocationTypeValueId; newFamilyLocation.IsMailingLocation = groupLocation.IsMailingLocation; newFamilyLocation.IsMappedLocation = groupLocation.IsMappedLocation; groupLocationService.Add( newFamilyLocation ); } rockContext.SaveChanges(); } } foreach ( var fm in _family.Members ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.PersonId, familyChanges, _family.Name, typeof( Group ), _family.Id ); } _family = familyService.Get( _family.Id ); if ( _family.Members.Any( m => m.PersonId == Person.Id ) ) { Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false ); } else { var fm = _family.Members .Where( m => m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) && m.Person.Gender == Gender.Male ) .OrderByDescending( m => m.Person.Age ) .FirstOrDefault(); if ( fm == null ) { fm = _family.Members .Where( m => m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) ) .OrderByDescending( m => m.Person.Age ) .FirstOrDefault(); } if ( fm == null ) { fm = _family.Members .OrderByDescending( m => m.Person.Age ) .FirstOrDefault(); } if ( fm != null ) { Response.Redirect( string.Format( "~/Person/{0}", fm.PersonId ), false ); } else { Response.Redirect( "~", false ); } } } ); } }
protected void btnSave_Click( object sender, EventArgs e ) { if ( string.IsNullOrWhiteSpace( txtFirstName.Text ) || string.IsNullOrWhiteSpace( txtLastName.Text ) || string.IsNullOrWhiteSpace( txtEmail.Text ) ) { ShowError( "Missing Information", "Please enter a value for First Name, Last Name, and Email" ); } else { var person = GetPerson(); if ( person != null ) { int groupId = int.MinValue; if ( int.TryParse( GetAttributeValue( "Group" ), out groupId ) ) { using ( new UnitOfWorkScope() ) { var groupService = new GroupService(); var groupMemberService = new GroupMemberService(); var group = groupService.Get( groupId ); if ( group != null && group.GroupType.DefaultGroupRoleId.HasValue ) { string linkedPage = GetAttributeValue( "ConfirmationPage" ); if ( !string.IsNullOrWhiteSpace( linkedPage ) ) { var member = group.Members.Where( m => m.PersonId == person.Id ).FirstOrDefault(); // If person has not registered or confirmed their registration if ( member == null || member.GroupMemberStatus != GroupMemberStatus.Active ) { Email email = null; Guid guid = Guid.Empty; if ( Guid.TryParse( GetAttributeValue( "ConfirmationEmail" ), out guid ) ) { email = new Email( guid ); } if ( member == null ) { member = new GroupMember(); member.GroupId = group.Id; member.PersonId = person.Id; member.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value; // If a confirmation email is configured, set status to Pending otherwise set it to active member.GroupMemberStatus = email != null ? GroupMemberStatus.Pending : GroupMemberStatus.Active; groupMemberService.Add( member, CurrentPersonId ); groupMemberService.Save( member, CurrentPersonId ); member = groupMemberService.Get( member.Id ); } // Send the confirmation if ( email != null ) { var mergeObjects = new Dictionary<string, object>(); mergeObjects.Add( "Member", member ); var pageParams = new Dictionary<string, string>(); pageParams.Add( "gm", member.UrlEncodedKey ); var pageReference = new Rock.Web.PageReference( linkedPage, pageParams ); mergeObjects.Add( "ConfirmationPage", pageReference.BuildUrl() ); var recipients = new Dictionary<string, Dictionary<string, object>>(); recipients.Add( person.Email, mergeObjects ); email.Send( recipients ); } ShowSuccess( GetAttributeValue( "SuccessMessage" ) ); } else { var pageParams = new Dictionary<string, string>(); pageParams.Add( "gm", member.UrlEncodedKey ); var pageReference = new Rock.Web.PageReference( linkedPage, pageParams ); Response.Redirect( pageReference.BuildUrl(), false ); } } else { ShowError( "Configuration Error", "Invalid Confirmation Page setting" ); } } else { ShowError( "Configuration Error", "The configured group does not exist, or it's group type does not have a default role configured." ); } } } else { ShowError( "Configuration Error", "Invalid Group setting" ); } } } }