/// <summary> /// Adds the related person to the selected person's known relationships with a role of 'Can check in' which /// is typically configured to allow check-in. If an inverse relationship is configured for 'Can check in' /// (i.e. 'Allow check in by'), that relationship will also be created. /// </summary> /// <param name="personId">A <see cref="System.Int32"/> representing the Id of the Person.</param> /// <param name="relatedPersonId">A <see cref="System.Int32"/> representing the Id of the related Person.</param> /// <param name="currentPersonId">A <see cref="System.Int32"/> representing the Id of the Person who is logged in.</param> public static void CreateCheckinRelationship(int personId, int relatedPersonId, int?currentPersonId) { using (new UnitOfWorkScope()) { var groupMemberService = new GroupMemberService(); var knownRelationshipGroup = groupMemberService.Queryable() .Where(m => m.PersonId == personId && m.GroupRole.Guid.Equals(new Guid(SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER))) .Select(m => m.Group) .FirstOrDefault(); if (knownRelationshipGroup != null) { int?canCheckInRoleId = new GroupTypeRoleService().Queryable() .Where(r => r.Guid.Equals(new Guid(SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_CAN_CHECK_IN))) .Select(r => r.Id) .FirstOrDefault(); if (canCheckInRoleId.HasValue) { var canCheckInMember = groupMemberService.Queryable() .FirstOrDefault(m => m.GroupId == knownRelationshipGroup.Id && m.PersonId == relatedPersonId && m.GroupRoleId == canCheckInRoleId.Value); if (canCheckInMember == null) { canCheckInMember = new GroupMember(); canCheckInMember.GroupId = knownRelationshipGroup.Id; canCheckInMember.PersonId = relatedPersonId; canCheckInMember.GroupRoleId = canCheckInRoleId.Value; groupMemberService.Add(canCheckInMember, currentPersonId); groupMemberService.Save(canCheckInMember, currentPersonId); } var inverseGroupMember = groupMemberService.GetInverseRelationship(canCheckInMember, true, currentPersonId); if (inverseGroupMember != null) { groupMemberService.Save(inverseGroupMember, currentPersonId); } } } } }
/// <summary> /// Adds the group member. /// </summary> /// <param name="familyGroup">The family group.</param> /// <param name="person">The person.</param> /// <returns></returns> protected GroupMember AddGroupMember( int familyGroupId, Person person ) { var rockContext = new RockContext(); GroupMember groupMember = new GroupMember(); groupMember.IsSystem = false; groupMember.GroupId = familyGroupId; groupMember.PersonId = person.Id; if ( person.Age >= 18 ) { groupMember.GroupRoleId = new GroupTypeRoleService( rockContext ).Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ).Id; } else { groupMember.GroupRoleId = new GroupTypeRoleService( rockContext ).Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ).Id; } GroupMemberService groupMemberService = new GroupMemberService( rockContext ); groupMemberService.Add( groupMember ); rockContext.SaveChanges(); return groupMember; }
/// <summary> /// Saves the registration. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="hasPayment">if set to <c>true</c> [has payment].</param> /// <returns></returns> private Registration SaveRegistration( RockContext rockContext, bool hasPayment ) { var registrationService = new RegistrationService( rockContext ); var registrantService = new RegistrationRegistrantService( rockContext ); var personService = new PersonService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); // variables to keep track of the family that new people should be added to int? singleFamilyId = null; var multipleFamilyGroupIds = new Dictionary<Guid, int>(); var dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() ); var dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() ); var familyGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY ); var adultRoleId = familyGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); var childRoleId = familyGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); var registration = new Registration(); registrationService.Add( registration ); registration.RegistrationInstanceId = RegistrationInstanceState.Id; registration.GroupId = GroupId; registration.FirstName = RegistrationState.FirstName; registration.LastName = RegistrationState.LastName; registration.ConfirmationEmail = RegistrationState.ConfirmationEmail; registration.DiscountCode = RegistrationState.DiscountCode; registration.DiscountAmount = RegistrationState.DiscountAmount; registration.DiscountPercentage = RegistrationState.DiscountPercentage; // If the 'your name' value equals the currently logged in person, use their person alias id if ( CurrentPerson != null && ( CurrentPerson.NickName.Trim().Equals( registration.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) || CurrentPerson.FirstName.Trim().Equals( registration.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) ) && CurrentPerson.LastName.Trim().Equals( registration.LastName.Trim(), StringComparison.OrdinalIgnoreCase ) ) { registration.PersonAliasId = CurrentPerson.PrimaryAliasId; } else { // otherwise look for one and one-only match by name/email var personMatches = personService.GetByMatch( registration.FirstName, registration.LastName, registration.ConfirmationEmail ); if ( personMatches.Count() == 1 ) { registration.PersonAliasId = personMatches.First().PrimaryAliasId; } } // If the registration includes a payment, make sure there's an actual person associated to registration if ( hasPayment && !registration.PersonAliasId.HasValue ) { // If a match was not found, create a new person var person = new Person(); person.FirstName = registration.FirstName; person.LastName = registration.LastName; person.IsEmailActive = true; person.Email = registration.ConfirmationEmail; 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; } registration.PersonAliasId = SavePerson( rockContext, person, Guid.NewGuid(), null, null, adultRoleId, childRoleId, multipleFamilyGroupIds, singleFamilyId ); } // Save the registration ( so we can get an id ) rockContext.SaveChanges(); // If the Registration Instance linkage specified a group, load it now Group group = null; if ( GroupId.HasValue ) { group = new GroupService( rockContext ).Get( GroupId.Value ); } // Get each registrant foreach ( var registrantInfo in RegistrationState.Registrants ) { var changes = new List<string>(); var familyChanges = new List<string>(); Person person = null; // Try to find a matching person based on name and email address string firstName = registrantInfo.GetFirstName( RegistrationTemplate ); string lastName = registrantInfo.GetLastName( RegistrationTemplate ); string email = registrantInfo.GetEmail( RegistrationTemplate ); var personMatches = personService.GetByMatch( firstName, lastName, email ); if ( personMatches.Count() == 1 ) { person = personMatches.First(); } if ( person == null ) { // If a match was not found, create a new person person = new Person(); person.FirstName = firstName; person.LastName = lastName; person.IsEmailActive = true; person.Email = email; 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; } } int? campusId = null; Location location = null; // Set any of the template's person fields foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.PersonField ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value ) .FirstOrDefault(); if ( fieldValue != null ) { switch ( field.PersonFieldType ) { case RegistrationPersonFieldType.Campus: { if ( fieldValue != null ) { campusId = fieldValue.ToString().AsIntegerOrNull(); } break; } case RegistrationPersonFieldType.Address: { location = fieldValue.ToString().FromJsonOrNull<Location>(); break; } case RegistrationPersonFieldType.Birthdate: { var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; person.SetBirthDate( fieldValue as DateTime? ); History.EvaluateChange( changes, "Birth Month", birthMonth, person.BirthMonth ); History.EvaluateChange( changes, "Birth Day", birthDay, person.BirthDay ); History.EvaluateChange( changes, "Birth Year", birthYear, person.BirthYear ); break; } case RegistrationPersonFieldType.Gender: { var newGender = fieldValue.ToString().ConvertToEnumOrNull<Gender>() ?? Gender.Unknown; History.EvaluateChange( changes, "Gender", person.Gender, newGender ); person.Gender = newGender; break; } case RegistrationPersonFieldType.MaritalStatus: { if ( fieldValue != null ) { int? newMaritalStatusId = fieldValue.ToString().AsIntegerOrNull(); History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) ); person.MaritalStatusValueId = newMaritalStatusId; } break; } case RegistrationPersonFieldType.MobilePhone: { SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(), changes ); break; } case RegistrationPersonFieldType.HomePhone: { SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(), changes ); break; } case RegistrationPersonFieldType.WorkPhone: { SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK.AsGuid(), changes ); break; } } } } // Save the person ( and family if needed ) SavePerson( rockContext, person, registrantInfo.FamilyGuid, campusId, location, adultRoleId, childRoleId, multipleFamilyGroupIds, singleFamilyId ); // Load the person's attributes person.LoadAttributes(); // Set any of the template's person fields foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.PersonAttribute && t.AttributeId.HasValue ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value ) .FirstOrDefault(); if ( fieldValue != null ) { var attribute = AttributeCache.Read( field.AttributeId.Value ); if ( attribute != null ) { string originalValue = person.GetAttributeValue( attribute.Key ); string newValue = fieldValue.ToString(); person.SetAttributeValue( attribute.Key, fieldValue.ToString() ); if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() ) { string formattedOriginalValue = string.Empty; if ( !string.IsNullOrWhiteSpace( originalValue ) ) { formattedOriginalValue = attribute.FieldType.Field.FormatValue( null, originalValue, attribute.QualifierValues, false ); } string formattedNewValue = string.Empty; if ( !string.IsNullOrWhiteSpace( newValue ) ) { formattedNewValue = attribute.FieldType.Field.FormatValue( null, newValue, attribute.QualifierValues, false ); } History.EvaluateChange( changes, attribute.Name, formattedOriginalValue, formattedNewValue ); } } } } person.SaveAttributeValues( rockContext ); GroupMember groupMember = null; // If the registration instance linkage specified a group to add registrant to, add them if there not already // part of that group if ( group != null ) { groupMember = group.Members.Where( m => m.PersonId == person.Id ).FirstOrDefault(); if ( groupMember == null && group.GroupType.DefaultGroupRoleId.HasValue ) { groupMember = new GroupMember(); groupMemberService.Add( groupMember ); groupMember.GroupId = group.Id; groupMember.PersonId = person.Id; if ( RegistrationTemplate.GroupTypeId.HasValue && RegistrationTemplate.GroupTypeId == group.GroupTypeId && RegistrationTemplate.GroupMemberRoleId.HasValue ) { groupMember.GroupRoleId = RegistrationTemplate.GroupMemberRoleId.Value; groupMember.GroupMemberStatus = RegistrationTemplate.GroupMemberStatus; } else { groupMember.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value; groupMember.GroupMemberStatus = GroupMemberStatus.Active; } } rockContext.SaveChanges(); // Set any of the template's group member attributes groupMember.LoadAttributes(); foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.GroupMemberAttribute && t.AttributeId.HasValue ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value ) .FirstOrDefault(); if ( fieldValue != null ) { var attribute = AttributeCache.Read( field.AttributeId.Value ); if ( attribute != null ) { groupMember.SetAttributeValue( attribute.Key, fieldValue.ToString() ); } } } groupMember.SaveAttributeValues( rockContext ); } var registrant = new RegistrationRegistrant(); registrantService.Add( registrant ); registrant.RegistrationId = registration.Id; registrant.PersonAliasId = person.PrimaryAliasId; registrant.Cost = registrantInfo.Cost; registrant.GroupMemberId = groupMember != null ? groupMember.Id : (int?)null; // Add or Update fees foreach ( var feeValue in registrantInfo.FeeValues.Where( f => f.Value != null ) ) { foreach ( var uiFee in feeValue.Value ) { var fee = new RegistrationRegistrantFee(); registrant.Fees.Add( fee ); fee.RegistrationTemplateFeeId = feeValue.Key; fee.Option = uiFee.Option; fee.Quantity = uiFee.Quantity; fee.Cost = uiFee.Cost; } } rockContext.SaveChanges(); // Set any of the templat's registrant attributes registrant.LoadAttributes(); foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.RegistrationAttribute && t.AttributeId.HasValue ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value ) .FirstOrDefault(); if ( fieldValue != null ) { var attribute = AttributeCache.Read( field.AttributeId.Value ); if ( attribute != null ) { registrant.SetAttributeValue( attribute.Key, fieldValue.ToString() ); } } registrant.SaveAttributeValues( rockContext ); } } return registration; }
/// <summary> /// Loads the drop downs. /// </summary> private void LoadDropDowns( BenevolenceRequest benevolenceRequest ) { ddlRequestStatus.BindToDefinedType( DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.BENEVOLENCE_REQUEST_STATUS ) ), false ); ddlConnectionStatus.BindToDefinedType( DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS ) ), true ); Guid groupGuid = GetAttributeValue( "CaseWorkerRole" ).AsGuid(); var personList = new GroupMemberService( new RockContext() ) .Queryable( "Person, Group" ) .Where( gm => gm.Group.Guid == groupGuid ) .Select( gm => gm.Person ) .ToList(); string caseWorkerPersonAliasValue = benevolenceRequest.CaseWorkerPersonAliasId.ToString(); if ( benevolenceRequest.CaseWorkerPersonAlias != null && benevolenceRequest.CaseWorkerPersonAlias.Person != null && !personList.Select( p => p.Id ).ToList().Contains( benevolenceRequest.CaseWorkerPersonAlias.Person.Id ) ) { personList.Add( benevolenceRequest.CaseWorkerPersonAlias.Person ); } ddlCaseWorker.DataSource = personList.OrderBy( p => p.NickName ).ThenBy( p => p.LastName ).ToList(); ddlCaseWorker.DataTextField = "FullName"; ddlCaseWorker.DataValueField = "PrimaryAliasId"; ddlCaseWorker.DataBind(); ddlCaseWorker.Items.Insert( 0, new ListItem() ); }
/// <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 ); }
/// <summary> /// Adds the person to group. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="person">The person.</param> /// <param name="workflowType">Type of the workflow.</param> /// <param name="groupMembers">The group members.</param> private void AddPersonToGroup( RockContext rockContext, Person person, WorkflowType workflowType, List<GroupMember> groupMembers ) { if (person != null ) { if ( !_group.Members .Any( m => m.PersonId == person.Id && m.GroupRoleId == _defaultGroupRole.Id)) { var groupMemberService = new GroupMemberService(rockContext); var groupMember = new GroupMember(); groupMember.PersonId = person.Id; groupMember.GroupRoleId = _defaultGroupRole.Id; groupMember.GroupMemberStatus = (GroupMemberStatus)GetAttributeValue("GroupMemberStatus").AsInteger(); groupMember.GroupId = _group.Id; groupMemberService.Add( groupMember ); rockContext.SaveChanges(); if ( workflowType != null ) { try { List<string> workflowErrors; var workflow = Workflow.Activate( workflowType, person.FullName ); new WorkflowService( rockContext ).Process( workflow, groupMember, out workflowErrors ); } catch (Exception ex) { ExceptionLogService.LogException( ex, this.Context ); } } } } }
/// <summary> /// Updates the group member. /// </summary> /// <param name="businessId">The business identifier.</param> /// <param name="groupType">Type of the group.</param> /// <param name="groupName">Name of the group.</param> /// <param name="campusId">The campus identifier.</param> /// <param name="groupRoleId">The group role identifier.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> private GroupMember UpdateGroupMember( int businessId, GroupTypeCache groupType, string groupName, int? campusId, int groupRoleId, RockContext rockContext ) { var groupMemberService = new GroupMemberService( rockContext ); GroupMember groupMember = groupMemberService.Queryable( "Group" ) .Where( m => m.PersonId == businessId && m.GroupRoleId == groupRoleId ) .FirstOrDefault(); if ( groupMember == null ) { groupMember = new GroupMember(); groupMember.Group = new Group(); groupMemberService.Add( groupMember ); } groupMember.PersonId = businessId; groupMember.GroupRoleId = groupRoleId; groupMember.GroupMemberStatus = GroupMemberStatus.Active; groupMember.Group.GroupTypeId = groupType.Id; groupMember.Group.Name = groupName; groupMember.Group.CampusId = campusId; return groupMember; }
/// <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 ) { 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" ); } } } }
protected void btnSave_Click( object sender, EventArgs e ) { RockContext rockContext = new RockContext(); var attendanceService = new AttendanceService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); foreach ( RepeaterItem item in rptScheduleDates.Items ) { var placeholder = item.FindControl( "phGroups" ) as PlaceHolder; if (placeholder != null ) { // get groups foreach( Control control in placeholder.Controls ) { if (control is DropDownList ) { var ddlGroup = (DropDownList)control; var groupId = ddlGroup.SelectedValue.AsInteger(); var scheduleId = ddlGroup.Attributes["schedule-id"].AsInteger(); var scheduleDate = ddlGroup.Attributes["schedule-date"].AsDateTime(); var originalGroupId = ddlGroup.Attributes["original-group-id"].AsInteger(); // check if person is already registered for this schedule var attending = _personalSchedules.Where( p => p.Date.Date == scheduleDate.Value.Date && p.Schedule.Id == scheduleId && p.Group.Id == groupId ) .Any(); if ( originalGroupId != 0 && groupId == 0 ) { RemovePersonRsvp( CurrentPerson, originalGroupId, scheduleId, scheduleDate ); } else if (!attending && groupId != 0 ) { // remove existing record if ( originalGroupId != 0 ) { RemovePersonRsvp( CurrentPerson, originalGroupId, scheduleId, scheduleDate ); } // mark them as coming var attendanceRecord = new Attendance(); attendanceRecord.PersonAliasId = CurrentPersonAliasId; attendanceRecord.GroupId = groupId; attendanceRecord.ScheduleId = scheduleId; attendanceRecord.StartDateTime = scheduleDate.Value.Date; attendanceRecord.RSVP = RSVP.Yes; attendanceRecord.LocationId = _location.Id; attendanceService.Add( attendanceRecord ); rockContext.SaveChanges(); // add them to the group var groupMember = groupMemberService.Queryable().Where( m => m.PersonId == CurrentPersonId && m.GroupId == groupId ).FirstOrDefault(); if (groupMember == null ) { bool createAsInactive = GetAttributeValue( "GroupMembersInactive" ).AsBoolean(); groupMember = new GroupMember(); groupMemberService.Add( groupMember ); groupMember.PersonId = CurrentPersonId.Value; groupMember.GroupId = groupId; groupMember.GroupMemberStatus = createAsInactive ? GroupMemberStatus.Inactive : GroupMemberStatus.Active; groupMember.GroupRoleId = _groupRoleId; } rockContext.SaveChanges(); var scheduleName = new ScheduleService( rockContext ).Queryable().Where( s => s.Id == scheduleId ).Select( s => s.Name ).FirstOrDefault(); if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "DescriptionAttribute" ) ) ) { groupMember.LoadAttributes(); groupMember.SetAttributeValue( GetAttributeValue( "DescriptionAttribute" ), string.Format( "{0} {1}", scheduleDate.Value.ToShortDateString(), scheduleName ) ); groupMember.SaveAttributeValues(); } } } } } } nbMessages.NotificationBoxType = NotificationBoxType.Success; nbMessages.Text = "Your changes have been saved."; }
/// <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 ); }
private void AddRegistrantToGroup( int registrantId ) { if ( RegistrationTemplateState != null && RegistrationTemplateState.GroupTypeId.HasValue && Registration.GroupId.HasValue ) { using ( var rockContext = new RockContext() ) { var registrant = new RegistrationRegistrantService( rockContext ).Get( registrantId ); if ( registrant != null && registrant.PersonId.HasValue && !registrant.GroupMemberId.HasValue ) { var groupService = new GroupService( rockContext ); var group = groupService.Get( Registration.GroupId.Value ); if ( group != null && group.GroupTypeId == RegistrationTemplateState.GroupTypeId.Value ) { int? groupRoleId = RegistrationTemplateState.GroupMemberRoleId.HasValue ? RegistrationTemplateState.GroupMemberRoleId.Value : group.GroupType.DefaultGroupRoleId; if ( groupRoleId.HasValue ) { var registrantChanges = new List<string>(); var groupMemberService = new GroupMemberService( rockContext ); var groupMember = groupMemberService .Queryable().AsNoTracking() .Where( m => m.GroupId == Registration.Group.Id && m.PersonId == registrant.PersonId && m.GroupRoleId == groupRoleId.Value ) .FirstOrDefault(); if ( groupMember == null ) { groupMember = new GroupMember(); groupMemberService.Add( groupMember ); groupMember.GroupId = group.Id; groupMember.PersonId = registrant.PersonId.Value; groupMember.GroupRoleId = groupRoleId.Value; groupMember.GroupMemberStatus = RegistrationTemplateState.GroupMemberStatus; rockContext.SaveChanges(); registrantChanges.Add( string.Format( "Registrant added to {0} group", group.Name ) ); } else { registrantChanges.Add( string.Format( "Registrant group member reference updated to existing person in {0} group", group.Name ) ); } registrant.GroupMemberId = groupMember.Id; rockContext.SaveChanges(); HistoryService.SaveChanges( rockContext, typeof( Registration ), Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(), registrant.RegistrationId, registrantChanges, "Registrant: " + CurrentPerson.FullName, null, null ); } } } } } }
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> /// Job that will sync groups. /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute( IJobExecutionContext context ) { JobDataMap dataMap = context.JobDetail.JobDataMap; try { // get groups set to sync RockContext rockContext = new RockContext(); GroupService groupService = new GroupService( rockContext ); var groupsThatSync = groupService.Queryable().Where( g => g.SyncDataViewId != null ).ToList(); foreach ( var syncGroup in groupsThatSync ) { GroupMemberService groupMemberService = new GroupMemberService( rockContext ); var syncSource = new DataViewService( rockContext ).Get( syncGroup.SyncDataViewId.Value ); // ensure this is a person dataview bool isPersonDataSet = syncSource.EntityTypeId == EntityTypeCache.Read( typeof( Rock.Model.Person ) ).Id; if ( isPersonDataSet ) { SortProperty sortById = new SortProperty(); sortById.Property = "Id"; sortById.Direction = System.Web.UI.WebControls.SortDirection.Ascending; List<string> errorMessages = new List<string>(); var sourceItems = syncSource.GetQuery( sortById, 180, out errorMessages ).Select( q => q.Id ).ToList(); var targetItems = groupMemberService.Queryable("Person").Where( gm => gm.GroupId == syncGroup.Id ).ToList(); // delete items from the target not in the source foreach ( var targetItem in targetItems.Where( t => !sourceItems.Contains( t.PersonId ) ) ) { // made a clone of the person as it will be detached when the group member is deleted. Also // saving the delete before the email is sent in case an exception occurs so the user doesn't // get an email everytime the agent runs. Person recipient = (Person)targetItem.Person.Clone(); groupMemberService.Delete( targetItem ); rockContext.SaveChanges(); if ( syncGroup.ExitSystemEmailId.HasValue ) { SendExitEmail( syncGroup.ExitSystemEmailId.Value, recipient, syncGroup ); } } // add items not in target but in the source foreach ( var sourceItem in sourceItems.Where( s => !targetItems.Select( t => t.PersonId ).Contains( s ) ) ) { // add source to target var newGroupMember = new GroupMember { Id = 0 }; newGroupMember.PersonId = sourceItem; newGroupMember.Group = syncGroup; newGroupMember.GroupMemberStatus = GroupMemberStatus.Active; newGroupMember.GroupRoleId = syncGroup.GroupType.DefaultGroupRoleId ?? syncGroup.GroupType.Roles.FirstOrDefault().Id; groupMemberService.Add( newGroupMember ); if ( syncGroup.WelcomeSystemEmailId.HasValue ) { SendWelcomeEmail( syncGroup.WelcomeSystemEmailId.Value, sourceItem, syncGroup, syncGroup.AddUserAccountsDuringSync ?? false ); } } rockContext.SaveChanges(); } } } catch ( System.Exception ex ) { HttpContext context2 = HttpContext.Current; ExceptionLogService.LogException( ex, context2 ); throw ex; } }
void modalAddPerson_SaveClick( object sender, EventArgs e ) { if ( ppPerson.PersonId.HasValue ) { int? roleId = grpRole.GroupRoleId; if ( roleId.HasValue ) { var rockContext = new RockContext(); var memberService = new GroupMemberService( rockContext ); var group = memberService.Queryable() .Where( m => m.PersonId == Person.Id && m.GroupRole.Guid == ownerRoleGuid ) .Select( m => m.Group ) .FirstOrDefault(); if ( group != null ) { GroupMember groupMember = null; int? groupMemberId = hfRoleId.Value.AsIntegerOrNull(); if ( groupMemberId.HasValue ) { groupMember = memberService.Queryable() .Where( m => m.Id == groupMemberId.Value ) .FirstOrDefault(); } if ( groupMember == null ) { groupMember = new GroupMember(); groupMember.GroupId = group.Id; memberService.Add( groupMember ); } GroupMember formerInverseGroupMember = null; if ( IsKnownRelationships ) { formerInverseGroupMember = memberService.GetInverseRelationship( groupMember, false, CurrentPersonAlias ); } groupMember.PersonId = ppPerson.PersonId.Value; groupMember.GroupRoleId = roleId.Value; rockContext.SaveChanges(); if ( IsKnownRelationships ) { var inverseGroupMember = memberService.GetInverseRelationship( groupMember, bool.Parse( GetAttributeValue( "CreateGroup" ) ), CurrentPersonAlias ); if ( inverseGroupMember != null ) { rockContext.SaveChanges(); if ( formerInverseGroupMember != null && formerInverseGroupMember.Id != inverseGroupMember.Id ) { memberService.Delete( formerInverseGroupMember ); rockContext.SaveChanges(); } } } } } } HideDialog(); BindData(); }
/// <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; }
/// <summary> /// Adds the registrants to group. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="registration">The registration.</param> private void AddRegistrantsToGroup( RockContext rockContext, Registration registration ) { // If the registration instance linkage specified a group to add registrant to, add them if they're not already // part of that group if ( registration.GroupId.HasValue ) { var groupService = new GroupService( rockContext ); var personAliasService = new PersonAliasService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); var group = groupService.Get( registration.GroupId.Value ); if ( group != null ) { foreach ( var registrant in registration.Registrants.Where( r => r.PersonAliasId.HasValue ).ToList() ) { var personAlias = personAliasService.Get( registrant.PersonAliasId.Value ); GroupMember groupMember = group.Members.Where( m => m.PersonId == personAlias.PersonId ).FirstOrDefault(); if ( groupMember == null ) { groupMember = new GroupMember(); groupMemberService.Add( groupMember ); groupMember.GroupId = group.Id; groupMember.PersonId = personAlias.PersonId; if ( RegistrationTemplate.GroupTypeId.HasValue && RegistrationTemplate.GroupTypeId == group.GroupTypeId && RegistrationTemplate.GroupMemberRoleId.HasValue ) { groupMember.GroupRoleId = RegistrationTemplate.GroupMemberRoleId.Value; groupMember.GroupMemberStatus = RegistrationTemplate.GroupMemberStatus; } else { if ( group.GroupType.DefaultGroupRoleId.HasValue ) { groupMember.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value; } else { groupMember.GroupRoleId = group.GroupType.Roles.Select( r => r.Id ).FirstOrDefault(); } groupMember.GroupMemberStatus = GroupMemberStatus.Active; } } rockContext.SaveChanges(); registrant.GroupMemberId = groupMember != null ? groupMember.Id : (int?)null; rockContext.SaveChanges(); // Set any of the template's group member attributes groupMember.LoadAttributes(); var registrantInfo = RegistrationState.Registrants.FirstOrDefault( r => r.Guid == registrant.Guid ); if ( registrantInfo != null ) { foreach ( var field in RegistrationTemplate.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.GroupMemberAttribute && t.AttributeId.HasValue ) ) ) { // Find the registrant's value var fieldValue = registrantInfo.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value.FieldValue ) .FirstOrDefault(); if ( fieldValue != null ) { var attribute = AttributeCache.Read( field.AttributeId.Value ); if ( attribute != null ) { string originalValue = groupMember.GetAttributeValue( attribute.Key ); string newValue = fieldValue.ToString(); groupMember.SetAttributeValue( attribute.Key, fieldValue.ToString() ); if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() ) { string formattedOriginalValue = string.Empty; if ( !string.IsNullOrWhiteSpace( originalValue ) ) { formattedOriginalValue = attribute.FieldType.Field.FormatValue( null, originalValue, attribute.QualifierValues, false ); } string formattedNewValue = string.Empty; if ( !string.IsNullOrWhiteSpace( newValue ) ) { formattedNewValue = attribute.FieldType.Field.FormatValue( null, newValue, attribute.QualifierValues, false ); } Helper.SaveAttributeValue( groupMember, attribute, newValue, rockContext ); } } } } } } } } }
/// <summary> /// Handles the Click event of the lbConnect 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 lbConnect_Click( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { var connectionRequestService = new ConnectionRequestService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); var connectionActivityTypeService = new ConnectionActivityTypeService( rockContext ); var connectionRequestActivityService = new ConnectionRequestActivityService( rockContext ); var connectionRequest = connectionRequestService.Get( hfConnectionRequestId.ValueAsInt() ); if ( connectionRequest != null && connectionRequest.PersonAlias != null && connectionRequest.ConnectionOpportunity != null ) { // Only do group member placement if the request has an assigned placement group if ( connectionRequest.ConnectionOpportunity.GroupMemberRoleId.HasValue && connectionRequest.AssignedGroupId.HasValue ) { // Only attempt the add if person does not already exist in group with same role var groupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId( connectionRequest.AssignedGroupId.Value, connectionRequest.PersonAlias.PersonId, connectionRequest.ConnectionOpportunity.GroupMemberRoleId.Value ); if ( groupMember == null ) { groupMember = new GroupMember(); groupMember.PersonId = connectionRequest.PersonAlias.PersonId; groupMember.GroupRoleId = connectionRequest.ConnectionOpportunity.GroupMemberRoleId.Value; groupMember.GroupMemberStatus = connectionRequest.ConnectionOpportunity.GroupMemberStatus; groupMember.GroupId = connectionRequest.AssignedGroupId.Value; groupMemberService.Add( groupMember ); } } // ... but always record the connection activity and change the state to connected. var guid = Rock.SystemGuid.ConnectionActivityType.CONNECTED.AsGuid(); var connectedActivityId = connectionActivityTypeService.Queryable() .Where( t => t.Guid == guid ) .Select( t => t.Id ) .FirstOrDefault(); if ( connectedActivityId > 0 ) { var connectionRequestActivity = new ConnectionRequestActivity(); connectionRequestActivity.ConnectionRequestId = connectionRequest.Id; connectionRequestActivity.ConnectionOpportunityId = connectionRequest.ConnectionOpportunityId; connectionRequestActivity.ConnectionActivityTypeId = connectedActivityId; connectionRequestActivity.ConnectorPersonAliasId = CurrentPersonAliasId; connectionRequestActivityService.Add( connectionRequestActivity ); } connectionRequest.ConnectionState = ConnectionState.Connected; rockContext.SaveChanges(); ShowDetail( connectionRequest.Id, connectionRequest.ConnectionOpportunityId ); } } }
/// <summary> /// Job that will sync groups. /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute( IJobExecutionContext context ) { JobDataMap dataMap = context.JobDetail.JobDataMap; bool requirePasswordReset = dataMap.GetBoolean( "RequirePasswordReset" ); int groupsSynced = 0; int groupsChanged = 0; try { // get groups set to sync GroupService groupService = new GroupService( new RockContext() ); var groupIdsThatSync = groupService.Queryable().Where( g => g.SyncDataViewId != null ).Select( a => a.Id ).ToList(); foreach ( var syncGroupId in groupIdsThatSync ) { bool hasGroupChanged = false; // use a fresh rockContext per group so that ChangeTracker doesn't get bogged down using ( var rockContext = new RockContext() ) { var syncGroup = new GroupService( rockContext ).Get( syncGroupId ); GroupMemberService groupMemberService = new GroupMemberService( rockContext ); // increase the timeout just in case the dataview source is slow rockContext.Database.CommandTimeout = 180; var syncSource = new DataViewService( rockContext ).Get( syncGroup.SyncDataViewId.Value ); // ensure this is a person dataview bool isPersonDataSet = syncSource.EntityTypeId == EntityTypeCache.Read( typeof( Rock.Model.Person ) ).Id; if ( isPersonDataSet ) { SortProperty sortById = new SortProperty(); sortById.Property = "Id"; sortById.Direction = System.Web.UI.WebControls.SortDirection.Ascending; List<string> errorMessages = new List<string>(); var personService = new PersonService( rockContext ); var parameterExpression = personService.ParameterExpression; var whereExpression = syncSource.GetExpression( personService, parameterExpression, out errorMessages ); var sourceItems = personService.Get( parameterExpression, whereExpression ).Select( q => q.Id ).ToList(); var targetItems = groupMemberService.Queryable().Where( gm => gm.GroupId == syncGroup.Id ).ToList(); // delete items from the target not in the source foreach ( var targetItem in targetItems.Where( t => !sourceItems.Contains( t.PersonId ) ) ) { // made a clone of the person as it will be detached when the group member is deleted. Also // saving the delete before the email is sent in case an exception occurs so the user doesn't // get an email everytime the agent runs. Person recipient = (Person)targetItem.Person.Clone(); groupMemberService.Delete( targetItem ); rockContext.SaveChanges(); hasGroupChanged = true; if ( syncGroup.ExitSystemEmailId.HasValue ) { SendExitEmail( syncGroup.ExitSystemEmailId.Value, recipient, syncGroup ); } } // add items not in target but in the source foreach ( var sourceItem in sourceItems.Where( s => !targetItems.Select( t => t.PersonId ).Contains( s ) ) ) { // add source to target var newGroupMember = new GroupMember { Id = 0 }; newGroupMember.PersonId = sourceItem; newGroupMember.Group = syncGroup; newGroupMember.GroupMemberStatus = GroupMemberStatus.Active; newGroupMember.GroupRoleId = syncGroup.GroupType.DefaultGroupRoleId ?? syncGroup.GroupType.Roles.FirstOrDefault().Id; groupMemberService.Add( newGroupMember ); hasGroupChanged = true; if ( syncGroup.WelcomeSystemEmailId.HasValue ) { SendWelcomeEmail( syncGroup.WelcomeSystemEmailId.Value, sourceItem, syncGroup, syncGroup.AddUserAccountsDuringSync ?? false, requirePasswordReset ); } } if ( hasGroupChanged ) { groupsChanged++; } groupsSynced++; rockContext.SaveChanges(); if ( hasGroupChanged && ( syncGroup.IsSecurityRole || syncGroup.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) ) { Rock.Security.Role.Flush( syncGroup.Id ); } } } } var resultMessage = string.Empty; if ( groupsSynced == 0 ) { resultMessage = "No groups to sync"; } else if ( groupsSynced == 1 ) { resultMessage = "1 group was sync'ed"; } else { resultMessage = string.Format( "{0} groups were sync'ed", groupsSynced ); } resultMessage += string.Format( " and {0} groups where changed", groupsChanged ); context.Result = resultMessage; } catch ( System.Exception ex ) { HttpContext context2 = HttpContext.Current; ExceptionLogService.LogException( ex, context2 ); throw; } }
/// <summary> /// Executes this instance. /// </summary> public void Execute() { using ( var rockContext = new RockContext() ) { var relationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid() ); if ( relationshipGroupType != null ) { var ownerRole = relationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid() ) ) .FirstOrDefault(); var friendRole = relationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_FACEBOOK_FRIEND.AsGuid() ) ) .FirstOrDefault(); if ( ownerRole != null && friendRole != null ) { var userLoginService = new UserLoginService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); // Convert list of facebook ids into list of usernames var friendUserNames = FacebookIds.Select( i => "FACEBOOK_" + i ).ToList(); // Get the list of person ids associated with friends usernames var friendPersonIds = userLoginService.Queryable() .Where( l => l.PersonId.HasValue && l.PersonId != PersonId && friendUserNames.Contains( l.UserName ) ) .Select( l => l.PersonId.Value ) .Distinct() .ToList(); // Get the person's group id var personGroup = groupMemberService.Queryable() .Where( m => m.PersonId == PersonId && m.GroupRoleId == ownerRole.Id && m.Group.GroupTypeId == relationshipGroupType.Id ) .Select( m => m.Group ) .FirstOrDefault(); // Verify that a 'known relationships' type group existed for the person, if not create it if ( personGroup == null ) { var groupMember = new GroupMember(); groupMember.PersonId = PersonId; groupMember.GroupRoleId = ownerRole.Id; personGroup = new Group(); personGroup.Name = relationshipGroupType.Name; personGroup.GroupTypeId = relationshipGroupType.Id; personGroup.Members.Add( groupMember ); var groupService = new GroupService( rockContext ); groupService.Add( personGroup ); rockContext.SaveChanges(); } // Get the person's relationship group id var personGroupId = personGroup.Id; // Get all of the friend's relationship group ids var friendGroupIds = groupMemberService.Queryable() .Where( m => m.Group.GroupTypeId == relationshipGroupType.Id && m.GroupRoleId == ownerRole.Id && friendPersonIds.Contains( m.PersonId ) ) .Select( m => m.GroupId ) .Distinct() .ToList(); // Find all the existing friend relationships in Rock ( both directions ) var existingFriends = groupMemberService.Queryable() .Where( m => m.Group.GroupTypeId == relationshipGroupType.Id && ( ( friendPersonIds.Contains( m.PersonId ) && m.GroupId == personGroupId ) || ( m.PersonId == PersonId && m.GroupId != personGroupId ) ) ) .ToList(); // Create temp group members for current Facebook friends var currentFriends = new List<GroupMember>(); // ( Person > Friend ) foreach ( int personId in friendPersonIds ) { var groupMember = new GroupMember(); groupMember.GroupId = personGroupId; groupMember.PersonId = personId; groupMember.GroupRoleId = friendRole.Id; groupMember.GroupMemberStatus = GroupMemberStatus.Active; currentFriends.Add( groupMember ); } // ( Friend > Person ) foreach ( int familyId in friendGroupIds ) { var groupMember = new GroupMember(); groupMember.GroupId = familyId; groupMember.PersonId = PersonId; groupMember.GroupRoleId = friendRole.Id; groupMember.GroupMemberStatus = GroupMemberStatus.Active; currentFriends.Add( groupMember ); } // Add any current friends that do not exist in Rock yet foreach ( var groupMember in currentFriends .Where( f => !existingFriends.Any( e => e.IsEqualTo( f ) ) ) ) { groupMemberService.Add( groupMember ); } // Delete any existing friends that are no longer facebook friends foreach ( var groupMember in existingFriends .Where( f => !currentFriends.Any( e => e.IsEqualTo( f ) ) ) ) { groupMemberService.Delete( groupMember ); } rockContext.SaveChanges(); } } } }
/// <summary> /// Handles the Click event of the lbPlaceInGroup 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 lbPlaceInGroup_Click( object sender, EventArgs e ) { var col = gGroupPlacements.Columns.OfType<GroupPickerField>().FirstOrDefault(); if ( col != null ) { var placements = new Dictionary<int, List<int>>(); var colIndex = gGroupPlacements.Columns.IndexOf( col ).ToString(); foreach ( GridViewRow row in gGroupPlacements.Rows ) { GroupPicker gp = row.FindControl( "groupPicker_" + colIndex.ToString() ) as GroupPicker; if ( gp != null ) { int? groupId = gp.SelectedValueAsInt(); if ( groupId.HasValue ) { int registrantId = (int)gGroupPlacements.DataKeys[row.RowIndex].Value; placements.AddOrIgnore( groupId.Value, new List<int>() ); placements[groupId.Value].Add( registrantId ); } } } using ( var rockContext = new RockContext() ) { var groupMemberService = new GroupMemberService( rockContext ); // Get all the registrants that were selected var registrantIds = placements.SelectMany( p => p.Value ).ToList(); var registrants = new RegistrationRegistrantService( rockContext ) .Queryable( "PersonAlias" ).AsNoTracking() .Where( r => registrantIds.Contains( r.Id ) ) .ToList(); // Get any groups that were selected var groupIds = placements.Keys.ToList(); foreach ( var group in new GroupService( rockContext ) .Queryable( "GroupType" ).AsNoTracking() .Where( g => groupIds.Contains( g.Id ) ) ) { foreach ( int registrantId in placements[group.Id] ) { int? roleId = group.GroupType.DefaultGroupRoleId; if ( !roleId.HasValue ) { roleId = group.GroupType.Roles .OrderBy( r => r.Order ) .Select( r => r.Id ) .FirstOrDefault(); } var registrant = registrants.FirstOrDefault( r => r.Id == registrantId ); if ( registrant != null && roleId.HasValue && roleId.Value > 0 ) { var groupMember = new GroupMember(); groupMember.PersonId = registrant.PersonAlias.PersonId; groupMember.GroupId = group.Id; groupMember.GroupRoleId = roleId.Value; groupMember.GroupMemberStatus = GroupMemberStatus.Active; groupMemberService.Add( groupMember ); } } } rockContext.SaveChanges(); } } BindGroupPlacementGrid(); }
/// <summary> /// Handles the Click event of the btnConfirm 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 btnConfirm_Click( object sender, EventArgs e ) { if ( Page.IsValid ) { var rockContext = new RockContext(); var personService = new PersonService( rockContext ); var ids = Individuals.Select( i => i.PersonId ).ToList(); #region Individual Details Updates int? newTitleId = ddlTitle.SelectedValueAsInt(); int? newSuffixId = ddlSuffix.SelectedValueAsInt(); int? newConnectionStatusId = ddlStatus.SelectedValueAsInt(); int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt(); int? newInactiveReasonId = ddlInactiveReason.SelectedValueAsInt(); string newInactiveReasonNote = tbInactiveReasonNote.Text; Gender newGender = ddlGender.SelectedValue.ConvertToEnum<Gender>(); int? newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt(); int? newGraduationYear = null; if ( ypGraduation.SelectedYear.HasValue ) { newGraduationYear = ypGraduation.SelectedYear.Value; } int? newCampusId = cpCampus.SelectedCampusId; bool? newEmailActive = null; if ( !string.IsNullOrWhiteSpace( ddlIsEmailActive.SelectedValue ) ) { newEmailActive = ddlIsEmailActive.SelectedValue == "Active"; } EmailPreference? newEmailPreference = ddlEmailPreference.SelectedValue.ConvertToEnumOrNull<EmailPreference>(); string newEmailNote = tbEmailNote.Text; int? newReviewReason = ddlReviewReason.SelectedValueAsInt(); string newSystemNote = tbSystemNote.Text; string newReviewReasonNote = tbReviewReasonNote.Text; int inactiveStatusId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ).Id; var allChanges = new Dictionary<int, List<string>>(); var people = personService.Queryable().Where( p => ids.Contains( p.Id ) ).ToList(); foreach ( var person in people ) { var changes = new List<string>(); allChanges.Add( person.Id, changes ); if ( SelectedFields.Contains( ddlTitle.ClientID ) ) { History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) ); person.TitleValueId = newTitleId; } if ( SelectedFields.Contains( ddlSuffix.ClientID ) ) { History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) ); person.SuffixValueId = newSuffixId; } if ( SelectedFields.Contains( ddlStatus.ClientID ) ) { History.EvaluateChange( changes, "Connection Status", DefinedValueCache.GetName( person.ConnectionStatusValueId ), DefinedValueCache.GetName( newConnectionStatusId ) ); person.ConnectionStatusValueId = newConnectionStatusId; } if ( SelectedFields.Contains( ddlRecordStatus.ClientID ) ) { History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( person.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) ); person.RecordStatusValueId = newRecordStatusId; if ( newRecordStatusId.HasValue && newRecordStatusId.Value == inactiveStatusId ) { History.EvaluateChange( changes, "Inactive Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( newInactiveReasonId ) ); person.RecordStatusReasonValueId = newInactiveReasonId; if ( !string.IsNullOrWhiteSpace( newInactiveReasonNote ) ) { History.EvaluateChange( changes, "Inactive Reason Note", person.InactiveReasonNote, newInactiveReasonNote ); person.InactiveReasonNote = newInactiveReasonNote; } } } if ( SelectedFields.Contains( ddlGender.ClientID ) ) { History.EvaluateChange( changes, "Gender", person.Gender, newGender ); person.Gender = newGender; } if ( SelectedFields.Contains( ddlMaritalStatus.ClientID ) ) { History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) ); person.MaritalStatusValueId = newMaritalStatusId; } if ( SelectedFields.Contains( ddlGradePicker.ClientID ) ) { History.EvaluateChange( changes, "Graduation Year", person.GraduationYear, newGraduationYear ); person.GraduationYear = newGraduationYear; } if ( SelectedFields.Contains( ddlIsEmailActive.ClientID ) ) { History.EvaluateChange( changes, "Email Is Active", person.IsEmailActive ?? true, newEmailActive.Value ); person.IsEmailActive = newEmailActive; } if ( SelectedFields.Contains( ddlEmailPreference.ClientID ) ) { History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference ); person.EmailPreference = newEmailPreference.Value; } if ( SelectedFields.Contains( tbEmailNote.ClientID ) ) { History.EvaluateChange( changes, "Email Note", person.EmailNote, newEmailNote ); person.EmailNote = newEmailNote; } if ( SelectedFields.Contains( tbSystemNote.ClientID ) ) { History.EvaluateChange( changes, "System Note", person.SystemNote, newSystemNote ); person.SystemNote = newSystemNote; } if ( SelectedFields.Contains( ddlReviewReason.ClientID ) ) { History.EvaluateChange( changes, "Review Reason", DefinedValueCache.GetName( person.ReviewReasonValueId ), DefinedValueCache.GetName( newReviewReason ) ); person.ReviewReasonValueId = newReviewReason; } if ( SelectedFields.Contains( tbReviewReasonNote.ClientID ) ) { History.EvaluateChange( changes, "Review Reason Note", person.ReviewReasonNote, newReviewReasonNote ); person.ReviewReasonNote = newReviewReasonNote; } } if ( SelectedFields.Contains( cpCampus.ClientID ) && cpCampus.SelectedCampusId.HasValue ) { int campusId = cpCampus.SelectedCampusId.Value; Guid familyGuid = new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY ); var familyMembers = new GroupMemberService( rockContext ).Queryable() .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid ) .Select( m => new { m.PersonId, m.GroupId } ) .Distinct() .ToList(); var families = new GroupMemberService( rockContext ).Queryable() .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid ) .Select( m => m.Group ) .Distinct() .ToList(); foreach ( int personId in ids ) { var familyIds = familyMembers.Where( m => m.PersonId == personId ).Select( m => m.GroupId ).ToList(); if ( familyIds.Count == 1 ) { int familyId = familyIds.FirstOrDefault(); var family = families.Where( g => g.Id == familyId ).FirstOrDefault(); { if ( family != null ) { family.CampusId = campusId; } familyMembers.RemoveAll( m => m.GroupId == familyId ); } } } rockContext.SaveChanges(); } // Update following if ( SelectedFields.Contains( ddlFollow.ClientID ) ) { var personAliasEntityType = EntityTypeCache.Read( "Rock.Model.PersonAlias" ); if ( personAliasEntityType != null ) { int personAliasEntityTypeId = personAliasEntityType.Id; bool follow = true; if ( !string.IsNullOrWhiteSpace( ddlFollow.SelectedValue ) ) { follow = ddlFollow.SelectedValue == "Add"; } var personAliasService = new PersonAliasService( rockContext ); var followingService = new FollowingService( rockContext ); if ( follow ) { var paQry = personAliasService.Queryable(); var alreadyFollowingIds = followingService.Queryable() .Where( f => f.EntityTypeId == personAliasEntityTypeId && f.PersonAlias.Id == CurrentPersonAlias.Id ) .Join( paQry, f => f.EntityId, p => p.Id, ( f, p ) => new { PersonAlias = p } ) .Select( p => p.PersonAlias.PersonId ) .Distinct() .ToList(); foreach ( int id in ids.Where( id => !alreadyFollowingIds.Contains( id ) ) ) { var following = new Following { EntityTypeId = personAliasEntityTypeId, EntityId = ( people.FirstOrDefault( p => p.Id == id ).PrimaryAliasId ) ?? 0, PersonAliasId = CurrentPersonAlias.Id }; followingService.Add( following ); } } else { var paQry = personAliasService.Queryable() .Where( p => ids.Contains( p.PersonId ) ) .Select( p => p.Id ); foreach ( var following in followingService.Queryable() .Where( f => f.EntityTypeId == personAliasEntityTypeId && paQry.Contains( f.EntityId ) && f.PersonAlias.Id == CurrentPersonAlias.Id ) ) { followingService.Delete( following ); } } } } rockContext.SaveChanges(); #endregion #region Attributes var selectedCategories = new List<CategoryCache>(); foreach ( string categoryGuid in GetAttributeValue( "AttributeCategories" ).SplitDelimitedValues() ) { var category = CategoryCache.Read( categoryGuid.AsGuid(), rockContext ); if ( category != null ) { selectedCategories.Add( category ); } } var attributes = new List<AttributeCache>(); var attributeValues = new Dictionary<int, string>(); int categoryIndex = 0; foreach ( var category in selectedCategories.OrderBy( c => c.Name ) ) { PanelWidget pw = null; string controlId = "pwAttributes_" + category.Id.ToString(); if ( categoryIndex % 2 == 0 ) { pw = phAttributesCol1.FindControl( controlId ) as PanelWidget; } else { pw = phAttributesCol2.FindControl( controlId ) as PanelWidget; } categoryIndex++; if ( pw != null ) { var orderedAttributeList = new AttributeService( rockContext ).GetByCategoryId( category.Id ) .OrderBy( a => a.Order ).ThenBy( a => a.Name ); foreach ( var attribute in orderedAttributeList ) { if ( attribute.IsAuthorized( Authorization.EDIT, CurrentPerson ) ) { var attributeCache = AttributeCache.Read( attribute.Id ); Control attributeControl = pw.FindControl( string.Format( "attribute_field_{0}", attribute.Id ) ); if ( attributeControl != null && SelectedFields.Contains( attributeControl.ClientID ) ) { string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues ); attributes.Add( attributeCache ); attributeValues.Add( attributeCache.Id, newValue ); } } } } } if ( attributes.Any() ) { foreach ( var person in people ) { person.LoadAttributes(); foreach ( var attribute in attributes ) { string originalValue = person.GetAttributeValue( attribute.Key ); string newValue = attributeValues[attribute.Id]; if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() ) { Rock.Attribute.Helper.SaveAttributeValue( person, attribute, newValue, rockContext ); string formattedOriginalValue = string.Empty; if ( !string.IsNullOrWhiteSpace( originalValue ) ) { formattedOriginalValue = attribute.FieldType.Field.FormatValue( null, originalValue, attribute.QualifierValues, false ); } string formattedNewValue = string.Empty; if ( !string.IsNullOrWhiteSpace( newValue ) ) { formattedNewValue = attribute.FieldType.Field.FormatValue( null, newValue, attribute.QualifierValues, false ); } History.EvaluateChange( allChanges[person.Id], attribute.Name, formattedOriginalValue, formattedNewValue ); } } } } // Create the history records foreach ( var changes in allChanges ) { if ( changes.Value.Any() ) { HistoryService.AddChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), changes.Key, changes.Value ); } } rockContext.SaveChanges(); #endregion #region Add Note if ( !string.IsNullOrWhiteSpace( tbNote.Text ) && CurrentPerson != null ) { string text = tbNote.Text; bool isAlert = cbIsAlert.Checked; bool isPrivate = cbIsPrivate.Checked; var noteTypeService = new NoteTypeService( rockContext ); var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() ); if ( noteType != null ) { var notes = new List<Note>(); var noteService = new NoteService( rockContext ); foreach ( int id in ids ) { var note = new Note(); note.IsSystem = false; note.EntityId = id; note.Caption = isPrivate ? "You - Personal Note" : string.Empty; note.Text = tbNote.Text; note.IsAlert = cbIsAlert.Checked; note.NoteType = noteType; notes.Add( note ); noteService.Add( note ); } rockContext.WrapTransaction( () => { rockContext.SaveChanges(); foreach ( var note in notes ) { note.AllowPerson( Authorization.EDIT, CurrentPerson, rockContext ); if ( isPrivate ) { note.MakePrivate( Authorization.VIEW, CurrentPerson, rockContext ); } } } ); } } #endregion #region Group int? groupId = gpGroup.SelectedValue.AsIntegerOrNull(); if ( groupId.HasValue ) { var group = new GroupService( rockContext ).Get( groupId.Value ); if ( group != null ) { var groupMemberService = new GroupMemberService( rockContext ); var existingMembers = groupMemberService.Queryable( "Group" ) .Where( m => m.GroupId == group.Id && ids.Contains( m.PersonId ) ) .ToList(); string action = ddlGroupAction.SelectedValue; if ( action == "Remove" ) { groupMemberService.DeleteRange( existingMembers ); rockContext.SaveChanges(); } else { var roleId = ddlGroupRole.SelectedValueAsInt(); var status = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>(); // Get the attribute values updated var gm = new GroupMember(); gm.Group = group; gm.GroupId = group.Id; gm.LoadAttributes( rockContext ); var selectedGroupAttributes = new List<AttributeCache>(); var selectedGroupAttributeValues = new Dictionary<string, string>(); foreach ( var attributeCache in gm.Attributes.Select( a => a.Value ) ) { Control attributeControl = phAttributes.FindControl( string.Format( "attribute_field_{0}", attributeCache.Id ) ); if ( attributeControl != null && ( action == "Add" || SelectedFields.Contains( attributeControl.ClientID ) ) ) { string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues ); selectedGroupAttributes.Add( attributeCache ); selectedGroupAttributeValues.Add( attributeCache.Key, newValue ); } } if ( action == "Add" ) { if ( roleId.HasValue ) { var newGroupMembers = new List<GroupMember>(); var existingIds = existingMembers.Select( m => m.PersonId ).Distinct().ToList(); foreach ( int id in ids.Where( id => !existingIds.Contains( id ) ) ) { var groupMember = new GroupMember(); groupMember.GroupId = group.Id; groupMember.GroupRoleId = roleId.Value; groupMember.GroupMemberStatus = status; groupMember.PersonId = id; groupMemberService.Add( groupMember ); newGroupMembers.Add( groupMember ); } rockContext.SaveChanges(); if ( selectedGroupAttributes.Any() ) { foreach ( var groupMember in newGroupMembers ) { foreach ( var attribute in selectedGroupAttributes ) { Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext ); } } } } } else // Update { if ( SelectedFields.Contains( ddlGroupRole.ClientID ) && roleId.HasValue ) { foreach ( var member in existingMembers.Where( m => m.GroupRoleId != roleId.Value ) ) { if ( !existingMembers.Where( m => m.PersonId == member.PersonId && m.GroupRoleId == roleId.Value ).Any() ) { member.GroupRoleId = roleId.Value; } } } if ( SelectedFields.Contains( ddlGroupMemberStatus.ClientID ) ) { foreach ( var member in existingMembers ) { member.GroupMemberStatus = status; } } rockContext.SaveChanges(); if ( selectedGroupAttributes.Any() ) { foreach ( var groupMember in existingMembers ) { foreach ( var attribute in selectedGroupAttributes ) { Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext ); } } } } } } } #endregion pnlEntry.Visible = false; pnlConfirm.Visible = false; nbResult.Text = string.Format( "{0} {1} succesfully updated.", ids.Count().ToString( "N0" ), ( ids.Count() > 1 ? "people were" : "person was" ) ); ; pnlResult.Visible = true; } }
/// <summary> /// Adds the person to group. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="person">The person.</param> /// <param name="workflowType">Type of the workflow.</param> /// <param name="groupMembers">The group members.</param> private void AddPersonToGroup( RockContext rockContext, Person person, WorkflowType workflowType, List<GroupMember> groupMembers ) { if (person != null ) { if ( !_group.Members .Any( m => m.PersonId == person.Id && m.GroupRoleId == _defaultGroupRole.Id)) { var groupMemberService = new GroupMemberService(rockContext); var groupMember = new GroupMember(); groupMember.PersonId = person.Id; groupMember.GroupRoleId = _defaultGroupRole.Id; groupMember.GroupMemberStatus = (GroupMemberStatus)GetAttributeValue("GroupMemberStatus").AsInteger(); groupMember.GroupId = _group.Id; groupMemberService.Add( groupMember ); rockContext.SaveChanges(); if ( workflowType != null ) { try { var workflowService = new WorkflowService( rockContext ); var workflow = Workflow.Activate( workflowType, person.FullName ); List<string> workflowErrors; if ( workflow.Process( rockContext, groupMember, out workflowErrors ) ) { if ( workflow.IsPersisted || workflow.IsPersisted ) { if ( workflow.Id == 0 ) { workflowService.Add( workflow ); } rockContext.WrapTransaction( () => { rockContext.SaveChanges(); workflow.SaveAttributeValues( _rockContext ); foreach ( var activity in workflow.Activities ) { activity.SaveAttributeValues( rockContext ); } } ); } } } catch (Exception ex) { ExceptionLogService.LogException( ex, this.Context ); } } } } }
/// <summary> /// Handles the Click event of the lbConnect 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 lbConnect_Click( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { var connectionRequestService = new ConnectionRequestService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); var connectionActivityTypeService = new ConnectionActivityTypeService( rockContext ); var connectionRequestActivityService = new ConnectionRequestActivityService( rockContext ); var connectionRequest = connectionRequestService.Get( hfConnectionRequestId.ValueAsInt() ); if ( connectionRequest != null && connectionRequest.PersonAlias != null && connectionRequest.ConnectionOpportunity != null ) { bool okToConnect = true; GroupMember groupMember = null; // Only do group member placement if the request has an assigned placement group, role, and status if ( connectionRequest.AssignedGroupId.HasValue && connectionRequest.AssignedGroupMemberRoleId.HasValue && connectionRequest.AssignedGroupMemberStatus.HasValue ) { var group = new GroupService( rockContext ).Get( connectionRequest.AssignedGroupId.Value ); if ( group != null ) { // Only attempt the add if person does not already exist in group with same role groupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId( connectionRequest.AssignedGroupId.Value, connectionRequest.PersonAlias.PersonId, connectionRequest.AssignedGroupMemberRoleId.Value ); if ( groupMember == null ) { groupMember = new GroupMember(); groupMember.PersonId = connectionRequest.PersonAlias.PersonId; groupMember.GroupId = connectionRequest.AssignedGroupId.Value; groupMember.GroupRoleId = connectionRequest.AssignedGroupMemberRoleId.Value; groupMember.GroupMemberStatus = connectionRequest.AssignedGroupMemberStatus.Value; foreach ( ListItem item in cblManualRequirements.Items ) { if ( !item.Selected && group.MustMeetRequirementsToAddMember.HasValue && group.MustMeetRequirementsToAddMember.Value ) { okToConnect = false; nbRequirementsErrors.Text = "Group Requirements have not been met. Please verify all of the requirements."; nbRequirementsErrors.Visible = true; break; } else { groupMember.GroupMemberRequirements.Add( new GroupMemberRequirement { GroupRequirementId = item.Value.AsInteger(), RequirementMetDateTime = RockDateTime.Now, LastRequirementCheckDateTime = RockDateTime.Now } ); } } if ( okToConnect ) { groupMemberService.Add( groupMember ); if ( !string.IsNullOrWhiteSpace( connectionRequest.AssignedGroupMemberAttributeValues ) ) { var savedValues = JsonConvert.DeserializeObject<Dictionary<string, string>>( connectionRequest.AssignedGroupMemberAttributeValues ); if ( savedValues != null ) { groupMember.LoadAttributes(); foreach ( var item in savedValues ) { groupMember.SetAttributeValue( item.Key, item.Value ); } } } } } } } if ( okToConnect ) { // ... but always record the connection activity and change the state to connected. var guid = Rock.SystemGuid.ConnectionActivityType.CONNECTED.AsGuid(); var connectedActivityId = connectionActivityTypeService.Queryable() .Where( t => t.Guid == guid ) .Select( t => t.Id ) .FirstOrDefault(); if ( connectedActivityId > 0 ) { var connectionRequestActivity = new ConnectionRequestActivity(); connectionRequestActivity.ConnectionRequestId = connectionRequest.Id; connectionRequestActivity.ConnectionOpportunityId = connectionRequest.ConnectionOpportunityId; connectionRequestActivity.ConnectionActivityTypeId = connectedActivityId; connectionRequestActivity.ConnectorPersonAliasId = CurrentPersonAliasId; connectionRequestActivityService.Add( connectionRequestActivity ); } connectionRequest.ConnectionState = ConnectionState.Connected; rockContext.SaveChanges(); if ( groupMember != null && !string.IsNullOrWhiteSpace( connectionRequest.AssignedGroupMemberAttributeValues ) ) { groupMember.SaveAttributeValues( rockContext ); } ShowDetail( connectionRequest.Id, connectionRequest.ConnectionOpportunityId ); } } } }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); Guid? groupGuid = null; Person person = null; DateTime attendanceDateTime = DateTime.Now; bool addToGroup = true; // get the group attribute Guid groupAttributeGuid = GetAttributeValue(action, "Group").AsGuid(); if ( !groupAttributeGuid.IsEmpty() ) { groupGuid = action.GetWorklowAttributeValue(groupAttributeGuid).AsGuidOrNull(); if ( !groupGuid.HasValue ) { errorMessages.Add("The group could not be found!"); } } // get person alias guid Guid personAliasGuid = Guid.Empty; string personAttribute = GetAttributeValue( action, "Person" ); Guid guid = personAttribute.AsGuid(); if (!guid.IsEmpty()) { var attribute = AttributeCache.Read( guid, rockContext ); if ( attribute != null ) { string value = action.GetWorklowAttributeValue(guid); personAliasGuid = value.AsGuid(); } if ( personAliasGuid != Guid.Empty ) { person = new PersonAliasService(rockContext).Queryable().AsNoTracking() .Where(p => p.Guid.Equals(personAliasGuid)) .Select(p => p.Person) .FirstOrDefault(); } else { errorMessages.Add("The person could not be found in the attribute!"); } } // get attendance date Guid dateTimeAttributeGuid = GetAttributeValue(action, "AttendanceDatetime").AsGuid(); if ( !dateTimeAttributeGuid.IsEmpty() ) { string attributeDatetime = action.GetWorklowAttributeValue(dateTimeAttributeGuid); if ( !string.IsNullOrWhiteSpace(attributeDatetime) ) { if ( !DateTime.TryParse(attributeDatetime, out attendanceDateTime) ) { errorMessages.Add(string.Format("Could not parse the date provided {0}.", attributeDatetime)); } } } // get add to group addToGroup = GetAttributeValue(action, "AddToGroup").AsBoolean(); // get location Guid locationGuid = Guid.Empty; Guid locationAttributeGuid = GetAttributeValue(action, "Location").AsGuid(); if ( !locationAttributeGuid.IsEmpty() ) { var locationAttribute = AttributeCache.Read(locationAttributeGuid, rockContext); if ( locationAttribute != null ) { locationGuid = action.GetWorklowAttributeValue(locationAttributeGuid).AsGuid(); } } //// get Schedule Guid scheduleGuid = Guid.Empty; Guid scheduleAttributeGuid = GetAttributeValue( action, "Schedule" ).AsGuid(); if ( !scheduleAttributeGuid.IsEmpty() ) { var scheduleAttribute = AttributeCache.Read( scheduleAttributeGuid, rockContext ); if ( scheduleAttribute != null ) { scheduleGuid = action.GetWorklowAttributeValue( scheduleAttributeGuid ).AsGuid(); } } // set attribute if ( groupGuid.HasValue && person != null && attendanceDateTime != DateTime.MinValue ) { var group = new GroupService(rockContext).Queryable("GroupType.DefaultGroupRole") .Where(g => g.Guid == groupGuid) .FirstOrDefault(); if ( group != null ) { GroupMemberService groupMemberService = new GroupMemberService(rockContext); // get group member var groupMember = groupMemberService.Queryable() .Where(m => m.Group.Guid == groupGuid && m.PersonId == person.Id) .FirstOrDefault(); if ( groupMember == null ) { if ( addToGroup ) { if ( group != null ) { groupMember = new GroupMember(); groupMember.GroupId = group.Id; groupMember.PersonId = person.Id; groupMember.GroupMemberStatus = GroupMemberStatus.Active; groupMember.GroupRole = group.GroupType.DefaultGroupRole; groupMemberService.Add(groupMember); rockContext.SaveChanges(); } } else { action.AddLogEntry(string.Format("{0} was not a member of the group {1} and the action was not configured to add them.", person.FullName, group.Name)); } } AttendanceService attendanceService = new AttendanceService(rockContext); Attendance attendance = new Attendance(); attendance.GroupId = group.Id; attendance.PersonAliasId = person.PrimaryAliasId; attendance.StartDateTime = attendanceDateTime; attendance.CampusId = group.CampusId; attendance.DidAttend = true; if ( locationGuid != Guid.Empty ) { var location = new LocationService(rockContext).Queryable().AsNoTracking() .Where(l => l.Guid == locationGuid) .FirstOrDefault(); if ( location != null ) { attendance.LocationId = location.Id; } } attendanceService.Add(attendance); rockContext.SaveChanges(); if ( attendance.LocationId.HasValue ) { Rock.CheckIn.KioskLocationAttendance.Flush( attendance.LocationId.Value ); } } else { errorMessages.Add(string.Format("Could not find group matching the guid '{0}'.", groupGuid)); } } errorMessages.ForEach( m => action.AddLogEntry( m, true ) ); return true; }
private int? AddRegistrantToGroup( RegistrationRegistrant registrant ) { if ( registrant.PersonAliasId.HasValue && registrant.Registration != null && registrant.Registration.Group != null && registrant.Registration.Group.GroupType != null && _template != null ) { var group = registrant.Registration.Group; var groupService = new GroupService( _rockContext ); var personAliasService = new PersonAliasService( _rockContext ); var groupMemberService = new GroupMemberService( _rockContext ); var personAlias = personAliasService.Get( registrant.PersonAliasId.Value ); GroupMember groupMember = group.Members.Where( m => m.PersonId == personAlias.PersonId ).FirstOrDefault(); if ( groupMember == null ) { groupMember = new GroupMember(); groupMemberService.Add( groupMember ); groupMember.GroupId = group.Id; groupMember.PersonId = personAlias.PersonId; if ( _template.GroupTypeId.HasValue && _template.GroupTypeId == group.GroupTypeId && _template.GroupMemberRoleId.HasValue ) { groupMember.GroupRoleId = _template.GroupMemberRoleId.Value; groupMember.GroupMemberStatus = _template.GroupMemberStatus; } else { if ( group.GroupType.DefaultGroupRoleId.HasValue ) { groupMember.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value; } else { groupMember.GroupRoleId = group.GroupType.Roles.Select( r => r.Id ).FirstOrDefault(); } } } groupMember.GroupMemberStatus = GroupMemberStatus.Active; _rockContext.SaveChanges(); return groupMember.Id; } return (int?)null; }
/// <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 ( RegistrantState != null ) { RockContext rockContext = new RockContext(); var personService = new PersonService( rockContext ); var registrantService = new RegistrationRegistrantService( rockContext ); var registrantFeeService = new RegistrationRegistrantFeeService( rockContext ); var registrationTemplateFeeService = new RegistrationTemplateFeeService( rockContext ); RegistrationRegistrant registrant = null; if ( RegistrantState.Id > 0 ) { registrant = registrantService.Get( RegistrantState.Id ); } bool newRegistrant = false; var registrantChanges = new List<string>(); if ( registrant == null ) { newRegistrant = true; registrant = new RegistrationRegistrant(); registrant.RegistrationId = RegistrantState.RegistrationId; registrantService.Add( registrant ); registrantChanges.Add( "Created Registrant" ); } if ( !registrant.PersonAliasId.Equals( ppPerson.PersonAliasId ) ) { string prevPerson = ( registrant.PersonAlias != null && registrant.PersonAlias.Person != null ) ? registrant.PersonAlias.Person.FullName : string.Empty; string newPerson = ppPerson.PersonName; History.EvaluateChange( registrantChanges, "Person", prevPerson, newPerson ); } registrant.PersonAliasId = ppPerson.PersonAliasId.Value; // Get the name of registrant for history string registrantName = "Unknown"; if ( ppPerson.PersonId.HasValue ) { var person = personService.Get( ppPerson.PersonId.Value ); if ( person != null ) { registrantName = person.FullName; } } History.EvaluateChange( registrantChanges, "Cost", registrant.Cost, cbCost.Text.AsDecimal() ); registrant.Cost = cbCost.Text.AsDecimal(); if ( !Page.IsValid ) { return; } // Remove/delete any registrant fees that are no longer in UI with quantity foreach ( var dbFee in registrant.Fees.ToList() ) { if ( !RegistrantState.FeeValues.Keys.Contains( dbFee.RegistrationTemplateFeeId ) || RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId] == null || !RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId] .Any( f => f.Option == dbFee.Option && f.Quantity > 0 ) ) { registrantChanges.Add( string.Format( "Removed '{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}", dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option ) ); registrant.Fees.Remove( dbFee ); registrantFeeService.Delete( dbFee ); } } // Add/Update any of the fees from UI foreach ( var uiFee in RegistrantState.FeeValues.Where( f => f.Value != null ) ) { foreach ( var uiFeeOption in uiFee.Value ) { var dbFee = registrant.Fees .Where( f => f.RegistrationTemplateFeeId == uiFee.Key && f.Option == uiFeeOption.Option ) .FirstOrDefault(); if ( dbFee == null ) { dbFee = new RegistrationRegistrantFee(); dbFee.RegistrationTemplateFeeId = uiFee.Key; dbFee.Option = uiFeeOption.Option; registrant.Fees.Add( dbFee ); } var templateFee = dbFee.RegistrationTemplateFee; if ( templateFee == null ) { templateFee = registrationTemplateFeeService.Get( uiFee.Key ); } string feeName = templateFee != null ? templateFee.Name : "Fee"; if ( !string.IsNullOrWhiteSpace( uiFeeOption.Option ) ) { feeName = string.Format( "{0} ({1})", feeName, uiFeeOption.Option ); } if ( dbFee.Id <= 0 ) { registrantChanges.Add( feeName + " Fee Added" ); } History.EvaluateChange( registrantChanges, feeName + " Quantity", dbFee.Quantity, uiFeeOption.Quantity ); dbFee.Quantity = uiFeeOption.Quantity; History.EvaluateChange( registrantChanges, feeName + " Cost", dbFee.Cost, uiFeeOption.Cost ); dbFee.Cost = uiFeeOption.Cost; } } if ( !registrant.IsValid ) { // Controls will render the error messages return; } // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges() rockContext.WrapTransaction( () => { rockContext.SaveChanges(); registrant.LoadAttributes(); foreach ( var field in TemplateState.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.RegistrationAttribute && t.AttributeId.HasValue ) ) ) { var attribute = AttributeCache.Read( field.AttributeId.Value ); if ( attribute != null ) { string originalValue = registrant.GetAttributeValue( attribute.Key ); var fieldValue = RegistrantState.FieldValues .Where( f => f.Key == field.Id ) .Select( f => f.Value.FieldValue ) .FirstOrDefault(); string newValue = fieldValue != null ? fieldValue.ToString() : string.Empty; if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() ) { string formattedOriginalValue = string.Empty; if ( !string.IsNullOrWhiteSpace( originalValue ) ) { formattedOriginalValue = attribute.FieldType.Field.FormatValue( null, originalValue, attribute.QualifierValues, false ); } string formattedNewValue = string.Empty; if ( !string.IsNullOrWhiteSpace( newValue ) ) { formattedNewValue = attribute.FieldType.Field.FormatValue( null, newValue, attribute.QualifierValues, false ); } History.EvaluateChange( registrantChanges, attribute.Name, formattedOriginalValue, formattedNewValue ); } if ( fieldValue != null ) { registrant.SetAttributeValue( attribute.Key, fieldValue.ToString() ); } } } registrant.SaveAttributeValues( rockContext ); } ); if ( newRegistrant && TemplateState.GroupTypeId.HasValue && ppPerson.PersonId.HasValue ) { using ( var newRockContext = new RockContext() ) { var reloadedRegistrant = new RegistrationRegistrantService( newRockContext ).Get( registrant.Id ); if ( reloadedRegistrant != null && reloadedRegistrant.Registration != null && reloadedRegistrant.Registration.Group != null && reloadedRegistrant.Registration.Group.GroupTypeId == TemplateState.GroupTypeId.Value ) { int? groupRoleId = TemplateState.GroupMemberRoleId.HasValue ? TemplateState.GroupMemberRoleId.Value : reloadedRegistrant.Registration.Group.GroupType.DefaultGroupRoleId; if ( groupRoleId.HasValue ) { var groupMemberService = new GroupMemberService( newRockContext ); var groupMember = groupMemberService .Queryable().AsNoTracking() .Where( m => m.GroupId == reloadedRegistrant.Registration.Group.Id && m.PersonId == reloadedRegistrant.PersonId && m.GroupRoleId == groupRoleId.Value ) .FirstOrDefault(); if ( groupMember == null ) { groupMember = new GroupMember(); groupMemberService.Add( groupMember ); groupMember.GroupId = reloadedRegistrant.Registration.Group.Id; groupMember.PersonId = ppPerson.PersonId.Value; groupMember.GroupRoleId = groupRoleId.Value; groupMember.GroupMemberStatus = TemplateState.GroupMemberStatus; newRockContext.SaveChanges(); registrantChanges.Add( string.Format( "Registrant added to {0} group", reloadedRegistrant.Registration.Group.Name ) ); } else { registrantChanges.Add( string.Format( "Registrant group member reference updated to existing person in {0} group", reloadedRegistrant.Registration.Group.Name ) ); } reloadedRegistrant.GroupMemberId = groupMember.Id; newRockContext.SaveChanges(); } } } } HistoryService.SaveChanges( rockContext, typeof( Registration ), Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(), registrant.RegistrationId, registrantChanges, "Registrant: " + registrantName, null, null ); } NavigateToRegistration(); }
/// <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 ); } } } ); } }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); // Determine which group to add the person to Group group = null; int? groupRoleId = null; var guidGroupAttribute = GetAttributeValue( action, "Group" ).AsGuidOrNull(); if ( guidGroupAttribute.HasValue ) { var attributeGroup = AttributeCache.Read( guidGroupAttribute.Value, rockContext ); if ( attributeGroup != null ) { var groupGuid = action.GetWorklowAttributeValue( guidGroupAttribute.Value ).AsGuidOrNull(); if ( groupGuid.HasValue ) { group = new GroupService( rockContext ).Get( groupGuid.Value ); if ( group != null ) { // use the group's grouptype's default group role if a group role wasn't specified groupRoleId = group.GroupType.DefaultGroupRoleId; } } } } if ( group == null ) { errorMessages.Add( "No group was provided" ); } if ( !groupRoleId.HasValue ) { errorMessages.Add( "Provided group doesn't have a default group role" ); } // determine the person that will be added to the group Person person = null; // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value var guidPersonAttribute = GetAttributeValue( action, "Person" ).AsGuidOrNull(); if ( guidPersonAttribute.HasValue ) { var attributePerson = AttributeCache.Read( guidPersonAttribute.Value, rockContext ); if ( attributePerson != null ) { string attributePersonValue = action.GetWorklowAttributeValue( guidPersonAttribute.Value ); if ( !string.IsNullOrWhiteSpace( attributePersonValue ) ) { if ( attributePerson.FieldType.Class == typeof( Rock.Field.Types.PersonFieldType ).FullName ) { Guid personAliasGuid = attributePersonValue.AsGuid(); if ( !personAliasGuid.IsEmpty() ) { person = new PersonAliasService( rockContext ).Queryable() .Where( a => a.Guid.Equals( personAliasGuid ) ) .Select( a => a.Person ) .FirstOrDefault(); } } else { errorMessages.Add( "The attribute used to provide the person was not of type 'Person'." ); } } } } if ( person == null ) { errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString() ) ); } // Add Person to Group if ( !errorMessages.Any() ) { var groupMemberService = new GroupMemberService( rockContext ); var groupMember = new GroupMember(); groupMember.PersonId = person.Id; groupMember.GroupId = group.Id; groupMember.GroupRoleId = groupRoleId.Value; groupMember.GroupMemberStatus = GroupMemberStatus.Active; if ( groupMember.IsValid ) { groupMemberService.Add( groupMember ); rockContext.SaveChanges(); } else { // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages errorMessages.AddRange( groupMember.ValidationResults.Select( a => a.ErrorMessage ) ); } } errorMessages.ForEach( m => action.AddLogEntry( m, true ) ); return true; }