private Group CreateTestGroup(RockContext rockContext, ElevatedSecurityLevel elevatedSecurityLevel) { var groupGuid = Guid.NewGuid(); var groupTypeGuid = Guid.NewGuid(); var group = new Group { Name = $"Test Group {groupGuid}", IsSecurityRole = true, Guid = groupGuid, ElevatedSecurityLevel = elevatedSecurityLevel, GroupType = new GroupType { Name = $"Test Group Type {groupTypeGuid}", Guid = groupTypeGuid, }, }; var groupService = new GroupService(rockContext); groupService.Add(group); rockContext.SaveChanges(); var groupTypeRole = new GroupTypeRole { Name = "Test Role", GroupTypeId = group.GroupTypeId }; var groupTypeRoleService = new GroupTypeRoleService(rockContext); groupTypeRoleService.Add(groupTypeRole); rockContext.SaveChanges(); return(group); }
/// <summary> /// Checks the settings. /// </summary> /// <returns></returns> private bool CheckSettings() { _rockContext = _rockContext ?? new RockContext(); if (CurrentGroup == null) { NavigateToHomePage(); return(false); } //Authorization check. Nothing is visible otherwise if (!CurrentGroup.IsAuthorized(Authorization.EDIT, CurrentPerson)) { return(false); } _defaultGroupRole = CurrentGroup.GroupType.DefaultGroupRole; _dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid()); if (_dvcConnectionStatus == null) { return(false); } _dvcRecordStatus = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid()); if (_dvcRecordStatus == null) { return(false); } return(true); }
private void SendToParentGroupRole(Group group, Group parentGroup, GroupTypeRole groupRole, Dictionary <int, List <DateTime> > occurrences, GroupMemberService groupMemberService, string staffEmail) { // Get the members with the specific role of those groups var roleMembers = groupMemberService .Queryable("Group,Person").AsNoTracking() .Where(m => m.GroupId.Equals(parentGroup.Id) && m.GroupMemberStatus == GroupMemberStatus.Active && m.GroupRoleId.Equals(groupRole.Id) && m.Person.Email != null && m.Person.Email != string.Empty) .ToList(); if (roleMembers.Count > 0) { // Loop through the members with specific role foreach (var member in roleMembers) { foreach (var occGroup in occurrences.Where(o => o.Key == group.Id)) { SendEmailToMember(member, group, occGroup); } } } else { if (parentGroup.ParentGroupId.HasValue) { SendToParentGroupRole(group, parentGroup.ParentGroup, groupRole, occurrences, groupMemberService, staffEmail); } } }
/// <summary> /// Initializes a new instance of the <see cref="GroupTypeRoleCache"/> class. /// </summary> /// <param name="role">The role.</param> public GroupTypeRoleCache(GroupTypeRole role) { Id = role.Id; Guid = role.Guid; Name = role.Name; Order = role.Order; MaxCount = role.MaxCount; MinCount = role.MinCount; IsLeader = role.IsLeader; CanView = role.CanView; CanEdit = role.CanEdit; }
/// <summary> /// Checks the settings. /// </summary> /// <returns></returns> private bool CheckSettings() { _rockContext = _rockContext ?? new RockContext(); _mode = GetAttributeValue("Mode"); int groupId = PageParameter("GroupId").AsInteger(); _group = new GroupService(_rockContext) .Queryable("GroupType.DefaultGroupRole").AsNoTracking() .FirstOrDefault(g => g.Id == groupId); if (_group == null) { nbNotice.Heading = "Unknown Group"; nbNotice.Text = "<p>This page requires a valid group id parameter, and there was not one provided.</p>"; return(false); } else { _defaultGroupRole = _group.GroupType.DefaultGroupRole; } _dvcConnectionStatus = DefinedValueCache.Read(GetAttributeValue("ConnectionStatus").AsGuid()); if (_dvcConnectionStatus == null) { nbNotice.Heading = "Invalid Connection Status"; nbNotice.Text = "<p>The selected Connection Status setting does not exist.</p>"; return(false); } _dvcRecordStatus = DefinedValueCache.Read(GetAttributeValue("RecordStatus").AsGuid()); if (_dvcRecordStatus == null) { nbNotice.Heading = "Invalid Record Status"; nbNotice.Text = "<p>The selected Record Status setting does not exist.</p>"; return(false); } _married = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid()); _homeAddressType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()); _familyType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()); _adultRole = _familyType.Roles.FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())); if (_married == null || _homeAddressType == null || _familyType == null || _adultRole == null) { nbNotice.Heading = "Missing System Value"; nbNotice.Text = "<p>There is a missing or invalid system value. Check the settings for Marital Status of 'Married', Location Type of 'Home', Group Type of 'Family', and Family Group Role of 'Adult'.</p>"; return(false); } return(true); }
/// <summary> /// Checks the settings. /// </summary> /// <returns></returns> private bool CheckSettings() { _rockContext = _rockContext ?? new RockContext(); if (CurrentGroup == null) { NavigateToHomePage(); return(false); } //Authorization check. Nothing is visible otherwise if (!CurrentGroup.IsAuthorized(Authorization.EDIT, CurrentPerson)) { return(false); } _defaultGroupRole = CurrentGroup.GroupType.DefaultGroupRole; _dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid()); if (_dvcConnectionStatus == null) { return(false); } _dvcRecordStatus = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid()); if (_dvcRecordStatus == null) { return(false); } _homeAddressType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()); _familyType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()); _adultRole = _familyType.Roles.FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())); if (!GetAttributeValue("LargeButton").AsBoolean()) { btnLaunchModal.Text = "<i class='fa fa-user-plus'></i>"; } if (!string.IsNullOrWhiteSpace(GetAttributeValue("CSSClass"))) { btnLaunchModal.CssClass = GetAttributeValue("CSSClass"); } return(true); }
/// <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>(); Person person = GetEntityFromWorkflowAttributes(action, "Person", "PersonAttribute", new PersonAliasService(rockContext))?.Person; Group group = GetEntityFromWorkflowAttributes(action, "Group", "GroupAttribute", new GroupService(rockContext)); GroupTypeRole groupRole = GetEntityFromWorkflowAttributes(action, "GroupRole", "GroupRoleAttribute", new GroupTypeRoleService(rockContext)); if (person == null) { errorMessages.Add("Invalid Person."); } if (group == null) { errorMessages.Add("Invalid Group."); } if (person == null || group == null || errorMessages.Any()) { errorMessages.ForEach(m => action.AddLogEntry(m, true)); return(false); } var groupMemberService = new GroupMemberService(rockContext); IQueryable <GroupMember> groupMemberships = groupMemberService.Queryable().Where(gm => gm.GroupId == group.Id && gm.PersonId == person.Id); if (groupRole != null) { groupMemberships = groupMemberships.Where(gm => gm.GroupRoleId == groupRole.Id); } foreach (GroupMember groupMember in groupMemberships) { groupMemberService.Delete(groupMember); } rockContext.SaveChanges(); errorMessages.ForEach(m => action.AddLogEntry(m, true)); return(true); }
/// <summary> /// Initializes a new instance of the <see cref="GroupTypeRoleCache"/> class. /// </summary> /// <param name="role">The role.</param> public GroupTypeRoleCache(GroupTypeRole role) { if (role == null) { return; } Id = role.Id; Guid = role.Guid; Name = role.Name; Order = role.Order; MaxCount = role.MaxCount; MinCount = role.MinCount; IsLeader = role.IsLeader; CanView = role.CanView; CanEdit = role.CanEdit; CanManageMembers = role.CanManageMembers; }
private void CheckinAreaRow_AddAreaClick(object sender, EventArgs e) { var parentRow = sender as CheckinAreaRow; parentRow.Expanded = true; using (var rockContext = new RockContext()) { var groupTypeService = new GroupTypeService(rockContext); var parentArea = groupTypeService.Get(parentRow.GroupTypeGuid); if (parentArea != null) { Guid newGuid = Guid.NewGuid(); var checkinArea = new GroupType(); checkinArea.Guid = newGuid; checkinArea.Name = "New Area"; checkinArea.IsSystem = false; checkinArea.ShowInNavigation = false; checkinArea.TakesAttendance = true; checkinArea.AttendanceRule = AttendanceRule.None; checkinArea.AttendancePrintTo = PrintTo.Default; checkinArea.AllowMultipleLocations = true; checkinArea.EnableLocationSchedules = true; checkinArea.Order = parentArea.ChildGroupTypes.Any() ? parentArea.ChildGroupTypes.Max(t => t.Order) + 1 : 0; GroupTypeRole defaultRole = new GroupTypeRole(); defaultRole.Name = "Member"; checkinArea.Roles.Add(defaultRole); parentArea.ChildGroupTypes.Add(checkinArea); rockContext.SaveChanges(); GroupTypeCache.Flush(parentArea.Id); Rock.CheckIn.KioskDevice.FlushAll(); SelectArea(newGuid); } } BuildRows(); }
/// <summary> /// Handles the SaveClick event of the mdAddCheckinGroupType 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 mdAddCheckinGroupType_SaveClick(object sender, EventArgs e) { using (var rockContext = new RockContext()) { var groupTypeService = new GroupTypeService(rockContext); GroupType groupType; if (hfGroupTypeId.Value.AsInteger() == 0) { groupType = new GroupType(); groupTypeService.Add(groupType); groupType.GroupTypePurposeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE).Id; groupType.ShowInNavigation = false; groupType.ShowInGroupList = false; var defaultRole = new GroupTypeRole(); defaultRole.Name = "Member"; groupType.Roles.Add(defaultRole); } else { groupType = groupTypeService.Get(hfGroupTypeId.Value.AsInteger()); } groupType.Name = tbGroupTypeName.Text; groupType.Description = tbGroupTypeDescription.Text; rockContext.SaveChanges(); // Reload to check for setting default role groupType = groupTypeService.Get(groupType.Id); if (groupType != null && !groupType.DefaultGroupRoleId.HasValue && groupType.Roles.Any()) { groupType.DefaultGroupRoleId = groupType.Roles.First().Id; rockContext.SaveChanges(); } } mdAddEditCheckinGroupType.Hide(); BindGrid(); }
protected void lbAddArea_Click(object sender, EventArgs e) { using (var rockContext = new RockContext()) { var groupTypeService = new GroupTypeService(rockContext); var parentGroupType = groupTypeService.Get(PageParameter("CheckInTypeId").AsInteger()); if (parentGroupType != null) { Guid newGuid = Guid.NewGuid(); var checkinArea = new GroupType(); checkinArea.Guid = newGuid; checkinArea.Name = "New Area"; checkinArea.IsSystem = false; checkinArea.ShowInNavigation = false; checkinArea.TakesAttendance = true; checkinArea.AttendanceRule = AttendanceRule.None; checkinArea.AttendancePrintTo = PrintTo.Default; checkinArea.AllowMultipleLocations = true; checkinArea.EnableLocationSchedules = true; checkinArea.Order = parentGroupType.ChildGroupTypes.Any() ? parentGroupType.ChildGroupTypes.Max(t => t.Order) + 1 : 0; GroupTypeRole defaultRole = new GroupTypeRole(); defaultRole.Name = "Member"; checkinArea.Roles.Add(defaultRole); parentGroupType.ChildGroupTypes.Add(checkinArea); rockContext.SaveChanges(); Rock.CheckIn.KioskDevice.Clear(); SelectArea(newGuid); } } BuildRows(); }
/// <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>(); // Get the Person, Group and GroupRole from the attributes Person person = GetEntityFromWorkflowAttributes(action, "Person", "PersonAttribute", new PersonAliasService(rockContext))?.Person; Group group = GetEntityFromWorkflowAttributes(action, "Group", "GroupAttribute", new GroupService(rockContext)); GroupTypeRole groupRole = GetEntityFromWorkflowAttributes(action, "GroupRole", "GroupRoleAttribute", new GroupTypeRoleService(rockContext)) ?? group?.GroupType?.DefaultGroupRole; GroupMemberStatus?groupMemberStatus = null; Guid?groupMemberWorkflowAttributeAttribute = GetAttributeValue(action, "GroupMemberStatusAttribute").AsGuidOrNull(); if (groupMemberWorkflowAttributeAttribute.HasValue) { string groupMemberWorkflowAttribute = action.GetWorkflowAttributeValue(groupMemberWorkflowAttributeAttribute.Value); if (!string.IsNullOrWhiteSpace(groupMemberWorkflowAttribute)) { if (Enum.TryParse(groupMemberWorkflowAttribute, true, out GroupMemberStatus groupMemberStatusOut)) { groupMemberStatus = groupMemberStatusOut; } } } if (groupMemberStatus == null) { string groupMemberAttribute = GetAttributeValue(action, "GroupMemberStatus"); if (!string.IsNullOrWhiteSpace(groupMemberAttribute)) { if (Enum.TryParse(groupMemberAttribute, true, out GroupMemberStatus groupMemberStatusOut)) { groupMemberStatus = groupMemberStatusOut; } } } if (person == null) { errorMessages.Add("Invalid Person."); } if (group == null) { errorMessages.Add("Invalid Group."); } if (groupRole == null) { errorMessages.Add("Invalid Group Role."); } if (person == null || group == null || groupRole == null || errorMessages.Any()) { errorMessages.ForEach(m => action.AddLogEntry(m, true)); return(false); } if (group.Members.Any(m => m.PersonId == person.Id && m.GroupRoleId == groupRole.Id)) { action.AddLogEntry("Skipping adding duplicate Group Member."); } else { var groupMember = new GroupMember { PersonId = person.Id, GroupId = group.Id, GroupRoleId = groupRole.Id, GroupMemberStatus = groupMemberStatus ?? GroupMemberStatus.Pending }; if (groupMember.IsValid) { new GroupMemberService(rockContext).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); }
protected GroupTypeRole GetInverseRole( GroupTypeRole role, GroupTypeRoleService groupRoleServ ) { role.LoadAttributes(); return groupRoleServ.Get( role.GetAttributeValue( "InverseRelationship" ).AsGuid() ); }
/// <summary> /// Checks the settings. If false is returned, it's expected that the caller will make /// the nbNotice visible to inform the user of the "settings" error. /// </summary> /// <returns>true if settings are valid; false otherwise</returns> private bool CheckSettings() { _rockContext = _rockContext ?? new RockContext(); _mode = GetAttributeValue("Mode"); _autoFill = GetAttributeValue("AutoFillForm").AsBoolean(); string registerButtonText = GetAttributeValue("RegisterButtonAltText"); if (string.IsNullOrWhiteSpace(registerButtonText)) { registerButtonText = "Register"; } btnRegister.Text = registerButtonText; var groupService = new GroupService(_rockContext); bool groupIsFromQryString = true; Guid?groupGuid = GetAttributeValue("Group").AsGuidOrNull(); if (groupGuid.HasValue) { _group = groupService.Get(groupGuid.Value); groupIsFromQryString = false; } if (_group == null) { groupGuid = PageParameter("GroupGuid").AsGuidOrNull(); if (groupGuid.HasValue) { _group = groupService.Get(groupGuid.Value); } } if (_group == null && GetAttributeValue("EnablePassingGroupId").AsBoolean(false)) { int?groupId = PageParameter("GroupId").AsIntegerOrNull(); if (groupId.HasValue) { _group = groupService.Get(groupId.Value); } } if (_group == null) { nbNotice.Heading = "Unknown Group"; nbNotice.Text = "<p>This page requires a valid group identifying parameter and there was not one provided.</p>"; return(false); } else { var groupTypeGuids = this.GetAttributeValue("AllowedGroupTypes").SplitDelimitedValues().AsGuidList(); if (groupIsFromQryString && groupTypeGuids.Any() && !groupTypeGuids.Contains(_group.GroupType.Guid)) { _group = null; nbNotice.Heading = "Invalid Group"; nbNotice.Text = "<p>The selected group is a restricted group type therefore this block cannot be used to add people to these groups (unless configured to allow).</p>"; return(false); } else { _defaultGroupRole = _group.GroupType.DefaultGroupRole; } } _dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid()); if (_dvcConnectionStatus == null) { nbNotice.Heading = "Invalid Connection Status"; nbNotice.Text = "<p>The selected Connection Status setting does not exist.</p>"; return(false); } _dvcRecordStatus = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid()); if (_dvcRecordStatus == null) { nbNotice.Heading = "Invalid Record Status"; nbNotice.Text = "<p>The selected Record Status setting does not exist.</p>"; return(false); } _married = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid()); _homeAddressType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()); _familyType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()); _adultRole = _familyType.Roles.FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())); if (_married == null || _homeAddressType == null || _familyType == null || _adultRole == null) { nbNotice.Heading = "Missing System Value"; nbNotice.Text = "<p>There is a missing or invalid system value. Check the settings for Marital Status of 'Married', Location Type of 'Home', Group Type of 'Family', and Family Group Role of 'Adult'.</p>"; return(false); } return(true); }
/// <summary> /// Checks the settings. /// </summary> /// <returns></returns> private bool CheckSettings() { _rockContext = _rockContext ?? new RockContext(); _mode = GetAttributeValue( "Mode" ); _autoFill = GetAttributeValue( "AutoFillForm" ).AsBoolean(); tbEmail.Required = _autoFill; string registerButtonText = GetAttributeValue( "RegisterButtonAltText" ); if ( string.IsNullOrWhiteSpace( registerButtonText ) ) { registerButtonText = "Register"; } btnRegister.Text = registerButtonText; var groupService = new GroupService( _rockContext ); bool groupIsFromQryString = true; Guid? groupGuid = GetAttributeValue( "Group" ).AsGuidOrNull(); if ( groupGuid.HasValue ) { _group = groupService.Get( groupGuid.Value ); groupIsFromQryString = false; } if ( _group == null ) { groupGuid = PageParameter( "GroupGuid" ).AsGuidOrNull(); if ( groupGuid.HasValue ) { _group = groupService.Get( groupGuid.Value ); } } if ( _group == null ) { int? groupId = PageParameter( "GroupId" ).AsIntegerOrNull(); if ( groupId.HasValue ) { _group = groupService.Get( groupId.Value ); } } if ( _group == null ) { nbNotice.Heading = "Unknown Group"; nbNotice.Text = "<p>This page requires a valid group id parameter, and there was not one provided.</p>"; return false; } else { if ( groupIsFromQryString && ( _group.IsSecurityRole || _group.GroupType.Guid == Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) { nbNotice.Heading = "Invalid Group"; nbNotice.Text = "<p>The selected group is a security group and this block cannot be used to add people to a security group (unless configured for that specific group).</p>"; return false; } else { _defaultGroupRole = _group.GroupType.DefaultGroupRole; } } _dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() ); if ( _dvcConnectionStatus == null ) { nbNotice.Heading = "Invalid Connection Status"; nbNotice.Text = "<p>The selected Connection Status setting does not exist.</p>"; return false; } _dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() ); if ( _dvcRecordStatus == null ) { nbNotice.Heading = "Invalid Record Status"; nbNotice.Text = "<p>The selected Record Status setting does not exist.</p>"; return false; } _married = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid() ); _homeAddressType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid() ); _familyType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid() ); _adultRole = _familyType.Roles.FirstOrDefault( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) ); if ( _married == null || _homeAddressType == null || _familyType == null || _adultRole == null ) { nbNotice.Heading = "Missing System Value"; nbNotice.Text = "<p>There is a missing or invalid system value. Check the settings for Marital Status of 'Married', Location Type of 'Home', Group Type of 'Family', and Family Group Role of 'Adult'.</p>"; return false; } return true; }
/// <summary> /// Shows the dialog. /// </summary> /// <param name="setValues">if set to <c>true</c> [set values].</param> private void ShowDialog( bool setValues = false ) { switch ( hfActiveDialog.Value ) { case "GROUPTYPEROLES": var role = GroupTypeRolesState.FirstOrDefault( r => r.Guid.Equals( hfRoleGuid.Value.AsGuid() ) ); if ( role == null ) { role = new GroupTypeRole(); role.GroupTypeId = hfGroupTypeId.ValueAsInt(); role.LoadAttributes(); } Helper.AddEditControls( role, phGroupTypeRoleAttributes, setValues, dlgGroupTypeRoles.ValidationGroup ); SetValidationGroup( phGroupTypeRoleAttributes.Controls, dlgGroupTypeRoles.ValidationGroup ); dlgGroupTypeRoles.Show(); break; case "CHILDGROUPTYPES": dlgChildGroupType.Show(); break; case "SCHEDULEEXCLUSION": dlgScheduleExclusion.Show(); break; case "LOCATIONTYPE": dlgLocationType.Show(); break; case "GROUPTYPEATTRIBUTES": dlgGroupTypeAttribute.Show(); break; case "GROUPATTRIBUTES": if (cbEnableIndexing.Visible && cbEnableIndexing.Checked ) { edtGroupAttributes.IsIndexingEnabledVisible = true; } else { edtGroupAttributes.IsIndexingEnabledVisible = false; } dlgGroupAttribute.Show(); break; case "GROUPMEMBERATTRIBUTES": dlgGroupMemberAttribute.Show(); break; case "MEMBERWORKFLOWTRIGGERS": dlgMemberWorkflowTriggers.Show(); break; } }
/// <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 ) { GroupType groupType; var rockContext = new RockContext(); GroupTypeService groupTypeService = new GroupTypeService( rockContext ); GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService( rockContext ); AttributeService attributeService = new AttributeService( rockContext ); AttributeQualifierService qualifierService = new AttributeQualifierService( rockContext ); CategoryService categoryService = new CategoryService( rockContext ); GroupScheduleExclusionService scheduleExclusionService = new GroupScheduleExclusionService( rockContext ); int groupTypeId = int.Parse( hfGroupTypeId.Value ); if ( groupTypeId == 0 ) { groupType = new GroupType(); groupTypeService.Add( groupType ); } else { groupType = groupTypeService.Get( groupTypeId ); // selected roles var selectedRoleGuids = GroupTypeRolesState.Select( r => r.Guid ); foreach ( var role in groupType.Roles.Where( r => !selectedRoleGuids.Contains( r.Guid ) ).ToList() ) { groupType.Roles.Remove( role ); groupTypeRoleService.Delete( role ); } } foreach ( var roleState in GroupTypeRolesState ) { GroupTypeRole role = groupType.Roles.Where( r => r.Guid == roleState.Guid ).FirstOrDefault(); if ( role == null ) { role = new GroupTypeRole(); groupType.Roles.Add( role ); } else { roleState.Id = role.Id; roleState.Guid = role.Guid; } role.CopyPropertiesFrom( roleState ); } ScheduleType allowedScheduleTypes = ScheduleType.None; foreach( ListItem li in cblScheduleTypes.Items ) { if ( li.Selected ) { allowedScheduleTypes = allowedScheduleTypes | (ScheduleType)li.Value.AsInteger(); } } GroupLocationPickerMode locationSelectionMode = GroupLocationPickerMode.None; foreach ( ListItem li in cblLocationSelectionModes.Items ) { if ( li.Selected ) { locationSelectionMode = locationSelectionMode | (GroupLocationPickerMode)li.Value.AsInteger(); } } groupType.Name = tbName.Text; groupType.Description = tbDescription.Text; groupType.GroupTerm = tbGroupTerm.Text; groupType.GroupMemberTerm = tbGroupMemberTerm.Text; groupType.ShowInGroupList = cbShowInGroupList.Checked; groupType.ShowInNavigation = cbShowInNavigation.Checked; groupType.IconCssClass = tbIconCssClass.Text; groupType.TakesAttendance = cbTakesAttendance.Checked; groupType.SendAttendanceReminder = cbSendAttendanceReminder.Checked; groupType.AttendanceRule = ddlAttendanceRule.SelectedValueAsEnum<AttendanceRule>(); groupType.AttendancePrintTo = ddlPrintTo.SelectedValueAsEnum<PrintTo>(); groupType.AllowedScheduleTypes = allowedScheduleTypes; groupType.LocationSelectionMode = locationSelectionMode; groupType.GroupTypePurposeValueId = ddlGroupTypePurpose.SelectedValueAsInt(); groupType.AllowMultipleLocations = cbAllowMultipleLocations.Checked; groupType.InheritedGroupTypeId = gtpInheritedGroupType.SelectedGroupTypeId; groupType.EnableLocationSchedules = cbEnableLocationSchedules.Checked; groupType.ChildGroupTypes = new List<GroupType>(); groupType.ChildGroupTypes.Clear(); foreach ( var item in ChildGroupTypesDictionary ) { var childGroupType = groupTypeService.Get( item.Key ); if ( childGroupType != null ) { groupType.ChildGroupTypes.Add( childGroupType ); } } // Delete any removed exclusions foreach ( var exclusion in groupType.GroupScheduleExclusions.Where( s => !ScheduleExclusionDictionary.Keys.Contains( s.Guid ) ).ToList() ) { groupType.GroupScheduleExclusions.Remove( exclusion ); scheduleExclusionService.Delete( exclusion ); } // Update exclusions foreach( var keyVal in ScheduleExclusionDictionary ) { var scheduleExclusion = groupType.GroupScheduleExclusions .FirstOrDefault( s => s.Guid.Equals( keyVal.Key)); if ( scheduleExclusion == null ) { scheduleExclusion = new GroupScheduleExclusion(); groupType.GroupScheduleExclusions.Add( scheduleExclusion); } scheduleExclusion.StartDate = keyVal.Value.Start; scheduleExclusion.EndDate = keyVal.Value.End; } DefinedValueService definedValueService = new DefinedValueService( rockContext ); groupType.LocationTypes = new List<GroupTypeLocationType>(); groupType.LocationTypes.Clear(); foreach ( var item in LocationTypesDictionary ) { var locationType = definedValueService.Get( item.Key ); if ( locationType != null ) { groupType.LocationTypes.Add( new GroupTypeLocationType { LocationTypeValueId = locationType.Id } ); } } if ( !groupType.IsValid ) { // Controls will render the error messages return; } // need WrapTransaction due to Attribute saves rockContext.WrapTransaction( () => { rockContext.SaveChanges(); /* Save Attributes */ string qualifierValue = groupType.Id.ToString(); SaveAttributes( new GroupType().TypeId, "Id", qualifierValue, GroupTypeAttributesState, rockContext ); SaveAttributes( new Group().TypeId, "GroupTypeId", qualifierValue, GroupAttributesState, rockContext ); SaveAttributes( new GroupMember().TypeId, "GroupTypeId", qualifierValue, GroupMemberAttributesState, rockContext ); // Reload to save default role groupType = groupTypeService.Get( groupType.Id ); groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault( r => r.Guid.Equals( DefaultRoleGuid ) ); if ( groupType.DefaultGroupRole == null ) { groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault(); } rockContext.SaveChanges(); // Reload the roles and apply their attribute values foreach ( var role in groupTypeRoleService.GetByGroupTypeId( groupType.Id ).ToList() ) { role.LoadAttributes( rockContext ); var roleState = GroupTypeRolesState.Where( r => r.Guid.Equals( role.Guid ) ).FirstOrDefault(); if ( roleState != null && roleState.AttributeValues != null ) { foreach ( var attributeValue in roleState.AttributeValues ) { role.SetAttributeValue( attributeValue.Key, roleState.GetAttributeValue( attributeValue.Key ) ); } role.SaveAttributeValues( rockContext ); } } } ); GroupTypeCache.Flush( groupType.Id ); NavigateToParentPage(); }
/// <summary> /// Gs the group attributes_ show edit. /// </summary> /// <param name="attributeGuid">The attribute GUID.</param> protected void gGroupTypeRoles_ShowEdit( Guid groupTypeRoleGuid ) { GroupTypeRole groupTypeRole; if ( groupTypeRoleGuid.Equals( Guid.Empty ) ) { groupTypeRole = new GroupTypeRole(); groupTypeRole.GroupTypeId = hfGroupTypeId.ValueAsInt(); groupTypeRole.LoadAttributes(); dlgGroupTypeRoles.Title = "Add Role"; } else { groupTypeRole = GroupTypeRolesState.First( a => a.Guid.Equals( groupTypeRoleGuid ) ); dlgGroupTypeRoles.Title = "Edit Role"; } hfRoleId.Value = groupTypeRole.Id.ToString(); hfRoleGuid.Value = groupTypeRole.Guid.ToString(); tbRoleName.Text = groupTypeRole.Name; tbRoleDescription.Text = groupTypeRole.Description; string groupTerm = string.IsNullOrWhiteSpace( tbGroupTerm.Text ) ? "Group" : tbGroupTerm.Text; string memberTerm = string.IsNullOrWhiteSpace( tbGroupMemberTerm.Text ) ? "Member" : tbGroupMemberTerm.Text; nbMinimumRequired.Text = groupTypeRole.MinCount.HasValue ? groupTypeRole.MinCount.ToString() : ""; nbMinimumRequired.Help = string.Format( "The minimum number of {0} in this {1} that are required to have this role.", memberTerm.Pluralize(), groupTerm ); nbMaximumAllowed.Text = groupTypeRole.MaxCount.HasValue ? groupTypeRole.MaxCount.ToString() : ""; nbMaximumAllowed.Help = string.Format( "The maximum number of {0} in this {1} that are allowed to have this role.", memberTerm.Pluralize(), groupTerm ); ShowDialog( "GroupTypeRoles", true ); }
/// <summary> /// Loads the individual data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadIndividuals(CsvDataModel csvData) { var lookupContext = new RockContext(); var groupTypeRoleService = new GroupTypeRoleService(lookupContext); var groupMemberService = new GroupMemberService(lookupContext); // Marital statuses: Married, Single, Separated, etc var maritalStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS), lookupContext).DefinedValues; // Connection statuses: Member, Visitor, Attendee, etc var connectionStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS), lookupContext).DefinedValues; int memberConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER)).Id; int visitorConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR)).Id; int attendeeConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE)).Id; // Suffix type: Dr., Jr., II, etc var suffixTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_SUFFIX), lookupContext).DefinedValues; // Title type: Mr., Mrs. Dr., etc var titleTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_TITLE), lookupContext).DefinedValues; // Record statuses: Active, Inactive, Pending int?recordStatusActiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE), lookupContext).Id; int?recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE), lookupContext).Id; int?recordStatusPendingId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING), lookupContext).Id; // Deceased record status reason (others available: No Activity, Moved, etc) var recordStatusDeceasedId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_REASON_DECEASED)).Id; // Record type: Person int?personRecordTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON), lookupContext).Id; // Group roles: Owner, Adult, Child, others GroupTypeRole ownerRole = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER)); int adultRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id; int childRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)).Id; // Phone types: Home, Work, Mobile var numberTypeValues = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext).DefinedValues; // Timeline note type id var noteTimelineTypeId = new NoteTypeService(lookupContext).Get(new Guid("7E53487C-D650-4D85-97E2-350EB8332763")).Id; // School defined type var schoolDefinedType = DefinedTypeCache.Read(new Guid("576FF1E2-6225-4565-A16D-230E26167A3D")); // Look up additional Person attributes (existing) var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).ToList(); // Core attributes: PreviousChurch, Position, Employer, School, etc var previousChurchAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "PreviousChurch")); var employerAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Employer")); var positionAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Position")); var firstVisitAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "FirstVisit")); var schoolAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "School")); var membershipDateAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "MembershipDate")); var baptismDateAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "BaptismDate")); var facebookAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Facebook")); var twitterAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Twitter")); var instagramAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Instagram")); // Text field type id int textFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT), lookupContext).Id; // Attribute entity type id int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id; // Visit info category var visitInfoCategory = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId) .Where(c => c.Name == "Visit Information").FirstOrDefault(); // Add a Secondary Email attribute if it doesn't exist var secondaryEmail = personAttributes.FirstOrDefault(a => a.Key == "SecondaryEmail"); if (secondaryEmail == null) { secondaryEmail = new Rock.Model.Attribute(); secondaryEmail.Key = "SecondaryEmail"; secondaryEmail.Name = "Secondary Email"; secondaryEmail.FieldTypeId = textFieldTypeId; secondaryEmail.EntityTypeId = PersonEntityTypeId; secondaryEmail.EntityTypeQualifierValue = string.Empty; secondaryEmail.EntityTypeQualifierColumn = string.Empty; secondaryEmail.Description = "The secondary email for this person"; secondaryEmail.DefaultValue = string.Empty; secondaryEmail.IsMultiValue = false; secondaryEmail.IsRequired = false; secondaryEmail.Order = 0; lookupContext.Attributes.Add(secondaryEmail); secondaryEmail.Categories.Add(visitInfoCategory); lookupContext.SaveChanges(true); } var secondaryEmailAttribute = AttributeCache.Read(secondaryEmail.Id, lookupContext); // Add a former name attribute var formerName = personAttributes.FirstOrDefault(a => a.Key == "FormerName"); if (formerName == null) { formerName = new Rock.Model.Attribute(); formerName.Key = "FormerName"; formerName.Name = "Former Name"; formerName.FieldTypeId = textFieldTypeId; formerName.EntityTypeId = PersonEntityTypeId; formerName.EntityTypeQualifierValue = string.Empty; formerName.EntityTypeQualifierColumn = string.Empty; formerName.Description = "The former name for this person"; formerName.DefaultValue = string.Empty; formerName.IsMultiValue = false; formerName.IsRequired = false; formerName.Order = 0; lookupContext.Attributes.Add(formerName); secondaryEmail.Categories.Add(visitInfoCategory); lookupContext.SaveChanges(true); } var formerNameAttribute = AttributeCache.Read(formerName.Id, lookupContext); // Look for custom attributes in the Individual file var allFields = csvData.TableNodes.FirstOrDefault().Columns.Select((node, index) => new { node = node, index = index }).ToList(); Dictionary <int, string> customAttributes = allFields.Where(f => f.index > Twitter).ToDictionary(f => f.index, f => f.node.Name); // Add any if they don't already exist if (customAttributes.Any()) { var newAttributes = new List <Rock.Model.Attribute>(); foreach (var newAttributePair in customAttributes.Where(ca => !personAttributes.Any(a => a.Name == ca.Value))) { var newAttribute = new Rock.Model.Attribute(); newAttribute.Name = newAttributePair.Value; newAttribute.Key = newAttributePair.Value.RemoveWhitespace(); newAttribute.Description = newAttributePair.Value + " created by CSV import"; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.FieldTypeId = textFieldTypeId; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsGridColumn = false; newAttribute.IsRequired = false; newAttribute.Order = 0; newAttributes.Add(newAttribute); } lookupContext.Attributes.AddRange(newAttributes); lookupContext.SaveChanges(true); personAttributes.AddRange(newAttributes); } var dateFormats = new[] { "MM/dd/yyyy", "MM/dd/yy" }; var currentFamilyGroup = new Group(); var newFamilyList = new List <Group>(); var newVisitorList = new List <Group>(); var importDate = DateTime.Now; int completed = 0; ReportProgress(0, string.Format("Starting Individual import ({0:N0} already exist).", ImportedPeople.Count(p => p.Members.Any(m => m.Person.ForeignId != null)))); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { int groupRoleId = adultRoleId; bool isFamilyRelationship = true; string rowFamilyId = row[FamilyId]; string rowPersonId = row[PersonId]; string rowFamilyName = row[FamilyName]; if (!string.IsNullOrWhiteSpace(rowFamilyId) && rowFamilyId != currentFamilyGroup.ForeignId) { currentFamilyGroup = ImportedPeople.FirstOrDefault(p => p.ForeignId == rowFamilyId); if (currentFamilyGroup == null) { currentFamilyGroup = new Group(); currentFamilyGroup.ForeignId = rowFamilyId; currentFamilyGroup.Name = row[FamilyName]; currentFamilyGroup.CreatedByPersonAliasId = ImportPersonAlias.Id; currentFamilyGroup.GroupTypeId = FamilyGroupTypeId; } } // Verify this person isn't already in our data var personExists = ImportedPeople.Any(p => p.Members.Any(m => m.Person.ForeignId == rowPersonId)); if (!personExists) { var person = new Person(); person.ForeignId = rowPersonId; person.SystemNote = string.Format("Imported via Excavator on {0}", importDate.ToString()); person.RecordTypeValueId = personRecordTypeId; person.CreatedByPersonAliasId = ImportPersonAlias.Id; string firstName = row[FirstName]; person.FirstName = firstName; person.NickName = row[NickName] ?? firstName; person.MiddleName = row[MiddleName]; person.LastName = row[LastName]; #region Assign values to the Person record DateTime birthDate; if (DateTime.TryParseExact(row[DateOfBirth], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate)) { person.BirthDate = birthDate; } DateTime anniversary; if (DateTime.TryParseExact(row[Anniversary], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out anniversary)) { person.AnniversaryDate = anniversary; } string gender = row[Gender]; if (gender != null) { switch (gender.Trim().ToLower()) { case "m": case "male": person.Gender = Rock.Model.Gender.Male; break; case "f": case "female": person.Gender = Rock.Model.Gender.Female; break; default: person.Gender = Rock.Model.Gender.Unknown; break; } } string prefix = row[Prefix]; if (!string.IsNullOrWhiteSpace(prefix)) { prefix = prefix.RemoveSpecialCharacters().Trim(); person.TitleValueId = titleTypes.Where(s => prefix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string suffix = row[Suffix]; if (!string.IsNullOrWhiteSpace(suffix)) { suffix = suffix.RemoveSpecialCharacters().Trim(); person.SuffixValueId = suffixTypes.Where(s => suffix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string maritalStatus = row[MaritalStatus]; if (!string.IsNullOrWhiteSpace(maritalStatus)) { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == maritalStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); } else { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == "Unknown") .Select(dv => (int?)dv.Id).FirstOrDefault(); } string familyRole = row[FamilyRole]; if (!string.IsNullOrWhiteSpace(familyRole)) { if (familyRole == "Visitor") { isFamilyRelationship = false; } if (familyRole == "Child" || person.Age < 18) { groupRoleId = childRoleId; } } string connectionStatus = row[ConnectionStatus]; if (!string.IsNullOrWhiteSpace(connectionStatus)) { if (connectionStatus == "Member") { person.ConnectionStatusValueId = memberConnectionStatusId; } else if (connectionStatus == "Visitor") { person.ConnectionStatusValueId = visitorConnectionStatusId; } else if (connectionStatus == "Deceased") { person.IsDeceased = true; person.RecordStatusReasonValueId = recordStatusDeceasedId; } else { // look for user-defined connection type or default to Attendee var customConnectionType = connectionStatusTypes.Where(dv => dv.Value == connectionStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); person.ConnectionStatusValueId = customConnectionType ?? attendeeConnectionStatusId; person.RecordStatusValueId = recordStatusActiveId; } } string recordStatus = row[RecordStatus]; if (!string.IsNullOrWhiteSpace(recordStatus)) { switch (recordStatus.Trim()) { case "Active": person.RecordStatusValueId = recordStatusActiveId; break; case "Inactive": person.RecordStatusValueId = recordStatusInactiveId; break; default: person.RecordStatusValueId = recordStatusPendingId; break; } } var personNumbers = new Dictionary <string, string>(); personNumbers.Add("Home", row[HomePhone]); personNumbers.Add("Mobile", row[MobilePhone]); personNumbers.Add("Work", row[WorkPhone]); string smsAllowed = row[AllowSMS]; foreach (var numberPair in personNumbers.Where(n => !string.IsNullOrWhiteSpace(n.Value))) { var extension = string.Empty; var countryCode = Rock.Model.PhoneNumber.DefaultCountryCode(); var normalizedNumber = string.Empty; var countryIndex = numberPair.Value.IndexOf('+'); int extensionIndex = numberPair.Value.LastIndexOf('x') > 0 ? numberPair.Value.LastIndexOf('x') : numberPair.Value.Length; if (countryIndex >= 0) { countryCode = numberPair.Value.Substring(countryIndex, countryIndex + 3).AsNumeric(); normalizedNumber = numberPair.Value.Substring(countryIndex + 3, extensionIndex - 3).AsNumeric(); extension = numberPair.Value.Substring(extensionIndex); } else if (extensionIndex > 0) { normalizedNumber = numberPair.Value.Substring(0, extensionIndex).AsNumeric(); extension = numberPair.Value.Substring(extensionIndex).AsNumeric(); } else { normalizedNumber = numberPair.Value.AsNumeric(); } if (!string.IsNullOrWhiteSpace(normalizedNumber)) { var currentNumber = new PhoneNumber(); currentNumber.CountryCode = countryCode; currentNumber.CreatedByPersonAliasId = ImportPersonAlias.Id; currentNumber.Extension = extension.Left(20); currentNumber.Number = normalizedNumber.Left(20); currentNumber.NumberTypeValueId = numberTypeValues.Where(v => v.Value.Equals(numberPair.Key)) .Select(v => (int?)v.Id).FirstOrDefault(); if (numberPair.Key == "Mobile") { switch (smsAllowed.Trim().ToLower()) { case "y": case "yes": case "active": currentNumber.IsMessagingEnabled = true; break; default: currentNumber.IsMessagingEnabled = false; break; } } person.PhoneNumbers.Add(currentNumber); } } // Map Person attributes person.Attributes = new Dictionary <string, AttributeCache>(); person.AttributeValues = new Dictionary <string, AttributeValue>(); string formerNameValue = row[FormerName]; if (!string.IsNullOrWhiteSpace(formerNameValue)) { AddPersonAttribute(formerNameAttribute, person, formerNameValue); } bool isEmailActive; switch (row[IsEmailActive].Trim().ToLower()) { case "n": case "no": case "inactive": isEmailActive = false; break; default: isEmailActive = true; break; } EmailPreference emailPreference; switch (row[AllowBulkEmail].Trim().ToLower()) { case "n": case "no": case "inactive": emailPreference = EmailPreference.NoMassEmails; break; default: emailPreference = EmailPreference.EmailAllowed; break; } string primaryEmail = row[Email]; if (!string.IsNullOrWhiteSpace(primaryEmail)) { person.Email = primaryEmail; person.IsEmailActive = isEmailActive; person.EmailPreference = emailPreference; } string secondaryEmailValue = row[SecondaryEmail]; if (!string.IsNullOrWhiteSpace(secondaryEmailValue)) { AddPersonAttribute(secondaryEmailAttribute, person, secondaryEmailValue); } DateTime membershipDateValue; if (DateTime.TryParseExact(row[MembershipDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out membershipDateValue)) { AddPersonAttribute(membershipDateAttribute, person, membershipDateValue.ToString()); } DateTime baptismDateValue; if (DateTime.TryParseExact(row[BaptismDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out baptismDateValue)) { AddPersonAttribute(baptismDateAttribute, person, baptismDateValue.ToString()); } DateTime firstVisitValue; if (DateTime.TryParseExact(row[FirstVisit], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out firstVisitValue)) { AddPersonAttribute(firstVisitAttribute, person, firstVisitValue.ToString()); } string previousChurchValue = row[PreviousChurch]; if (!string.IsNullOrWhiteSpace(previousChurchValue)) { AddPersonAttribute(previousChurchAttribute, person, previousChurchValue); } string positionValue = row[Occupation]; if (!string.IsNullOrWhiteSpace(positionValue)) { AddPersonAttribute(positionAttribute, person, positionValue); } string employerValue = row[Employer]; if (!string.IsNullOrWhiteSpace(employerValue)) { AddPersonAttribute(employerAttribute, person, employerValue); } string schoolName = row[School]; if (!string.IsNullOrWhiteSpace(schoolName)) { // Add school if it doesn't exist Guid schoolGuid; var schoolExists = schoolDefinedType.DefinedValues.Any(s => s.Value.Equals(schoolName)); if (!schoolExists) { var newSchool = new DefinedValue(); newSchool.DefinedTypeId = schoolDefinedType.Id; newSchool.Value = schoolName; newSchool.Order = 0; lookupContext.DefinedValues.Add(newSchool); lookupContext.SaveChanges(); schoolGuid = newSchool.Guid; } else { schoolGuid = schoolDefinedType.DefinedValues.FirstOrDefault(s => s.Value.Equals(schoolName)).Guid; } AddPersonAttribute(schoolAttribute, person, schoolGuid.ToString()); } string facebookValue = row[Facebook]; if (!string.IsNullOrWhiteSpace(facebookValue)) { AddPersonAttribute(facebookAttribute, person, facebookValue); } string twitterValue = row[Twitter]; if (!string.IsNullOrWhiteSpace(twitterValue)) { AddPersonAttribute(twitterAttribute, person, twitterValue); } string instagramValue = row[Instagram]; if (!string.IsNullOrWhiteSpace(instagramValue)) { AddPersonAttribute(instagramAttribute, person, instagramValue); } foreach (var attributePair in customAttributes) { string newAttributeValue = row[attributePair.Key]; if (!string.IsNullOrWhiteSpace(newAttributeValue)) { int?newAttributeId = personAttributes.Where(a => a.Key == attributePair.Value) .Select(a => (int?)a.Id).FirstOrDefault(); if (newAttributeId != null) { var newAttribute = AttributeCache.Read((int)newAttributeId); AddPersonAttribute(newAttribute, person, newAttributeValue); } } } // Add notes to timeline var notePairs = new Dictionary <string, string>(); notePairs.Add("General", row[GeneralNote]); notePairs.Add("Medical", row[MedicalNote]); notePairs.Add("Security", row[SecurityNote]); var newNoteList = new List <Note>(); foreach (var notePair in notePairs.Where(n => !string.IsNullOrWhiteSpace(n.Value))) { var newNote = new Note(); newNote.CreatedByPersonAliasId = ImportPersonAlias.Id; newNote.CreatedDateTime = importDate; newNote.EntityId = person.Id; newNote.Text = notePair.Value; newNote.NoteTypeId = noteTimelineTypeId; newNote.Caption = string.Format("{0} Note", notePair.Key); if (!notePair.Key.Equals("General")) { newNote.IsAlert = true; } newNoteList.Add(newNote); } if (newNoteList.Any()) { lookupContext.Notes.AddRange(newNoteList); lookupContext.SaveChanges(true); } #endregion var groupMember = new GroupMember(); groupMember.Person = person; groupMember.GroupRoleId = groupRoleId; groupMember.GroupMemberStatus = GroupMemberStatus.Active; if (isFamilyRelationship || currentFamilyGroup.Members.Count() < 1) { currentFamilyGroup.Members.Add(groupMember); newFamilyList.Add(currentFamilyGroup); completed++; } else { var visitorGroup = new Group(); visitorGroup.ForeignId = rowFamilyId.ToString(); visitorGroup.Members.Add(groupMember); visitorGroup.GroupTypeId = FamilyGroupTypeId; visitorGroup.Name = person.LastName + " Family"; newFamilyList.Add(visitorGroup); completed++; newVisitorList.Add(visitorGroup); } if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} people imported.", completed)); } else if (completed % ReportingNumber < 1) { SaveIndividuals(newFamilyList, newVisitorList); ReportPartialProgress(); newFamilyList.Clear(); } } } if (newFamilyList.Any()) { SaveIndividuals(newFamilyList, newVisitorList); } ReportProgress(0, string.Format("Finished individual import: {0:N0} people imported.", completed)); return(completed); }
protected GroupTypeRole GetInverseRole(GroupTypeRole role, GroupTypeRoleService groupRoleServ) { role.LoadAttributes(); return(groupRoleServ.Get(role.GetAttributeValue("InverseRelationship").AsGuid())); }
public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var personAliasService = new PersonAliasService(rockContext); // get person Person person = null; var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull(); if (guidPersonAttribute.HasValue) { var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext); if (attributePerson != null) { var attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value).AsGuidOrNull(); if (attributePersonValue.HasValue) { person = personAliasService.GetPerson(attributePersonValue.Value); if (person == null) { errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute)); return(false); } } } } Person relatedPerson = null; var guidRelatedPersonAttribute = GetAttributeValue(action, "RelationshipTo").AsGuidOrNull(); if (guidRelatedPersonAttribute.HasValue) { var attributePerson = AttributeCache.Read(guidRelatedPersonAttribute.Value, rockContext); if (attributePerson != null) { var attributePersonValue = action.GetWorklowAttributeValue(guidRelatedPersonAttribute.Value).AsGuidOrNull(); if (attributePersonValue.HasValue) { relatedPerson = personAliasService.GetPerson(attributePersonValue.Value); if (relatedPerson == null) { errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute)); return(false); } } } } var groupTypeRoleService = new GroupTypeRoleService(rockContext); GroupTypeRole relationshipType = null; var relationshipRoleGuid = GetActionAttributeValue(action, "RelationshipType").AsGuidOrNull(); if (relationshipRoleGuid.HasValue) { relationshipType = groupTypeRoleService.Get(relationshipRoleGuid.Value); if (relationshipType == null) { errorMessages.Add(string.Format("GroupTypeRole (Relationship Type) could not be found for selected value ('{0}')!", relationshipRoleGuid)); return(false); } } var groupMemberService = new GroupMemberService(rockContext); // Check if relationship already exists if ( groupMemberService.GetKnownRelationship(person.Id, relationshipType.Id) .Any(gm => gm.Person.Id == relatedPerson.Id)) { errorMessages.Add(string.Format("Relationship of {0} already exists between {1} and {2}", relationshipType.Name, person.FullName, relatedPerson.FullName)); return(false); } groupMemberService.CreateKnownRelationship(person.Id, relatedPerson.Id, relationshipType.Id); // Create inverse relationship if it doesn't exist. if (relationshipType.Attributes.ContainsKey("InverseRelationship")) { var inverseRelationshipTypeGuid = relationshipType.GetAttributeValue("InverseRelationship").AsGuidOrNull(); if (inverseRelationshipTypeGuid.HasValue) { var inverseRelationshipType = groupTypeRoleService.Get(inverseRelationshipTypeGuid.Value); // Ensure relationship doesn't already exist if (!groupMemberService.GetKnownRelationship(relatedPerson.Id, inverseRelationshipType.Id) .Any(gm => gm.Person.Id == person.Id)) { groupMemberService.CreateKnownRelationship(relatedPerson.Id, person.Id, inverseRelationshipType.Id); } } } return(true); }
private void CheckinAreaRow_AddAreaClick( object sender, EventArgs e ) { var parentRow = sender as CheckinAreaRow; parentRow.Expanded = true; using ( var rockContext = new RockContext() ) { var groupTypeService = new GroupTypeService( rockContext ); var parentArea = groupTypeService.Get( parentRow.GroupTypeGuid ); if ( parentArea != null ) { Guid newGuid = Guid.NewGuid(); var checkinArea = new GroupType(); checkinArea.Guid = newGuid; checkinArea.Name = "New Area"; checkinArea.IsSystem = false; checkinArea.ShowInNavigation = false; checkinArea.TakesAttendance = true; checkinArea.AttendanceRule = AttendanceRule.None; checkinArea.AttendancePrintTo = PrintTo.Default; checkinArea.AllowMultipleLocations = true; checkinArea.EnableLocationSchedules = true; checkinArea.Order = parentArea.ChildGroupTypes.Any() ? parentArea.ChildGroupTypes.Max( t => t.Order ) + 1 : 0; GroupTypeRole defaultRole = new GroupTypeRole(); defaultRole.Name = "Member"; checkinArea.Roles.Add( defaultRole ); parentArea.ChildGroupTypes.Add( checkinArea ); rockContext.SaveChanges(); GroupTypeCache.Flush( parentArea.Id ); Rock.CheckIn.KioskDevice.FlushAll(); SelectArea( newGuid ); } } BuildRows(); }
/// <summary> /// Saves the people. /// </summary> /// <param name="familyList">The family list.</param> /// <param name="visitorList">The visitor list.</param> /// <param name="ownerRole">The owner role.</param> /// <param name="childRoleId">The child role identifier.</param> /// <param name="inviteeRoleId">The invitee role identifier.</param> /// <param name="invitedByRoleId">The invited by role identifier.</param> /// <param name="canCheckInRoleId">The can check in role identifier.</param> /// <param name="allowCheckInByRoleId">The allow check in by role identifier.</param> private static void SavePeople( List<Group> familyList, List<Group> visitorList, GroupTypeRole ownerRole, int childRoleId, int inviteeRoleId, int invitedByRoleId, int canCheckInRoleId, int allowCheckInByRoleId ) { var rockContext = new RockContext(); var groupMemberService = new GroupMemberService( rockContext ); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Groups.AddRange( familyList ); rockContext.SaveChanges( DisableAudit ); var newAttributeValues = new List<AttributeValue>(); foreach ( var familyGroups in familyList.GroupBy<Group, int?>( g => g.ForeignId.AsType<int?>() ) ) { bool visitorsExist = familyGroups.Count() > 1; foreach ( var newFamilyGroup in familyGroups ) { foreach ( var groupMember in newFamilyGroup.Members ) { var person = groupMember.Person; foreach ( var attributeCache in person.Attributes.Select( a => a.Value ) ) { var newValue = person.AttributeValues[attributeCache.Key]; if ( newValue != null ) { newValue.EntityId = person.Id; newAttributeValues.Add( newValue ); } } if ( !person.Aliases.Any( a => a.AliasPersonId == person.Id ) ) { person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } ); } if ( groupMember.GroupRoleId != childRoleId ) { person.GivingGroupId = newFamilyGroup.Id; } if ( visitorsExist ) { // Retrieve or create the group this person is an owner of var ownerGroup = groupMemberService.Queryable() .Where( m => m.PersonId == person.Id && m.GroupRoleId == ownerRole.Id ) .Select( m => m.Group ) .FirstOrDefault(); if ( ownerGroup == null ) { var ownerGroupMember = new GroupMember(); ownerGroupMember.PersonId = person.Id; ownerGroupMember.GroupRoleId = ownerRole.Id; ownerGroup = new Group(); ownerGroup.Name = ownerRole.GroupType.Name; ownerGroup.GroupTypeId = ownerRole.GroupTypeId.Value; ownerGroup.Members.Add( ownerGroupMember ); rockContext.Groups.Add( ownerGroup ); } // if this is a visitor, then add proper relationships to the family member if ( visitorList.Where( v => v.ForeignId == newFamilyGroup.ForeignId ) .Any( v => v.Members.Any( m => m.Person.ForeignId.Equals( person.Id ) ) ) ) { var familyMembers = familyGroups.Except( visitorList ).SelectMany( g => g.Members ); foreach ( var familyMember in familyMembers.Select( m => m.Person ) ) { var invitedByMember = new GroupMember(); invitedByMember.PersonId = familyMember.Id; invitedByMember.GroupRoleId = invitedByRoleId; ownerGroup.Members.Add( invitedByMember ); if ( person.Age < 18 && familyMember.Age > 15 ) { var allowCheckinMember = new GroupMember(); allowCheckinMember.PersonId = familyMember.Id; allowCheckinMember.GroupRoleId = allowCheckInByRoleId; ownerGroup.Members.Add( allowCheckinMember ); } } } else { // not a visitor, add the visitors to the family member's known relationship var visitors = visitorList.Where( v => v.ForeignId == newFamilyGroup.ForeignId ).SelectMany( g => g.Members ); foreach ( var visitor in visitors.Select( g => g.Person ) ) { var inviteeMember = new GroupMember(); inviteeMember.PersonId = visitor.Id; inviteeMember.GroupRoleId = inviteeRoleId; ownerGroup.Members.Add( inviteeMember ); // if visitor can be checked in and this person is considered an adult if ( visitor.Age < 18 && person.Age > 15 ) { var canCheckInMember = new GroupMember(); canCheckInMember.PersonId = visitor.Id; canCheckInMember.GroupRoleId = canCheckInRoleId; ownerGroup.Members.Add( canCheckInMember ); } } } } } } } rockContext.AttributeValues.AddRange( newAttributeValues ); rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( DisableAudit ); } ); }
/// <summary> /// Handles the SaveClick event of the dlgGroupMemberAttribute 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 gGroupTypeRoles_SaveClick( object sender, EventArgs e ) { var groupTypeRole = new GroupTypeRole(); var groupTypeRoleState = GroupTypeRolesState.FirstOrDefault( r => r.Guid.Equals( hfRoleGuid.Value.AsGuid() ) ); if ( groupTypeRoleState != null ) { groupTypeRole.CopyPropertiesFrom( groupTypeRoleState ); GroupTypeRolesState.RemoveEntity( groupTypeRoleState.Guid ); } else { groupTypeRole.Order = GroupTypeRolesState.Any() ? GroupTypeRolesState.Max( a => a.Order ) + 1 : 0; groupTypeRole.GroupTypeId = hfGroupTypeId.ValueAsInt(); } groupTypeRole.Name = tbRoleName.Text; groupTypeRole.Description = tbRoleDescription.Text; groupTypeRole.IsLeader = cbIsLeader.Checked; groupTypeRole.CanView = cbCanView.Checked; groupTypeRole.CanEdit = cbCanEdit.Checked; int result; groupTypeRole.MinCount = null; if ( int.TryParse( nbMinimumRequired.Text, out result ) ) { groupTypeRole.MinCount = result; } groupTypeRole.MaxCount = null; if ( int.TryParse( nbMaximumAllowed.Text, out result ) ) { groupTypeRole.MaxCount = result; } groupTypeRole.LoadAttributes(); Helper.GetEditValues( phGroupTypeRoleAttributes, groupTypeRole ); // Controls will show warnings if ( !groupTypeRole.IsValid ) { return; } GroupTypeRolesState.Add( groupTypeRole ); BindGroupTypeRolesGrid(); HideDialog(); }
/// <summary> /// Shows the dialog. /// </summary> /// <param name="setValues">if set to <c>true</c> [set values].</param> private void ShowDialog( bool setValues = false ) { switch ( hfActiveDialog.Value ) { case "GROUPTYPEROLES": var role = GroupTypeRolesState.FirstOrDefault( r => r.Guid.Equals( hfRoleGuid.Value.AsGuid() ) ); if ( role == null ) { role = new GroupTypeRole(); role.GroupTypeId = hfGroupTypeId.ValueAsInt(); role.LoadAttributes(); } Helper.AddEditControls( role, phGroupTypeRoleAttributes, setValues ); SetValidationGroup( phGroupTypeRoleAttributes.Controls, dlgGroupTypeRoles.ValidationGroup ); dlgGroupTypeRoles.Show(); break; case "CHILDGROUPTYPES": dlgChildGroupType.Show(); break; case "SCHEDULEEXCLUSION": dlgScheduleExclusion.Show(); break; case "LOCATIONTYPE": dlgLocationType.Show(); break; case "GROUPTYPEATTRIBUTES": dlgGroupTypeAttribute.Show(); break; case "GROUPATTRIBUTES": dlgGroupAttribute.Show(); break; case "GROUPMEMBERATTRIBUTES": dlgGroupMemberAttribute.Show(); break; } }
/// <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 ) { GroupType groupType; using ( new UnitOfWorkScope() ) { GroupTypeService groupTypeService = new GroupTypeService(); GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(); AttributeService attributeService = new AttributeService(); AttributeQualifierService qualifierService = new AttributeQualifierService(); CategoryService categoryService = new CategoryService(); int groupTypeId = int.Parse( hfGroupTypeId.Value ); if ( groupTypeId == 0 ) { groupType = new GroupType(); groupTypeService.Add( groupType, CurrentPersonId ); } else { groupType = groupTypeService.Get( groupTypeId ); // selected roles var selectedRoleGuids = GroupTypeRolesState.Select( r => r.Guid ); foreach ( var role in groupType.Roles.Where( r => !selectedRoleGuids.Contains( r.Guid ) ).ToList() ) { groupType.Roles.Remove( role ); groupTypeRoleService.Delete( role, CurrentPersonId ); } } foreach ( var roleState in GroupTypeRolesState ) { GroupTypeRole role = groupType.Roles.Where( r => r.Guid == roleState.Guid ).FirstOrDefault(); if ( role == null ) { role = new GroupTypeRole(); groupType.Roles.Add( role ); } else { roleState.Id = role.Id; roleState.Guid = role.Guid; } role.CopyPropertiesFrom( roleState ); } GroupLocationPickerMode locationSelectionMode = GroupLocationPickerMode.None; foreach(ListItem li in cblLocationSelectionModes.Items) { if ( li.Selected ) { locationSelectionMode = locationSelectionMode | (GroupLocationPickerMode)li.Value.AsInteger().Value; } } groupType.Name = tbName.Text; groupType.Description = tbDescription.Text; groupType.GroupTerm = tbGroupTerm.Text; groupType.GroupMemberTerm = tbGroupMemberTerm.Text; groupType.ShowInGroupList = cbShowInGroupList.Checked; groupType.ShowInNavigation = cbShowInNavigation.Checked; groupType.IconCssClass = tbIconCssClass.Text; groupType.TakesAttendance = cbTakesAttendance.Checked; groupType.AttendanceRule = ddlAttendanceRule.SelectedValueAsEnum<AttendanceRule>(); groupType.AttendancePrintTo = ddlAttendancePrintTo.SelectedValueAsEnum<PrintTo>(); groupType.LocationSelectionMode = locationSelectionMode; groupType.GroupTypePurposeValueId = ddlGroupTypePurpose.SelectedValueAsInt(); groupType.AllowMultipleLocations = cbAllowMultipleLocations.Checked; groupType.InheritedGroupTypeId = gtpInheritedGroupType.SelectedGroupTypeId; groupType.ChildGroupTypes = new List<GroupType>(); groupType.ChildGroupTypes.Clear(); foreach ( var item in ChildGroupTypesDictionary ) { var childGroupType = groupTypeService.Get( item.Key ); if ( childGroupType != null ) { groupType.ChildGroupTypes.Add( childGroupType ); } } DefinedValueService definedValueService = new DefinedValueService(); groupType.LocationTypes = new List<GroupTypeLocationType>(); groupType.LocationTypes.Clear(); foreach ( var item in LocationTypesDictionary ) { var locationType = definedValueService.Get( item.Key ); if ( locationType != null ) { groupType.LocationTypes.Add( new GroupTypeLocationType { LocationTypeValueId = locationType.Id } ); } } if ( !groupType.IsValid ) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction( () => { groupTypeService.Save( groupType, CurrentPersonId ); /* Save Attributes */ string qualifierValue = groupType.Id.ToString(); SaveAttributes( new GroupType().TypeId, "Id", qualifierValue, GroupTypeAttributesState, attributeService, qualifierService, categoryService ); SaveAttributes( new Group().TypeId, "GroupTypeId", qualifierValue, GroupAttributesState, attributeService, qualifierService, categoryService ); SaveAttributes( new GroupMember().TypeId, "GroupTypeId", qualifierValue, GroupMemberAttributesState, attributeService, qualifierService, categoryService ); // Reload to save default role groupType = groupTypeService.Get( groupType.Id ); groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault( r => r.Guid.Equals( DefaultRoleGuid ) ); if ( groupType.DefaultGroupRole == null ) { groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault(); } groupTypeService.Save( groupType, CurrentPersonId ); // Reload the roles and apply their attribute values foreach ( var role in groupTypeRoleService.GetByGroupTypeId( groupType.Id ) ) { role.LoadAttributes(); var roleState = GroupTypeRolesState.Where( r => r.Guid.Equals( role.Guid ) ).FirstOrDefault(); if ( roleState != null && roleState.AttributeValues != null ) { foreach ( var attributeValue in roleState.AttributeValues ) { role.SetAttributeValue( attributeValue.Key, roleState.GetAttributeValue( attributeValue.Key ) ); } Helper.SaveAttributeValues( role, CurrentPersonId ); } } } ); GroupTypeCache.Flush( groupType.Id ); } NavigateToParentPage(); }
/// <summary> /// Saves the people. /// </summary> /// <param name="familyList">The family list.</param> /// <param name="visitorList">The visitor list.</param> /// <param name="ownerRole">The owner role.</param> /// <param name="childRoleId">The child role identifier.</param> /// <param name="inviteeRoleId">The invitee role identifier.</param> /// <param name="invitedByRoleId">The invited by role identifier.</param> /// <param name="canCheckInRoleId">The can check in role identifier.</param> /// <param name="allowCheckInByRoleId">The allow check in by role identifier.</param> private void SavePeople( List<Group> familyList, List<Group> visitorList, GroupTypeRole ownerRole, int childRoleId, int inviteeRoleId, int invitedByRoleId, int canCheckInRoleId, int allowCheckInByRoleId ) { var rockContext = new RockContext(); var groupMemberService = new GroupMemberService( rockContext ); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Groups.AddRange( familyList ); rockContext.SaveChanges( DisableAudit ); foreach ( var familyGroups in familyList.GroupBy<Group, int?>( g => g.ForeignId.AsType<int?>() ) ) { bool visitorsExist = familyGroups.Count() > 1; foreach ( var newFamilyGroup in familyGroups ) { foreach ( var groupMember in newFamilyGroup.Members ) { var person = groupMember.Person; // save current values before loading from the db var newPersonAttributes = person.Attributes; var newPersonValues = person.AttributeValues; person.LoadAttributes( rockContext ); foreach ( var attributeCache in newPersonAttributes.Select( a => a.Value ) ) { var currentAttributeValue = person.AttributeValues[attributeCache.Key]; var newAttributeValue = newPersonValues[attributeCache.Key].Value; if ( currentAttributeValue.Value != newAttributeValue && !string.IsNullOrWhiteSpace( newAttributeValue ) ) { // set the new value and add it to the database currentAttributeValue.Value = newAttributeValue; if ( currentAttributeValue.Id == 0 ) { currentAttributeValue.EntityId = person.Id; rockContext.Entry( currentAttributeValue ).State = EntityState.Added; } else { rockContext.Entry( currentAttributeValue ).State = EntityState.Modified; } } } if ( !person.Aliases.Any( a => a.AliasPersonId == person.Id ) ) { person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid, ForeignId = person.ForeignId } ); } if ( groupMember.GroupRoleId != childRoleId ) { person.GivingGroupId = newFamilyGroup.Id; } if ( visitorsExist ) { // Retrieve or create the group this person is an owner of var ownerGroup = groupMemberService.Queryable() .Where( m => m.PersonId == person.Id && m.GroupRoleId == ownerRole.Id ) .Select( m => m.Group ) .FirstOrDefault(); if ( ownerGroup == null ) { var ownerGroupMember = new GroupMember(); ownerGroupMember.PersonId = person.Id; ownerGroupMember.GroupRoleId = ownerRole.Id; ownerGroup = new Group(); ownerGroup.Name = ownerRole.GroupType.Name; ownerGroup.GroupTypeId = ownerRole.GroupTypeId.Value; ownerGroup.Members.Add( ownerGroupMember ); rockContext.Groups.Add( ownerGroup ); } // if this is a visitor, then add relationships to the family member(s) if ( visitorList.Where( v => v.ForeignId == newFamilyGroup.ForeignId ) .Any( v => v.Members.Any( m => m.Person.ForeignId.Equals( person.ForeignId ) ) ) ) { var familyMembers = familyGroups.Except( visitorList ).SelectMany( g => g.Members ); foreach ( var familyMember in familyMembers.Select( m => m.Person ) ) { var invitedByMember = new GroupMember(); invitedByMember.PersonId = familyMember.Id; invitedByMember.GroupRoleId = invitedByRoleId; ownerGroup.Members.Add( invitedByMember ); if ( person.Age < 18 && familyMember.Age > 18 ) { var allowCheckinMember = new GroupMember(); allowCheckinMember.PersonId = familyMember.Id; allowCheckinMember.GroupRoleId = allowCheckInByRoleId; ownerGroup.Members.Add( allowCheckinMember ); } } } else { // not a visitor, add the visitors to the family member's known relationship var visitors = visitorList.Where( v => v.ForeignId == newFamilyGroup.ForeignId ) .SelectMany( g => g.Members ).ToList(); foreach ( var visitor in visitors.Select( g => g.Person ) ) { var inviteeMember = new GroupMember(); inviteeMember.PersonId = visitor.Id; inviteeMember.GroupRoleId = inviteeRoleId; ownerGroup.Members.Add( inviteeMember ); // if visitor can be checked in and this person is considered an adult if ( visitor.Age < 18 && person.Age > 18 ) { var canCheckInMember = new GroupMember(); canCheckInMember.PersonId = visitor.Id; canCheckInMember.GroupRoleId = canCheckInRoleId; ownerGroup.Members.Add( canCheckInMember ); } } } } } } } rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( DisableAudit ); if ( familyList.Any() ) { var familyMembers = familyList.SelectMany( gm => gm.Members ); ImportedPeople.AddRange( familyMembers.Select( m => new PersonKeys { PersonAliasId = m.Person.PrimaryAliasId, IndividualId = m.Person.ForeignId.AsType<int?>(), HouseholdId = m.Group.ForeignId.AsType<int?>(), IsFamilyMember = true } ).ToList() ); } if ( visitorList.Any() ) { var visitors = visitorList.SelectMany( gm => gm.Members ); ImportedPeople.AddRange( visitors.Select( m => new PersonKeys { PersonAliasId = m.Person.PrimaryAliasId, IndividualId = m.Person.ForeignId.AsType<int?>(), HouseholdId = m.Group.ForeignId.AsType<int?>(), IsFamilyMember = false } ).ToList() ); } } ); // end wrap transaction }
/// <summary> /// Loads the individual data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadIndividuals(CSVInstance csvData) { var lookupContext = new RockContext(); var groupTypeRoleService = new GroupTypeRoleService(lookupContext); var groupMemberService = new GroupMemberService(lookupContext); // Marital statuses: Married, Single, Separated, etc var maritalStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS), lookupContext).DefinedValues; // Connection statuses: Member, Visitor, Attendee, etc var connectionStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS), lookupContext).DefinedValues; int memberConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER)).Id; int visitorConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR)).Id; int attendeeConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE)).Id; // Suffix type: Dr., Jr., II, etc var suffixTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_SUFFIX), lookupContext).DefinedValues; // Title type: Mr., Mrs. Dr., etc var titleTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_TITLE), lookupContext).DefinedValues; // Record statuses: Active, Inactive, Pending int?recordStatusActiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE), lookupContext).Id; int?recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE), lookupContext).Id; int?recordStatusPendingId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING), lookupContext).Id; // Deceased record status reason (others available: No Activity, Moved, etc) var recordStatusDeceasedId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_REASON_DECEASED)).Id; // Record type: Person int?personRecordTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON), lookupContext).Id; // Group roles: Owner, Adult, Child, others GroupTypeRole ownerRole = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER)); int adultRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id; int childRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)).Id; // Phone types: Home, Work, Mobile var numberTypeValues = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext).DefinedValues; // Personal note type id var personalNoteTypeId = new NoteTypeService(lookupContext).Get(new Guid(Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE)).Id; // School defined type var schoolDefinedType = DefinedTypeCache.Read(new Guid("576FF1E2-6225-4565-A16D-230E26167A3D")); // Look up existing Person attributes var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).ToList(); var schoolAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "School")); // Text field type id int textFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT), lookupContext).Id; int dateFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.DATE), lookupContext).Id; // Attribute entity type id int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id; // Visit info category var visitInfoCategory = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId) .Where(c => c.Name == "Visit Information").FirstOrDefault(); // Look for custom attributes in the Individual file var allFields = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList(); Dictionary <int, string> customAttributes = allFields .Where(f => f.index > SecurityNote) .ToDictionary(f => f.index, f => f.node.Name.RemoveWhitespace()); // Add any attributes if they don't already exist if (customAttributes.Any()) { var newAttributes = new List <Rock.Model.Attribute>(); foreach (var newAttributePair in customAttributes.Where(ca => !personAttributes.Any(a => a.Key == ca.Value))) { var newAttribute = new Rock.Model.Attribute(); newAttribute.Name = newAttributePair.Value; newAttribute.Key = newAttributePair.Value.RemoveWhitespace(); newAttribute.Description = newAttributePair.Value + " created by CSV import"; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.FieldTypeId = textFieldTypeId; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsGridColumn = false; newAttribute.IsRequired = false; newAttribute.Order = 0; newAttributes.Add(newAttribute); } lookupContext.Attributes.AddRange(newAttributes); lookupContext.SaveChanges(DisableAuditing); personAttributes.AddRange(newAttributes); } // Set the supported date formats var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy" }; var currentFamilyGroup = new Group(); var newFamilyList = new List <Group>(); var newVisitorList = new List <Group>(); var newNoteList = new List <Note>(); int completed = 0; int newFamilies = 0; int newPeople = 0; ReportProgress(0, string.Format("Starting Individual import ({0:N0} already exist).", ImportedPeopleKeys.Count())); string[] row; row = csvData.Database.FirstOrDefault(); while (row != null) { int groupRoleId = adultRoleId; bool isFamilyRelationship = true; string rowFamilyName = row[FamilyName]; string rowFamilyKey = row[FamilyId]; string rowPersonKey = row[PersonId]; int? rowFamilyId = rowFamilyKey.AsType <int?>(); int? rowPersonId = rowPersonKey.AsType <int?>(); // Check that this person isn't already in our data var personExists = ImportedFamilies.Any(g => g.Members.Any(m => m.Person.ForeignKey == rowPersonKey)); if (!personExists) { #region person create var person = new Person(); person.ForeignKey = rowPersonKey; person.ForeignId = rowPersonId; person.SystemNote = string.Format("Imported via Excavator on {0}", ImportDateTime); person.RecordTypeValueId = personRecordTypeId; person.CreatedByPersonAliasId = ImportPersonAliasId; string firstName = row[FirstName].Left(50); string nickName = row[NickName].Left(50); person.FirstName = firstName; person.NickName = string.IsNullOrWhiteSpace(nickName) ? firstName : nickName; person.MiddleName = row[MiddleName].Left(50); person.LastName = row[LastName].Left(50); DateTime createdDateValue; if (DateTime.TryParseExact(row[CreatedDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDateValue)) { person.CreatedDateTime = createdDateValue; person.ModifiedDateTime = ImportDateTime; } else { person.CreatedDateTime = ImportDateTime; person.ModifiedDateTime = ImportDateTime; } DateTime birthDate; if (DateTime.TryParseExact(row[DateOfBirth], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate)) { person.BirthDay = birthDate.Day; person.BirthMonth = birthDate.Month; person.BirthYear = birthDate.Year; } DateTime graduationDate; if (DateTime.TryParseExact(row[GraduationDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out graduationDate)) { person.GraduationYear = graduationDate.Year; } DateTime anniversary; if (DateTime.TryParseExact(row[Anniversary], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out anniversary)) { person.AnniversaryDate = anniversary; } string gender = row[Gender]; if (gender != null) { switch (gender.Trim().ToLower()) { case "m": case "male": person.Gender = Rock.Model.Gender.Male; break; case "f": case "female": person.Gender = Rock.Model.Gender.Female; break; default: person.Gender = Rock.Model.Gender.Unknown; break; } } string prefix = row[Prefix]; if (!string.IsNullOrWhiteSpace(prefix)) { prefix = prefix.RemoveSpecialCharacters().Trim(); person.TitleValueId = titleTypes.Where(s => prefix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string suffix = row[Suffix]; if (!string.IsNullOrWhiteSpace(suffix)) { suffix = suffix.RemoveSpecialCharacters().Trim(); person.SuffixValueId = suffixTypes.Where(s => suffix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string maritalStatus = row[MaritalStatus]; if (!string.IsNullOrWhiteSpace(maritalStatus)) { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == maritalStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); } else { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == "Unknown") .Select(dv => ( int? )dv.Id).FirstOrDefault(); } string familyRole = row[FamilyRole]; if (!string.IsNullOrWhiteSpace(familyRole)) { if (familyRole == "Visitor") { isFamilyRelationship = false; } if (familyRole == "Child" || person.Age < 18) { groupRoleId = childRoleId; } } string connectionStatus = row[ConnectionStatus]; if (!string.IsNullOrWhiteSpace(connectionStatus)) { if (connectionStatus == "Member") { person.ConnectionStatusValueId = memberConnectionStatusId; } else if (connectionStatus == "Visitor") { person.ConnectionStatusValueId = visitorConnectionStatusId; } else { // look for user-defined connection type or default to Attendee var customConnectionType = connectionStatusTypes.Where(dv => dv.Value == connectionStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); person.ConnectionStatusValueId = customConnectionType ?? attendeeConnectionStatusId; person.RecordStatusValueId = recordStatusActiveId; } } string recordStatus = row[RecordStatus]; if (!string.IsNullOrWhiteSpace(recordStatus)) { switch (recordStatus.Trim().ToLower()) { case "active": person.RecordStatusValueId = recordStatusActiveId; break; case "inactive": person.RecordStatusValueId = recordStatusInactiveId; break; default: person.RecordStatusValueId = recordStatusPendingId; break; } } string isDeceasedValue = row[IsDeceased]; if (!string.IsNullOrWhiteSpace(isDeceasedValue)) { switch (isDeceasedValue.Trim().ToLower()) { case "y": case "yes": person.IsDeceased = true; person.RecordStatusReasonValueId = recordStatusDeceasedId; person.RecordStatusValueId = recordStatusInactiveId; break; default: person.IsDeceased = false; break; } } var personNumbers = new Dictionary <string, string>(); personNumbers.Add("Home", row[HomePhone]); personNumbers.Add("Mobile", row[MobilePhone]); personNumbers.Add("Work", row[WorkPhone]); string smsAllowed = row[AllowSMS]; foreach (var numberPair in personNumbers.Where(n => !string.IsNullOrWhiteSpace(n.Value))) { var extension = string.Empty; var countryCode = Rock.Model.PhoneNumber.DefaultCountryCode(); var normalizedNumber = string.Empty; var countryIndex = numberPair.Value.IndexOf('+'); int extensionIndex = numberPair.Value.LastIndexOf('x') > 0 ? numberPair.Value.LastIndexOf('x') : numberPair.Value.Length; if (countryIndex >= 0) { countryCode = numberPair.Value.Substring(countryIndex, countryIndex + 3).AsNumeric(); normalizedNumber = numberPair.Value.Substring(countryIndex + 3, extensionIndex - 3).AsNumeric().TrimStart(new Char[] { '0' }); extension = numberPair.Value.Substring(extensionIndex); } else if (extensionIndex > 0) { normalizedNumber = numberPair.Value.Substring(0, extensionIndex).AsNumeric(); extension = numberPair.Value.Substring(extensionIndex).AsNumeric(); } else { normalizedNumber = numberPair.Value.AsNumeric(); } if (!string.IsNullOrWhiteSpace(normalizedNumber)) { var currentNumber = new PhoneNumber(); currentNumber.CountryCode = countryCode; currentNumber.CreatedByPersonAliasId = ImportPersonAliasId; currentNumber.Extension = extension.Left(20); currentNumber.Number = normalizedNumber.TrimStart(new Char[] { '0' }).Left(20); currentNumber.NumberFormatted = PhoneNumber.FormattedNumber(currentNumber.CountryCode, currentNumber.Number); currentNumber.NumberTypeValueId = numberTypeValues.Where(v => v.Value.Equals(numberPair.Key)) .Select(v => ( int? )v.Id).FirstOrDefault(); if (numberPair.Key == "Mobile") { switch (smsAllowed.Trim().ToLower()) { case "y": case "yes": case "active": currentNumber.IsMessagingEnabled = true; break; default: currentNumber.IsMessagingEnabled = false; break; } } person.PhoneNumbers.Add(currentNumber); } } // Map Person attributes person.Attributes = new Dictionary <string, AttributeCache>(); person.AttributeValues = new Dictionary <string, AttributeValueCache>(); bool isEmailActive; switch (row[IsEmailActive].Trim().ToLower()) { case "n": case "no": case "inactive": isEmailActive = false; break; default: isEmailActive = true; break; } EmailPreference emailPreference; switch (row[AllowBulkEmail].Trim().ToLower()) { case "n": case "no": case "inactive": emailPreference = EmailPreference.NoMassEmails; break; default: emailPreference = EmailPreference.EmailAllowed; break; } person.EmailPreference = emailPreference; string primaryEmail = row[Email].Trim().Left(75); if (!string.IsNullOrWhiteSpace(primaryEmail)) { if (primaryEmail.IsEmail()) { person.Email = primaryEmail; person.IsEmailActive = isEmailActive; } else { LogException("InvalidPrimaryEmail", string.Format("PersonId: {0} - Email: {1}", rowPersonKey, primaryEmail)); } } string schoolName = row[School]; if (!string.IsNullOrWhiteSpace(schoolName)) { // Add school if it doesn't exist Guid schoolGuid; var schoolExists = lookupContext.DefinedValues.Any(s => s.DefinedTypeId == schoolDefinedType.Id && s.Value.Equals(schoolName)); if (!schoolExists) { var newSchool = new DefinedValue(); newSchool.DefinedTypeId = schoolDefinedType.Id; newSchool.Value = schoolName; newSchool.Order = 0; lookupContext.DefinedValues.Add(newSchool); lookupContext.SaveChanges(); schoolGuid = newSchool.Guid; } else { schoolGuid = lookupContext.DefinedValues.FirstOrDefault(s => s.Value.Equals(schoolName)).Guid; } AddPersonAttribute(schoolAttribute, person, schoolGuid.ToString().ToUpper()); } foreach (var attributePair in customAttributes) { string newAttributeValue = row[attributePair.Key]; if (!string.IsNullOrWhiteSpace(newAttributeValue)) { // check if this attribute value is a date DateTime valueAsDateTime; if (DateTime.TryParseExact(newAttributeValue, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueAsDateTime)) { newAttributeValue = valueAsDateTime.ToString("yyyy-MM-dd"); } int?newAttributeId = personAttributes.Where(a => a.Key == attributePair.Value.RemoveWhitespace()) .Select(a => (int?)a.Id).FirstOrDefault(); if (newAttributeId != null) { var newAttribute = AttributeCache.Read((int)newAttributeId); AddPersonAttribute(newAttribute, person, newAttributeValue); } } } // Add notes to timeline var notePairs = new Dictionary <string, string>(); notePairs.Add("General", row[GeneralNote]); notePairs.Add("Medical", row[MedicalNote]); notePairs.Add("Security", row[SecurityNote]); foreach (var notePair in notePairs.Where(n => !string.IsNullOrWhiteSpace(n.Value))) { var newNote = new Note(); newNote.NoteTypeId = personalNoteTypeId; newNote.CreatedByPersonAliasId = ImportPersonAliasId; newNote.CreatedDateTime = ImportDateTime; newNote.Text = notePair.Value; newNote.ForeignKey = rowPersonKey; newNote.ForeignId = rowPersonId; newNote.Caption = string.Format("{0} Note", notePair.Key); if (!notePair.Key.Equals("General")) { newNote.IsAlert = true; } newNoteList.Add(newNote); } #endregion person create var groupMember = new GroupMember(); groupMember.Person = person; groupMember.GroupRoleId = groupRoleId; groupMember.CreatedDateTime = ImportDateTime; groupMember.ModifiedDateTime = ImportDateTime; groupMember.CreatedByPersonAliasId = ImportPersonAliasId; groupMember.GroupMemberStatus = GroupMemberStatus.Active; if (rowFamilyKey != currentFamilyGroup.ForeignKey) { // person not part of the previous family, see if that family exists or create a new one currentFamilyGroup = ImportedFamilies.FirstOrDefault(g => g.ForeignKey == rowFamilyKey); if (currentFamilyGroup == null) { currentFamilyGroup = CreateFamilyGroup(row[FamilyName], rowFamilyKey); newFamilyList.Add(currentFamilyGroup); newFamilies++; } else { lookupContext.Groups.Attach(currentFamilyGroup); lookupContext.Entry(currentFamilyGroup).State = EntityState.Modified; } currentFamilyGroup.Members.Add(groupMember); } else { // person is part of this family group, check if they're a visitor if (isFamilyRelationship || currentFamilyGroup.Members.Count() < 1) { currentFamilyGroup.Members.Add(groupMember); } else { var visitorFamily = CreateFamilyGroup(person.LastName + " Family", rowFamilyKey); visitorFamily.Members.Add(groupMember); newFamilyList.Add(visitorFamily); newVisitorList.Add(visitorFamily); newFamilies++; } } // look ahead 1 row string rowNextFamilyKey = "-1"; if ((row = csvData.Database.FirstOrDefault()) != null) { rowNextFamilyKey = row[FamilyId]; } newPeople++; completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} people imported.", completed)); } if (newPeople >= ReportingNumber && rowNextFamilyKey != currentFamilyGroup.ForeignKey) { SaveIndividuals(newFamilyList, newVisitorList, newNoteList); lookupContext.SaveChanges(); ReportPartialProgress(); // Clear out variables currentFamilyGroup = new Group(); newFamilyList.Clear(); newVisitorList.Clear(); newNoteList.Clear(); newPeople = 0; } } else { row = csvData.Database.FirstOrDefault(); } } // Save any changes to new families if (newFamilyList.Any()) { SaveIndividuals(newFamilyList, newVisitorList, newNoteList); } // Save any changes to existing families lookupContext.SaveChanges(); DetachAllInContext(lookupContext); lookupContext.Dispose(); ReportProgress(0, string.Format("Finished individual import: {0:N0} families and {1:N0} people added.", newFamilies, completed)); return(completed); }
/// <summary> /// Saves the people. /// </summary> /// <param name="familyList">The family list.</param> /// <param name="visitorList">The visitor list.</param> /// <param name="ownerRole">The owner role.</param> /// <param name="childRoleId">The child role identifier.</param> /// <param name="inviteeRoleId">The invitee role identifier.</param> /// <param name="invitedByRoleId">The invited by role identifier.</param> /// <param name="canCheckInRoleId">The can check in role identifier.</param> /// <param name="allowCheckInByRoleId">The allow check in by role identifier.</param> private void SavePeople( List<Group> familyList, List<Group> visitorList, Dictionary<Guid, string> previousNamesList, GroupTypeRole ownerRole, int childRoleId, int inviteeRoleId, int invitedByRoleId, int canCheckInRoleId, int allowCheckInByRoleId ) { var rockContext = new RockContext(); var groupMemberService = new GroupMemberService( rockContext ); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Groups.AddRange( familyList ); rockContext.SaveChanges( DisableAuditing ); foreach ( var familyGroups in familyList.GroupBy<Group, int?>( g => g.ForeignId ) ) { bool visitorsExist = familyGroups.Count() > 1; foreach ( var newFamilyGroup in familyGroups ) { foreach ( var groupMember in newFamilyGroup.Members ) { // don't call LoadAttributes, it only rewrites existing cache objects // groupMember.Person.LoadAttributes( rockContext ); foreach ( var attributeCache in groupMember.Person.Attributes.Select( a => a.Value ) ) { var existingValue = rockContext.AttributeValues.FirstOrDefault( v => v.Attribute.Key == attributeCache.Key && v.EntityId == groupMember.Person.Id ); var newAttributeValue = groupMember.Person.AttributeValues[attributeCache.Key]; // set the new value and add it to the database if ( existingValue == null ) { existingValue = new AttributeValue(); existingValue.AttributeId = newAttributeValue.AttributeId; existingValue.EntityId = groupMember.Person.Id; existingValue.Value = newAttributeValue.Value; rockContext.AttributeValues.Add( existingValue ); } else { existingValue.Value = newAttributeValue.Value; rockContext.Entry( existingValue ).State = EntityState.Modified; } } // add a default person alias if ( !groupMember.Person.Aliases.Any( a => a.AliasPersonId == groupMember.Person.Id ) ) { groupMember.Person.Aliases.Add( new PersonAlias { AliasPersonId = groupMember.Person.Id, AliasPersonGuid = groupMember.Person.Guid, ForeignId = groupMember.Person.ForeignId, ForeignKey = groupMember.Person.ForeignKey } ); } // assign the previous name if ( previousNamesList.Any( l => l.Key.Equals( groupMember.Person.Guid ) ) ) { var newPreviousName = new PersonPreviousName(); newPreviousName.LastName = previousNamesList[groupMember.Person.Guid]; newPreviousName.PersonAlias = groupMember.Person.Aliases.FirstOrDefault(); rockContext.PersonPreviousNames.Add( newPreviousName ); } // assign the giving group if ( groupMember.GroupRoleId != childRoleId ) { groupMember.Person.GivingGroupId = newFamilyGroup.Id; } if ( visitorsExist ) { // Retrieve or create the group this person is an owner of var ownerGroup = groupMemberService.Queryable() .Where( m => m.PersonId == groupMember.Person.Id && m.GroupRoleId == ownerRole.Id ) .Select( m => m.Group ) .FirstOrDefault(); if ( ownerGroup == null ) { var ownerGroupMember = new GroupMember(); ownerGroupMember.PersonId = groupMember.Person.Id; ownerGroupMember.GroupRoleId = ownerRole.Id; ownerGroup = new Group(); ownerGroup.Name = ownerRole.GroupType.Name; ownerGroup.GroupTypeId = ownerRole.GroupTypeId.Value; ownerGroup.Members.Add( ownerGroupMember ); rockContext.Groups.Add( ownerGroup ); } // if this is a visitor, then add relationships to the family member(s) if ( visitorList.Where( v => v.ForeignId == newFamilyGroup.ForeignId ) .Any( v => v.Members.Any( m => m.Person.ForeignId.Equals( groupMember.Person.ForeignId ) ) ) ) { var familyMembers = familyGroups.Except( visitorList ).SelectMany( g => g.Members ); foreach ( var familyMember in familyMembers.Select( m => m.Person ) ) { var invitedByMember = new GroupMember(); invitedByMember.PersonId = familyMember.Id; invitedByMember.GroupRoleId = invitedByRoleId; ownerGroup.Members.Add( invitedByMember ); if ( groupMember.Person.Age < 18 && familyMember.Age > 18 ) { var allowCheckinMember = new GroupMember(); allowCheckinMember.PersonId = familyMember.Id; allowCheckinMember.GroupRoleId = allowCheckInByRoleId; ownerGroup.Members.Add( allowCheckinMember ); } } } else { // not a visitor, add the visitors to the family member's known relationship var visitors = visitorList.Where( v => v.ForeignId == newFamilyGroup.ForeignId ) .SelectMany( g => g.Members ).ToList(); foreach ( var visitor in visitors.Select( g => g.Person ) ) { var inviteeMember = new GroupMember(); inviteeMember.PersonId = visitor.Id; inviteeMember.GroupRoleId = inviteeRoleId; ownerGroup.Members.Add( inviteeMember ); // if visitor can be checked in and this person is considered an adult if ( visitor.Age < 18 && groupMember.Person.Age > 18 ) { var canCheckInMember = new GroupMember(); canCheckInMember.PersonId = visitor.Id; canCheckInMember.GroupRoleId = canCheckInRoleId; ownerGroup.Members.Add( canCheckInMember ); } } } } // Add known relationship group var knownRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS ); var knownGroup = groupMemberService.Queryable() .Where( m => m.PersonId == groupMember.Person.Id && m.GroupRoleId == allowCheckInByRoleId && m.Group.GroupTypeId == knownRelationshipGroupType.Id ) .Select( m => m.Group ) .FirstOrDefault(); if ( knownGroup == null ) { var knownGroupMember = new GroupMember(); knownGroupMember.PersonId = groupMember.Person.Id; knownGroupMember.GroupRoleId = allowCheckInByRoleId; knownGroup = new Group(); knownGroup.Name = knownRelationshipGroupType.Name; knownGroup.GroupTypeId = knownRelationshipGroupType.Id; knownGroup.Members.Add( knownGroupMember ); rockContext.Groups.Add( knownGroup ); } // Add implied relationship group var impliedRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS ); var impliedGroup = groupMemberService.Queryable() .Where( m => m.PersonId == groupMember.Person.Id && m.GroupRoleId == ownerRole.Id && m.Group.GroupTypeId == impliedRelationshipGroupType.Id ) .Select( m => m.Group ) .FirstOrDefault(); if ( impliedGroup == null ) { var impliedGroupMember = new GroupMember(); impliedGroupMember.PersonId = groupMember.Person.Id; impliedGroupMember.GroupRoleId = ownerRole.Id; impliedGroup = new Group(); impliedGroup.Name = impliedRelationshipGroupType.Name; impliedGroup.GroupTypeId = impliedRelationshipGroupType.Id; impliedGroup.Members.Add( impliedGroupMember ); rockContext.Groups.Add( impliedGroup ); } } } } rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( DisableAuditing ); // add the new people to our tracking list if ( familyList.Any() ) { var familyMembers = familyList.SelectMany( gm => gm.Members ); ImportedPeople.AddRange( familyMembers.Select( m => new PersonKeys { PersonAliasId = (int)m.Person.PrimaryAliasId, PersonId = m.Person.Id, IndividualId = m.Person.ForeignId, HouseholdId = m.Group.ForeignId, FamilyRoleId = m.Person.ReviewReasonNote.ConvertToEnum<FamilyRole>() } ).ToList() ); } if ( visitorList.Any() ) { var visitors = visitorList.SelectMany( gm => gm.Members ); ImportedPeople.AddRange( visitors.Select( m => new PersonKeys { PersonAliasId = (int)m.Person.PrimaryAliasId, PersonId = m.Person.Id, IndividualId = m.Person.ForeignId, HouseholdId = m.Group.ForeignId, FamilyRoleId = m.Person.ReviewReasonNote.ConvertToEnum<FamilyRole>() } ).ToList() ); } } ); // end wrap transaction }
private void CreateControls(bool setSelection) { // Load all the attribute controls attributeControls.Clear(); pnlAttributes.Controls.Clear(); phDuplicates.Controls.Clear(); var rockContext = new RockContext(); var attributeService = new AttributeService(rockContext); var locationService = new LocationService(rockContext); foreach (string categoryGuid in GetAttributeValue("AttributeCategories").SplitDelimitedValues(false)) { Guid guid = Guid.Empty; if (Guid.TryParse(categoryGuid, out guid)) { var category = CategoryCache.Read(guid); if (category != null) { var attributeControl = new NewFamilyAttributes(); attributeControl.ClearRows(); pnlAttributes.Controls.Add(attributeControl); attributeControls.Add(attributeControl); attributeControl.ID = "familyAttributes_" + category.Id.ToString(); attributeControl.CategoryId = category.Id; foreach (var attribute in attributeService.GetByCategoryId(category.Id)) { if (attribute.IsAuthorized(Authorization.EDIT, CurrentPerson)) { attributeControl.AttributeList.Add(AttributeCache.Read(attribute)); } } } } } nfmMembers.ClearRows(); nfciContactInfo.ClearRows(); var groupMemberService = new GroupMemberService(rockContext); var familyGroupType = GroupTypeCache.GetFamilyGroupType(); int adultRoleId = familyGroupType.Roles.First(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id; var homeLocationGuid = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid(); var location = locationService.Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country); foreach (var familyMember in FamilyMembers) { string familyMemberGuidString = familyMember.Person.Guid.ToString().Replace("-", "_"); var familyMemberRow = new NewFamilyMembersRow(); nfmMembers.Controls.Add(familyMemberRow); familyMemberRow.ID = string.Format("row_{0}", familyMemberGuidString); familyMemberRow.RoleUpdated += familyMemberRow_RoleUpdated; familyMemberRow.DeleteClick += familyMemberRow_DeleteClick; familyMemberRow.PersonGuid = familyMember.Person.Guid; familyMemberRow.RequireGender = nfmMembers.RequireGender; familyMemberRow.RequireGrade = nfmMembers.RequireGrade; familyMemberRow.RoleId = familyMember.GroupRoleId; familyMemberRow.ShowGrade = familyMember.GroupRoleId == _childRoleId; familyMemberRow.ValidationGroup = BlockValidationGroup; var contactInfoRow = new NewFamilyContactInfoRow(); nfciContactInfo.Controls.Add(contactInfoRow); contactInfoRow.ID = string.Format("ci_row_{0}", familyMemberGuidString); contactInfoRow.PersonGuid = familyMember.Person.Guid; contactInfoRow.IsMessagingEnabled = _SMSEnabled; contactInfoRow.PersonName = familyMember.Person.FullName; if (_homePhone != null) { var homePhoneNumber = familyMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _homePhone.Id).FirstOrDefault(); if (homePhoneNumber != null) { contactInfoRow.HomePhoneNumber = PhoneNumber.FormattedNumber(homePhoneNumber.CountryCode, homePhoneNumber.Number); contactInfoRow.HomePhoneCountryCode = homePhoneNumber.CountryCode; } } if (_cellPhone != null) { var cellPhoneNumber = familyMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _cellPhone.Id).FirstOrDefault(); if (cellPhoneNumber != null) { contactInfoRow.CellPhoneNumber = PhoneNumber.FormattedNumber(cellPhoneNumber.CountryCode, cellPhoneNumber.Number); contactInfoRow.CellPhoneCountryCode = cellPhoneNumber.CountryCode; } } contactInfoRow.Email = familyMember.Person.Email; if (setSelection) { if (familyMember.Person != null) { familyMemberRow.TitleValueId = familyMember.Person.TitleValueId; familyMemberRow.FirstName = familyMember.Person.FirstName; familyMemberRow.LastName = familyMember.Person.LastName; familyMemberRow.SuffixValueId = familyMember.Person.SuffixValueId; familyMemberRow.Gender = familyMember.Person.Gender; familyMemberRow.BirthDate = familyMember.Person.BirthDate; familyMemberRow.ConnectionStatusValueId = familyMember.Person.ConnectionStatusValueId; familyMemberRow.GradeOffset = familyMember.Person.GradeOffset; } } foreach (var attributeControl in attributeControls) { var attributeRow = new NewFamilyAttributesRow(); attributeControl.Controls.Add(attributeRow); attributeRow.ID = string.Format("{0}_{1}", attributeControl.ID, familyMemberGuidString); attributeRow.AttributeList = attributeControl.AttributeList; attributeRow.PersonGuid = familyMember.Person.Guid; attributeRow.PersonName = familyMember.Person.FullName; if (setSelection) { attributeRow.SetEditValues(familyMember.Person); } } if (Duplicates.ContainsKey(familyMember.Person.Guid)) { var dupRow = new HtmlGenericControl("div"); dupRow.AddCssClass("row"); dupRow.ID = string.Format("dupRow_{0}", familyMemberGuidString); phDuplicates.Controls.Add(dupRow); var newPersonCol = new HtmlGenericControl("div"); newPersonCol.AddCssClass("col-md-6"); newPersonCol.ID = string.Format("newPersonCol_{0}", familyMemberGuidString); dupRow.Controls.Add(newPersonCol); newPersonCol.Controls.Add(PersonHtmlPanel( familyMemberGuidString, familyMember.Person, familyMember.GroupRole, location, rockContext)); LinkButton lbRemoveMember = new LinkButton(); lbRemoveMember.ID = string.Format("lbRemoveMember_{0}", familyMemberGuidString); lbRemoveMember.AddCssClass("btn btn-danger btn-xs"); lbRemoveMember.Text = "Remove"; lbRemoveMember.Click += lbRemoveMember_Click; newPersonCol.Controls.Add(lbRemoveMember); var dupPersonCol = new HtmlGenericControl("div"); dupPersonCol.AddCssClass("col-md-6"); dupPersonCol.ID = string.Format("dupPersonCol_{0}", familyMemberGuidString); dupRow.Controls.Add(dupPersonCol); var duplicateHeader = new HtmlGenericControl("h4"); duplicateHeader.InnerText = "Possible Duplicate Records"; dupPersonCol.Controls.Add(duplicateHeader); foreach (var duplicate in Duplicates[familyMember.Person.Guid]) { GroupTypeRole groupTypeRole = null; Location duplocation = null; var familyGroupMember = groupMemberService.Queryable() .Where(a => a.PersonId == duplicate.Id) .Where(a => a.Group.GroupTypeId == familyGroupType.Id) .Select(s => new { s.GroupRole, GroupLocation = s.Group.GroupLocations.Where(a => a.GroupLocationTypeValue.Guid == homeLocationGuid).Select(a => a.Location).FirstOrDefault() }) .FirstOrDefault(); if (familyGroupMember != null) { groupTypeRole = familyGroupMember.GroupRole; duplocation = familyGroupMember.GroupLocation; } dupPersonCol.Controls.Add(PersonHtmlPanel( familyMemberGuidString, duplicate, groupTypeRole, duplocation, rockContext)); } } } ShowPage(); }
/// <summary> /// Saves the people. /// </summary> /// <param name="familyList">The family list.</param> /// <param name="visitorList">The visitor list.</param> /// <param name="ownerRole">The owner role.</param> /// <param name="childRoleId">The child role identifier.</param> /// <param name="inviteeRoleId">The invitee role identifier.</param> /// <param name="invitedByRoleId">The invited by role identifier.</param> /// <param name="canCheckInRoleId">The can check in role identifier.</param> /// <param name="allowCheckInByRoleId">The allow check in by role identifier.</param> private static void SavePeople(List <Group> familyList, List <Group> visitorList, GroupTypeRole ownerRole, int childRoleId, int inviteeRoleId, int invitedByRoleId, int canCheckInRoleId, int allowCheckInByRoleId) { var rockContext = new RockContext(); var groupMemberService = new GroupMemberService(rockContext); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Groups.AddRange(familyList); rockContext.SaveChanges(DisableAudit); var newAttributeValues = new List <AttributeValue>(); foreach (var familyGroups in familyList.GroupBy <Group, int?>(g => g.ForeignId.AsType <int?>())) { bool visitorsExist = familyGroups.Count() > 1; foreach (var newFamilyGroup in familyGroups) { foreach (var groupMember in newFamilyGroup.Members) { var person = groupMember.Person; foreach (var attributeCache in person.Attributes.Select(a => a.Value)) { var newValue = person.AttributeValues[attributeCache.Key]; if (newValue != null) { newValue.EntityId = person.Id; newAttributeValues.Add(newValue); } } if (!person.Aliases.Any(a => a.AliasPersonId == person.Id)) { person.Aliases.Add(new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid }); } if (groupMember.GroupRoleId != childRoleId) { person.GivingGroupId = newFamilyGroup.Id; } if (visitorsExist) { // Retrieve or create the group this person is an owner of var ownerGroup = groupMemberService.Queryable() .Where(m => m.PersonId == person.Id && m.GroupRoleId == ownerRole.Id) .Select(m => m.Group) .FirstOrDefault(); if (ownerGroup == null) { var ownerGroupMember = new GroupMember(); ownerGroupMember.PersonId = person.Id; ownerGroupMember.GroupRoleId = ownerRole.Id; ownerGroup = new Group(); ownerGroup.Name = ownerRole.GroupType.Name; ownerGroup.GroupTypeId = ownerRole.GroupTypeId.Value; ownerGroup.Members.Add(ownerGroupMember); rockContext.Groups.Add(ownerGroup); } // if this is a visitor, then add proper relationships to the family member if (visitorList.Where(v => v.ForeignId == newFamilyGroup.ForeignId) .Any(v => v.Members.Any(m => m.Person.ForeignId.Equals(person.Id)))) { var familyMembers = familyGroups.Except(visitorList).SelectMany(g => g.Members); foreach (var familyMember in familyMembers.Select(m => m.Person)) { var invitedByMember = new GroupMember(); invitedByMember.PersonId = familyMember.Id; invitedByMember.GroupRoleId = invitedByRoleId; ownerGroup.Members.Add(invitedByMember); if (person.Age < 18 && familyMember.Age > 15) { var allowCheckinMember = new GroupMember(); allowCheckinMember.PersonId = familyMember.Id; allowCheckinMember.GroupRoleId = allowCheckInByRoleId; ownerGroup.Members.Add(allowCheckinMember); } } } else { // not a visitor, add the visitors to the family member's known relationship var visitors = visitorList.Where(v => v.ForeignId == newFamilyGroup.ForeignId).SelectMany(g => g.Members); foreach (var visitor in visitors.Select(g => g.Person)) { var inviteeMember = new GroupMember(); inviteeMember.PersonId = visitor.Id; inviteeMember.GroupRoleId = inviteeRoleId; ownerGroup.Members.Add(inviteeMember); // if visitor can be checked in and this person is considered an adult if (visitor.Age < 18 && person.Age > 15) { var canCheckInMember = new GroupMember(); canCheckInMember.PersonId = visitor.Id; canCheckInMember.GroupRoleId = canCheckInRoleId; ownerGroup.Members.Add(canCheckInMember); } } } } } } } rockContext.AttributeValues.AddRange(newAttributeValues); rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges(DisableAudit); }); }
/// <summary> /// Checks the settings. /// </summary> /// <returns></returns> private bool CheckSettings() { _rockContext = _rockContext ?? new RockContext(); _mode = GetAttributeValue( "Mode" ); _autoFill = GetAttributeValue( "AutoFillForm" ).AsBoolean(); tbEmail.Required = _autoFill; string registerButtonText = GetAttributeValue( "RegisterButtonAltText" ); if ( string.IsNullOrWhiteSpace( registerButtonText ) ) { registerButtonText = "Register"; } btnRegister.Text = registerButtonText; int groupId = PageParameter( "GroupId" ).AsInteger(); _group = new GroupService( _rockContext ) .Queryable( "GroupType.DefaultGroupRole" ).AsNoTracking() .FirstOrDefault( g => g.Id == groupId ); if ( _group == null ) { nbNotice.Heading = "Unknown Group"; nbNotice.Text = "<p>This page requires a valid group id parameter, and there was not one provided.</p>"; return false; } else { _defaultGroupRole = _group.GroupType.DefaultGroupRole; } _dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() ); if ( _dvcConnectionStatus == null ) { nbNotice.Heading = "Invalid Connection Status"; nbNotice.Text = "<p>The selected Connection Status setting does not exist.</p>"; return false; } _dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() ); if ( _dvcRecordStatus == null ) { nbNotice.Heading = "Invalid Record Status"; nbNotice.Text = "<p>The selected Record Status setting does not exist.</p>"; return false; } _married = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid() ); _homeAddressType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid() ); _familyType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid() ); _adultRole = _familyType.Roles.FirstOrDefault( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) ); if ( _married == null || _homeAddressType == null || _familyType == null || _adultRole == null ) { nbNotice.Heading = "Missing System Value"; nbNotice.Text = "<p>There is a missing or invalid system value. Check the settings for Marital Status of 'Married', Location Type of 'Home', Group Type of 'Family', and Family Group Role of 'Adult'.</p>"; return false; } return true; }
/// <summary> /// Checks the settings. If false is returned, it's expected that the caller will make /// the nbNotice visible to inform the user of the "settings" error. /// </summary> /// <returns>true if settings are valid; false otherwise</returns> private bool CheckSettings() { _rockContext = _rockContext ?? new RockContext(); _autoFill = GetAttributeValue("AutoFillForm").AsBoolean(); string registerButtonText = GetAttributeValue("RegisterButtonAltText"); if (string.IsNullOrWhiteSpace(registerButtonText)) { registerButtonText = "Register"; } btnRegister.Text = registerButtonText; var publishGroupService = new PublishGroupService(_rockContext); if (_publishGroup == null) { var publishGroupGuid = PageParameter("PublishGroup").AsGuidOrNull(); if (publishGroupGuid.HasValue) { _publishGroup = publishGroupService.Get(publishGroupGuid.Value); } else { var slug = PageParameter("PublishGroup").ToLower(); _publishGroup = publishGroupService.Queryable().Where(pg => pg.Slug == slug).FirstOrDefault(); } } if (_publishGroup == null || _publishGroup.PublishGroupStatus != PublishGroupStatus.Approved) { nbNotice.Heading = "Unknown Group"; nbNotice.Text = "<p>This page requires a valid group identifying parameter and there was not one provided.</p>"; nbNotice.Visible = true; return(false); } if (_publishGroup.RegistrationLink.IsNotNullOrWhiteSpace()) { Response.Redirect(_publishGroup.RegistrationLink, false); Context.ApplicationInstance.CompleteRequest(); return(false); } _showSpouse = _publishGroup.AllowSpouseRegistration; _defaultGroupRole = _publishGroup.Group.GroupType.DefaultGroupRole; _dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid()); if (_dvcConnectionStatus == null) { nbNotice.Heading = "Invalid Connection Status"; nbNotice.Text = "<p>The selected Connection Status setting does not exist.</p>"; return(false); } _dvcRecordStatus = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid()); if (_dvcRecordStatus == null) { nbNotice.Heading = "Invalid Record Status"; nbNotice.Text = "<p>The selected Record Status setting does not exist.</p>"; return(false); } _married = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid()); _homeAddressType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()); _familyType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()); _adultRole = _familyType.Roles.FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())); if (_married == null || _homeAddressType == null || _familyType == null || _adultRole == null) { nbNotice.Heading = "Missing System Value"; nbNotice.Text = "<p>There is a missing or invalid system value. Check the settings for Marital Status of 'Married', Location Type of 'Home', Group Type of 'Family', and Family Group Role of 'Adult'.</p>"; return(false); } return(true); }
/// <summary> /// Handles the SaveClick event of the mdAddCheckinGroupType 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 mdAddCheckinGroupType_SaveClick( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { var groupTypeService = new GroupTypeService( rockContext ); GroupType groupType; if ( hfGroupTypeId.Value.AsInteger() == 0 ) { groupType = new GroupType(); groupTypeService.Add( groupType ); groupType.GroupTypePurposeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE ).Id; groupType.ShowInNavigation = false; groupType.ShowInGroupList = false; var defaultRole = new GroupTypeRole(); defaultRole.Name = "Member"; groupType.Roles.Add( defaultRole ); } else { groupType = groupTypeService.Get( hfGroupTypeId.Value.AsInteger() ); } groupType.Name = tbGroupTypeName.Text; groupType.Description = tbGroupTypeDescription.Text; rockContext.SaveChanges(); // Reload to check for setting default role groupType = groupTypeService.Get( groupType.Id ); if ( groupType != null && !groupType.DefaultGroupRoleId.HasValue && groupType.Roles.Any() ) { groupType.DefaultGroupRoleId = groupType.Roles.First().Id; rockContext.SaveChanges(); } } mdAddEditCheckinGroupType.Hide(); BindGrid(); }
/// <summary> /// Maps the person. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="selectedColumns">The selected columns.</param> private void MapPerson(IQueryable <Row> tableData, List <string> selectedColumns = null) { var lookupContext = new RockContext(); var groupTypeRoleService = new GroupTypeRoleService(lookupContext); // Marital statuses: Married, Single, Separated, etc var maritalStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS), lookupContext).DefinedValues; // Connection statuses: Member, Visitor, Attendee, etc var connectionStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS), lookupContext).DefinedValues; // Record status reasons: No Activity, Moved, Deceased, etc var recordStatusReasons = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_RECORD_STATUS_REASON), lookupContext).DefinedValues; // Record statuses: Active, Inactive, Pending int?recordStatusActiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE), lookupContext).Id; int?recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE), lookupContext).Id; int?recordStatusPendingId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING), lookupContext).Id; // Record type: Person int?personRecordTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON), lookupContext).Id; // Suffix type: Dr., Jr., II, etc var suffixTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_SUFFIX)).DefinedValues; // Title type: Mr., Mrs. Dr., etc var titleTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_TITLE), lookupContext).DefinedValues; // Note type: Comment int noteCommentTypeId = new NoteTypeService(lookupContext).Get(new Guid("7E53487C-D650-4D85-97E2-350EB8332763")).Id; // Group roles: Owner, Adult, Child, others GroupTypeRole ownerRole = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER)); int adultRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id; int childRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)).Id; int inviteeRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_INVITED)).Id; int invitedByRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_INVITED_BY)).Id; int canCheckInRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_CAN_CHECK_IN)).Id; int allowCheckInByRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_ALLOW_CHECK_IN_BY)).Id; // Group type: Family int familyGroupTypeId = new GroupTypeService(lookupContext).Get(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY)).Id; // Look up additional Person attributes (existing) var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).ToList(); // Cached F1 attributes: IndividualId, HouseholdId // Core attributes: PreviousChurch, Position, Employer, School var individualIdAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "F1IndividualId")); var householdIdAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "F1HouseholdId")); var previousChurchAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "PreviousChurch")); var employerAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Employer")); var positionAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Position")); var firstVisitAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "FirstVisit")); var schoolAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "School")); var membershipDateAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "MembershipDate")); var familyList = new List <Group>(); var visitorList = new List <Group>(); int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying person import ({0:N0} found, {1:N0} already exist).", totalRows, ImportedPeople.Count())); foreach (var groupedRows in tableData.GroupBy <Row, int?>(r => r["Household_ID"] as int?)) { var familyGroup = new Group(); var householdCampusList = new List <string>(); foreach (var row in groupedRows) { bool isFamilyRelationship = true; string currentCampus = string.Empty; int? individualId = row["Individual_ID"] as int?; int? householdId = row["Household_ID"] as int?; if (GetPersonAliasId(individualId, householdId) == null) { var person = new Person(); person.FirstName = row["First_Name"] as string; person.MiddleName = row["Middle_Name"] as string; person.NickName = row["Goes_By"] as string ?? person.FirstName; person.LastName = row["Last_Name"] as string; person.BirthDate = row["Date_Of_Birth"] as DateTime?; person.CreatedByPersonAliasId = ImportPersonAlias.Id; person.RecordTypeValueId = personRecordTypeId; person.ForeignId = individualId.ToString(); int groupRoleId = adultRoleId; var gender = row["Gender"] as string; if (gender != null) { person.Gender = (Gender)Enum.Parse(typeof(Gender), gender); } string prefix = row["Prefix"] as string; if (prefix != null) { prefix = prefix.RemoveSpecialCharacters().Trim(); person.TitleValueId = titleTypes.Where(s => prefix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string suffix = row["Suffix"] as string; if (suffix != null) { suffix = suffix.RemoveSpecialCharacters().Trim(); person.SuffixValueId = suffixTypes.Where(s => suffix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string maritalStatus = row["Marital_Status"] as string; if (maritalStatus != null) { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == maritalStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); } else { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == "Unknown") .Select(dv => (int?)dv.Id).FirstOrDefault(); } string familyRole = row["Household_Position"].ToString().ToLower(); if (familyRole != null) { if (familyRole == "visitor") { isFamilyRelationship = false; } if (familyRole == "child" || person.Age < 18) { groupRoleId = childRoleId; } } string memberStatus = row["Status_Name"].ToString().ToLower(); if (memberStatus == "member") { person.ConnectionStatusValueId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER)).Id; person.RecordStatusValueId = recordStatusActiveId; } else if (memberStatus == "visitor") { person.ConnectionStatusValueId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR)).Id; person.RecordStatusValueId = recordStatusActiveId; } else if (memberStatus == "deceased") { person.IsDeceased = true; person.RecordStatusReasonValueId = recordStatusReasons.Where(dv => dv.Value == "Deceased") .Select(dv => dv.Id).FirstOrDefault(); person.RecordStatusValueId = recordStatusInactiveId; } else { // F1 defaults are Member & Visitor; all others are user-defined var customConnectionType = connectionStatusTypes.Where(dv => dv.Value == memberStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); int attendeeId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE)).Id; person.ConnectionStatusValueId = customConnectionType ?? attendeeId; person.RecordStatusValueId = recordStatusActiveId; } string campus = row["SubStatus_Name"] as string; if (campus != null) { currentCampus = campus; } string status_comment = row["Status_Comment"] as string; if (status_comment != null) { person.SystemNote = status_comment; } // Map F1 attributes person.Attributes = new Dictionary <string, AttributeCache>(); person.AttributeValues = new Dictionary <string, AttributeValue>(); // individual_id already defined in scope AddPersonAttribute(individualIdAttribute, person, individualId.ToString()); // household_id already defined in scope AddPersonAttribute(householdIdAttribute, person, householdId.ToString()); string previousChurch = row["Former_Church"] as string; AddPersonAttribute(previousChurchAttribute, person, previousChurch); string employer = row["Employer"] as string; AddPersonAttribute(employerAttribute, person, employer); string position = row["Occupation_Name"] as string ?? row["Occupation_Description"] as string; AddPersonAttribute(positionAttribute, person, position); string school = row["School_Name"] as string; AddPersonAttribute(schoolAttribute, person, school); DateTime?membershipDate = row["Status_Date"] as DateTime?; if (membershipDate != null) { person.CreatedDateTime = membershipDate; AddPersonAttribute(membershipDateAttribute, person, membershipDate.Value.ToString("MM/dd/yyyy")); } DateTime?firstVisit = row["First_Record"] as DateTime?; if (firstVisit != null) { person.CreatedDateTime = firstVisit; AddPersonAttribute(firstVisitAttribute, person, firstVisit.Value.ToString("MM/dd/yyyy")); } // Other Attributes to create: // former name // bar_code // member_env_code // denomination_name var groupMember = new GroupMember(); groupMember.Person = person; groupMember.GroupRoleId = groupRoleId; groupMember.GroupMemberStatus = GroupMemberStatus.Active; if (isFamilyRelationship) { householdCampusList.Add(currentCampus); familyGroup.Members.Add(groupMember); familyGroup.ForeignId = householdId.ToString(); } else { var visitorGroup = new Group(); visitorGroup.ForeignId = householdId.ToString(); visitorGroup.Members.Add(groupMember); visitorGroup.GroupTypeId = familyGroupTypeId; visitorGroup.Name = person.LastName + " Family"; visitorGroup.CampusId = CampusList.Where(c => c.Name.StartsWith(currentCampus) || c.ShortCode == currentCampus) .Select(c => (int?)c.Id).FirstOrDefault(); familyList.Add(visitorGroup); completed += visitorGroup.Members.Count; visitorList.Add(visitorGroup); } } } if (familyGroup.Members.Any()) { familyGroup.Name = familyGroup.Members.OrderByDescending(p => p.Person.Age) .FirstOrDefault().Person.LastName + " Family"; familyGroup.GroupTypeId = familyGroupTypeId; string primaryHouseholdCampus = householdCampusList.GroupBy(c => c).OrderByDescending(c => c.Count()) .Select(c => c.Key).FirstOrDefault(); if (primaryHouseholdCampus != null) { familyGroup.CampusId = CampusList.Where(c => c.Name.StartsWith(primaryHouseholdCampus) || c.ShortCode == primaryHouseholdCampus) .Select(c => (int?)c.Id).FirstOrDefault(); } familyList.Add(familyGroup); completed += familyGroup.Members.Count; if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} people imported ({1}% complete).", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { SavePeople(familyList, visitorList, ownerRole, childRoleId, inviteeRoleId, invitedByRoleId, canCheckInRoleId, allowCheckInByRoleId); familyList.Clear(); visitorList.Clear(); ReportPartialProgress(); } } } // Save any remaining families in the batch if (familyList.Any()) { SavePeople(familyList, visitorList, ownerRole, childRoleId, inviteeRoleId, invitedByRoleId, canCheckInRoleId, allowCheckInByRoleId); } ReportProgress(100, string.Format("Finished person import: {0:N0} people imported.", completed)); }
protected void btnSave_Click(object sender, EventArgs e) { RockContext rockContext = new RockContext(); var person = GetPerson(); var personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias)); var changeRequest = new ChangeRequest { EntityTypeId = personAliasEntityType.Id, EntityId = person.PrimaryAliasId ?? 0, RequestorAliasId = CurrentPersonAliasId ?? 0, RequestorComment = tbComments.Text }; changeRequest.EvaluatePropertyChange(person, "PhotoId", iuPhoto.BinaryFileId); changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0)); changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text); changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text); changeRequest.EvaluatePropertyChange(person, "MiddleName", tbMiddleName.Text); changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text); changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0)); var families = person.GetFamilies(); if (families.Count() == 1) { var groupMember = person.PrimaryFamily.Members.Where(gm => gm.PersonId == person.Id).FirstOrDefault(); if (groupMember != null) { GroupTypeRole groupTypeRole = null; GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext); if (ddlFamilyRole.SelectedValue == "A") { groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()); } else if (ddlFamilyRole.SelectedValue == "C") { groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()); } changeRequest.EvaluatePropertyChange(groupMember, "GroupRole", groupTypeRole, true); } } //Evaluate PhoneNumbers var phoneNumberTypeIds = new List <int>(); bool smsSelected = false; foreach (RepeaterItem item in rContactInfo.Items) { HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField; PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl("cbUnlisted") as CheckBox; CheckBox cbSms = item.FindControl("cbSms") as CheckBox; if (hfPhoneType != null && pnbPhone != null && cbSms != null && cbUnlisted != null) { int phoneNumberTypeId; if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId)) { var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId); string oldPhoneNumber = string.Empty; if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace()) //Add number { phoneNumber = new PhoneNumber { PersonId = person.Id, NumberTypeValueId = phoneNumberTypeId, CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode), IsMessagingEnabled = !smsSelected && cbSms.Checked, Number = PhoneNumber.CleanNumber(pnbPhone.Number) }; var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number); changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment); } else if (phoneNumber != null && pnbPhone.Text.IsNullOrWhiteSpace()) // delete number { var phoneComment = string.Format("{0}: {1}.", phoneNumber.NumberTypeValue.Value, phoneNumber.NumberFormatted); changeRequest.DeleteEntity(phoneNumber, true, phoneComment); } else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace()) // update number { changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true); changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true); changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true); } if (hfPhoneType.Value.AsInteger() == DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid())) { var validationInfo = ValidateMobilePhoneNumber(PhoneNumber.CleanNumber(pnbPhone.Number)); if (validationInfo.IsNotNullOrWhiteSpace()) { changeRequest.RequestorComment += "<h4>Dynamically Generated Warnings:</h4>" + validationInfo; } } } } } changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text); changeRequest.EvaluatePropertyChange(person, "IsEmailActive", cbIsEmailActive.Checked); changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>()); changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>()); var birthday = bpBirthday.SelectedDate; if (birthday.HasValue) { changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month); changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day); if (birthday.Value.Year != DateTime.MinValue.Year) { changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year); } else { int?year = null; changeRequest.EvaluatePropertyChange(person, "BirthYear", year); } } changeRequest.EvaluatePropertyChange(person, "Gender", ddlGender.SelectedValueAsEnum <Gender>()); changeRequest.EvaluatePropertyChange(person, "MaritalStatusValue", DefinedValueCache.Get(ddlMaritalStatus.SelectedValueAsInt() ?? 0)); changeRequest.EvaluatePropertyChange(person, "AnniversaryDate", dpAnniversaryDate.SelectedDate); changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear); var groupEntity = EntityTypeCache.Get(typeof(Group)); var groupLocationEntity = EntityTypeCache.Get(typeof(GroupLocation)); var family = person.GetFamily(); var familyChangeRequest = new ChangeRequest() { EntityTypeId = groupEntity.Id, EntityId = family.Id, RequestorAliasId = CurrentPersonAliasId ?? 0 }; familyChangeRequest.EvaluatePropertyChange(family, "Campus", CampusCache.Get(ddlCampus.SelectedValueAsInt() ?? 0)); var currentLocation = person.GetHomeLocation(); Location location = new Location { Street1 = acAddress.Street1, Street2 = acAddress.Street2, City = acAddress.City, State = acAddress.State, PostalCode = acAddress.PostalCode, }; var globalAttributesCache = GlobalAttributesCache.Get(); location.Country = globalAttributesCache.OrganizationCountry; location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country; if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) || (currentLocation != null && currentLocation.Street1 != location.Street1)) { LocationService locationService = new LocationService(rockContext); locationService.Add(location); rockContext.SaveChanges(); var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid()); var homeLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()); GroupLocation groupLocation = new GroupLocation { CreatedByPersonAliasId = CurrentPersonAliasId, ModifiedByPersonAliasId = CurrentPersonAliasId, GroupId = family.Id, LocationId = location.Id, GroupLocationTypeValueId = homeLocationType.Id, IsMailingLocation = true, IsMappedLocation = true }; var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString()); var homelocations = family.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id); foreach (var homelocation in homelocations) { familyChangeRequest.EvaluatePropertyChange( homelocation, "GroupLocationTypeValue", previousLocationType, true, homelocation.Location.ToString()); familyChangeRequest.EvaluatePropertyChange( homelocation, "IsMailingLocation", false, true, homelocation.Location.ToString()); } } //Adding a new family member if (pAddPerson.SelectedValue.HasValue) { PersonService personService = new PersonService(rockContext); var insertPerson = personService.Get(pAddPerson.SelectedValue.Value); if (insertPerson != null) { GroupMemberService groupMemberService = new GroupMemberService(rockContext); var familyGroupTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id; //Remove all other group members if (cbRemovePerson.Checked) { var members = groupMemberService.Queryable() .Where(m => m.PersonId == pAddPerson.SelectedValue.Value && m.Group.GroupTypeId == familyGroupTypeId); foreach (var member in members) { var comment = string.Format("Removed {0} from {1}", insertPerson.FullName, member.Group.Name); familyChangeRequest.DeleteEntity(member, true, comment); } } var personFamilies = person.GetFamilies().ToList(); GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext); var roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id; if (insertPerson.Age.HasValue && insertPerson.Age.Value < 18) { roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id; } foreach (var personFamily in personFamilies) { //Make a new group member GroupMember familyMember = new GroupMember { PersonId = pAddPerson.SelectedValue.Value, GroupId = personFamily.Id, GroupMemberStatus = GroupMemberStatus.Active, Guid = Guid.NewGuid(), GroupRoleId = roleId }; var insertComment = string.Format("Added {0} to {1}", insertPerson.FullName, personFamily.Name); familyChangeRequest.AddEntity(familyMember, rockContext, true, insertComment); } } } bool autoApply = CanAutoApply(person); List <string> errors; if (changeRequest.ChangeRecords.Any() || (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace())) { ChangeRequestService changeRequestService = new ChangeRequestService(rockContext); changeRequestService.Add(changeRequest); rockContext.SaveChanges(); if (autoApply) { changeRequest.CompleteChanges(rockContext, out errors); } changeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull()); } if (familyChangeRequest.ChangeRecords.Any()) { familyChangeRequest.RequestorComment = tbComments.Text; ChangeRequestService changeRequestService = new ChangeRequestService(rockContext); changeRequestService.Add(familyChangeRequest); rockContext.SaveChanges(); if (autoApply) { familyChangeRequest.CompleteChanges(rockContext, out errors); } familyChangeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull()); } if (autoApply) { NavigateToPerson(); } else { pnlMain.Visible = false; pnlNoPerson.Visible = false; pnlDone.Visible = true; } }
private Panel PersonHtmlPanel( string familyMemberGuidString, Person person, GroupTypeRole GroupTypeRole, Location location, RockContext rockContext) { var personInfoHtml = new StringBuilder(); Guid?recordTypeValueGuid = null; if (person.RecordTypeValueId.HasValue) { recordTypeValueGuid = DefinedValueCache.Read(person.RecordTypeValueId.Value, rockContext).Guid; } string personName = string.Format("{0} <small>(New Record)</small>", person.FullName); if (person.Id > 0) { string personUrl = ResolveRockUrl(string.Format("~/person/{0}", person.Id)); personName = string.Format("<a href='{0}' target='_blank'>{1}</a>", personUrl, person.FullName); } personInfoHtml.Append("<div class='row margin-b-lg'>"); // add photo if it's not the new record if (person.Id > 0) { personInfoHtml.Append("<div class='col-md-2'>"); if (person.PhotoId.HasValue) { personInfoHtml.AppendFormat( "<img src='{0}' class='img-thumbnail'>", Person.GetPhotoUrl(person.PhotoId.Value, person.Age, person.Gender, recordTypeValueGuid, 65, 65)); } personInfoHtml.Append("</div>"); } personInfoHtml.Append("<div class='col-md-10'>"); personInfoHtml.AppendFormat("<h4 class='margin-t-none'>{0}</h4>", personName); if (GroupTypeRole != null) { personInfoHtml.Append(GroupTypeRole.Name); } int?personAge = person.Age; if (personAge.HasValue) { personInfoHtml.AppendFormat(" <em>({0} yrs old)</em>", personAge.Value);; } var familyMembers = person.GetFamilyMembers(false, rockContext); if (familyMembers != null && familyMembers.Any()) { personInfoHtml.AppendFormat("<p><strong>Family Members:</strong> {0}", familyMembers.Select(m => m.Person.NickName).ToList().AsDelimited(", ")); } if (location != null) { personInfoHtml.AppendFormat("<p><strong>Address</strong><br/>{0}</p>", location.GetFullStreetAddress().ConvertCrLfToHtmlBr()); } // Generate the HTML for Email and PhoneNumbers if (!string.IsNullOrWhiteSpace(person.Email) || person.PhoneNumbers.Any()) { string emailAndPhoneHtml = "<p class='margin-t-sm'>"; emailAndPhoneHtml += person.Email; string phoneNumberList = string.Empty; foreach (var phoneNumber in person.PhoneNumbers) { var phoneType = DefinedValueCache.Read(phoneNumber.NumberTypeValueId ?? 0, rockContext); phoneNumberList += string.Format( "<br>{0} <small>{1}</small>", phoneNumber.IsUnlisted ? "Unlisted" : phoneNumber.NumberFormatted, phoneType != null ? phoneType.Value : string.Empty); } emailAndPhoneHtml += phoneNumberList + "<p>"; personInfoHtml.Append(emailAndPhoneHtml); } personInfoHtml.Append("</div>"); personInfoHtml.Append("</div>"); var dupPersonPnl = new Panel(); dupPersonPnl.ID = string.Format("dupPersonPnl_{0}_{1}", familyMemberGuidString, person.Id); dupPersonPnl.Controls.Add(new LiteralControl(personInfoHtml.ToString())); return(dupPersonPnl); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { RockContext rockContext = new RockContext(); var groupService = new GroupService(rockContext); Group group = null; Guid personGuid = Guid.Empty; GroupTypeRole groupMemberRole = null; // get group id from url Guid?groupGuid = PageParameter("GroupGuid").AsGuidOrNull(); if (groupGuid.HasValue) { group = groupService.Queryable("GroupType,GroupType.Roles").Where(g => g.Guid == groupGuid.Value).FirstOrDefault(); } if (group == null && GetAttributeValue("EnablePassingGroupId").AsBoolean(true)) { int?groupId = PageParameter("GroupId").AsIntegerOrNull(); if (groupId.HasValue) { group = groupService.Queryable("GroupType,GroupType.Roles").Where(g => g.Id == groupId).FirstOrDefault(); } } if (group == null) { groupGuid = GetAttributeValue("DefaultGroup").AsGuidOrNull(); if (groupGuid.HasValue) { group = groupService.Queryable("GroupType,GroupType.Roles").Where(g => g.Guid == groupGuid.Value).FirstOrDefault(); } } if (group == null) { lAlerts.Text = "Could not determine the group to add to."; return; } // Validate the group type. if (!string.IsNullOrEmpty(GetAttributeValue("LimitGroupType"))) { bool groupTypeMatch = GetAttributeValue("LimitGroupType") .Split(',') .Contains(group.GroupType.Guid.ToString(), StringComparer.CurrentCultureIgnoreCase); if (!groupTypeMatch) { lAlerts.Text = "Invalid group specified."; return; } } // get group role id from url if (!string.IsNullOrWhiteSpace(PageParameter("GroupMemberRoleId"))) { int groupMemberRoleId = 0; if (Int32.TryParse(PageParameter("GroupMemberRoleId"), out groupMemberRoleId)) { groupMemberRole = new GroupTypeRoleService(rockContext).Get(groupMemberRoleId); } } else if (!string.IsNullOrWhiteSpace(GetAttributeValue("DefaultGroupMemberRole"))) { Guid groupMemberRoleGuid = Guid.Empty; if (Guid.TryParse(GetAttributeValue("DefaultGroupMemberRole"), out groupMemberRoleGuid)) { groupMemberRole = new GroupTypeRoleService(rockContext).Get(groupMemberRoleGuid); } } else { groupMemberRole = group.GroupType.DefaultGroupRole; } if (groupMemberRole == null) { lAlerts.Text += "Could not determine the group role to use for the add."; return; } // get person if (!string.IsNullOrWhiteSpace(PageParameter("PersonGuid"))) { Guid.TryParse(PageParameter("PersonGuid"), out personGuid); } if (personGuid == Guid.Empty) { lAlerts.Text += "A valid person identifier was not found in the page address."; return; } // ensure that the group type has this role if (!group.GroupType.Roles.Contains(groupMemberRole)) { lAlerts.Text += "The group you have provided does not have the group member role configured."; return; } // get person Person person = new PersonService(rockContext).Get(personGuid); if (person == null) { lAlerts.Text += "A person could not be found for the identifier provided."; return; } // hide alert divAlert.Visible = false; // get status var groupMemberStatus = this.GetAttributeValue("GroupMemberStatus").ConvertToEnum <GroupMemberStatus>(GroupMemberStatus.Active); // load merge fields var mergeFields = new Dictionary <string, object>(); mergeFields.Add("GroupMemberStatus", groupMemberStatus.ToString()); mergeFields.Add("Group", group); mergeFields.Add("Person", person); mergeFields.Add("Role", groupMemberRole); mergeFields.Add("CurrentPerson", CurrentPerson); // ensure that the person is not already in the group if (group.Members.Where(m => m.PersonId == person.Id && m.GroupRoleId == groupMemberRole.Id).Count() != 0) { string templateInGroup = GetAttributeValue("AlreadyInGroupMessage"); lContent.Text = templateInGroup.ResolveMergeFields(mergeFields); return; } // add person to group GroupMember groupMember = new GroupMember(); groupMember.GroupId = group.Id; groupMember.PersonId = person.Id; groupMember.GroupRoleId = groupMemberRole.Id; groupMember.GroupMemberStatus = groupMemberStatus; group.Members.Add(groupMember); try { rockContext.SaveChanges(); } catch (Exception ex) { divAlert.Visible = true; lAlerts.Text = String.Format("An error occurred adding {0} to the group {1}. Message: {2}.", person.FullName, group.Name, ex.Message); } string templateSuccess = GetAttributeValue("SuccessMessage"); lContent.Text = templateSuccess.ResolveMergeFields(mergeFields); } }
private Panel PersonHtmlPanel( string groupMemberGuidString, Person person, GroupTypeRole GroupTypeRole, Location location, RockContext rockContext ) { var personInfoHtml = new StringBuilder(); Guid? recordTypeValueGuid = null; if ( person.RecordTypeValueId.HasValue ) { recordTypeValueGuid = DefinedValueCache.Read( person.RecordTypeValueId.Value, rockContext ).Guid; } string personName = string.Format("{0} <small>(New Record)</small>", person.FullName); if ( person.Id > 0 ) { string personUrl = ResolveRockUrl( string.Format( "~/person/{0}", person.Id ) ); personName = string.Format( "<a href='{0}' target='_blank'>{1}</a>", personUrl, person.FullName ); } personInfoHtml.Append( "<div class='row margin-b-lg'>" ); // add photo if it's not the new record if ( person.Id > 0 ) { personInfoHtml.Append( "<div class='col-md-2'>" ); if ( person.PhotoId.HasValue ) { personInfoHtml.AppendFormat( "<img src='{0}' class='img-thumbnail'>", Person.GetPersonPhotoUrl( person, 200, 200 ) ); } personInfoHtml.Append( "</div>" ); } personInfoHtml.Append( "<div class='col-md-10'>" ); personInfoHtml.AppendFormat( "<h4 class='margin-t-none'>{0}</h4>", personName ); if ( GroupTypeRole != null ) { personInfoHtml.Append( GroupTypeRole.Name ); } int? personAge = person.Age; if ( personAge.HasValue ) { personInfoHtml.AppendFormat( " <em>({0} yrs old)</em>", personAge.Value ); ; } var groupMembers = person.GetGroupMembers( _groupType.Id, false, rockContext ); if ( groupMembers != null && groupMembers.Any() ) { personInfoHtml.AppendFormat( "<p><strong>{0} Members:</strong> {1}", _groupType.Name, groupMembers.Select( m => m.Person.NickName ).ToList().AsDelimited( ", " ) ); } if ( location != null ) { personInfoHtml.AppendFormat( "<p><strong>Address</strong><br/>{0}</p>", location.GetFullStreetAddress().ConvertCrLfToHtmlBr() ); } // Generate the HTML for Email and PhoneNumbers if ( !string.IsNullOrWhiteSpace( person.Email ) || person.PhoneNumbers.Any() ) { string emailAndPhoneHtml = "<p class='margin-t-sm'>"; emailAndPhoneHtml += person.Email; string phoneNumberList = string.Empty; foreach ( var phoneNumber in person.PhoneNumbers ) { var phoneType = DefinedValueCache.Read( phoneNumber.NumberTypeValueId ?? 0, rockContext ); phoneNumberList += string.Format( "<br>{0} <small>{1}</small>", phoneNumber.IsUnlisted ? "Unlisted" : phoneNumber.NumberFormatted, phoneType != null ? phoneType.Value : string.Empty ); } emailAndPhoneHtml += phoneNumberList + "<p>"; personInfoHtml.Append( emailAndPhoneHtml ); } personInfoHtml.Append( "</div>" ); personInfoHtml.Append( "</div>" ); var dupPersonPnl = new Panel(); dupPersonPnl.ID = string.Format( "dupPersonPnl_{0}_{1}", groupMemberGuidString, person.Id ); dupPersonPnl.Controls.Add( new LiteralControl( personInfoHtml.ToString() ) ); return dupPersonPnl; }
/// <summary> /// Maps the activity ministry. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapActivityMinistry( IQueryable<Row> tableData ) { var lookupContext = new RockContext(); var rockContext = new RockContext(); // Add an Attribute for the unique F1 Ministry Id //int groupEntityTypeId = EntityTypeCache.Read("Rock.Model.Group").Id; //var ministryAttributeId = new AttributeService(lookupContext).Queryable().Where(a => a.EntityTypeId == groupEntityTypeId // && a.Key == "F1MinistryId").Select(a => a.Id).FirstOrDefault(); //var activityAttributeId = new AttributeService(lookupContext).Queryable().Where(a => a.EntityTypeId == groupEntityTypeId // && a.Key == "F1ActivityId").Select(a => a.Id).FirstOrDefault(); //if (ministryAttributeId == 0) //{ // var newMinistryAttribute = new Rock.Model.Attribute(); // newMinistryAttribute.Key = "F1MinistryId"; // newMinistryAttribute.Name = "F1 Ministry Id"; // newMinistryAttribute.FieldTypeId = IntegerFieldTypeId; // newMinistryAttribute.EntityTypeId = groupEntityTypeId; // newMinistryAttribute.EntityTypeQualifierValue = string.Empty; // newMinistryAttribute.EntityTypeQualifierColumn = string.Empty; // newMinistryAttribute.Description = "The FellowshipOne identifier for the ministry that was imported"; // newMinistryAttribute.DefaultValue = string.Empty; // newMinistryAttribute.IsMultiValue = false; // newMinistryAttribute.IsRequired = false; // newMinistryAttribute.Order = 0; // lookupContext.Attributes.Add(newMinistryAttribute); // lookupContext.SaveChanges(DisableAudit); // ministryAttributeId = newMinistryAttribute.Id; //} //if (activityAttributeId == 0) //{ // var newActivityAttribute = new Rock.Model.Attribute(); // newActivityAttribute.Key = "F1ActivityId"; // newActivityAttribute.Name = "F1 Activity Id"; // newActivityAttribute.FieldTypeId = IntegerFieldTypeId; // newActivityAttribute.EntityTypeId = groupEntityTypeId; // newActivityAttribute.EntityTypeQualifierValue = string.Empty; // newActivityAttribute.EntityTypeQualifierColumn = string.Empty; // newActivityAttribute.Description = "The FellowshipOne identifier for the activity that was imported"; // newActivityAttribute.DefaultValue = string.Empty; // newActivityAttribute.IsMultiValue = false; // newActivityAttribute.IsRequired = false; // newActivityAttribute.Order = 0; // lookupContext.Attributes.Add(newActivityAttribute); // lookupContext.SaveChanges(DisableAudit); // activityAttributeId = newActivityAttribute.Id; //} //// Get previously imported Ministries //List<AttributeValue> importedMinistriesAVList = new AttributeValueService(lookupContext).GetByAttributeId(ministryAttributeId).ToList(); //// Get previously imported Activities //List<AttributeValue> importedActivitiesAVList = new AttributeValueService( lookupContext ).GetByAttributeId( activityAttributeId ).ToList(); //int importedMinistriesCount = 0; //int importedActivitiesCount = 0; //if ( importedMinistriesAVList.Any() ) { importedMinistriesCount = importedMinistriesAVList.Count(); } //if ( importedActivitiesAVList.Any() ) { importedActivitiesCount = importedActivitiesAVList.Count(); } var orderMax = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Order != 0).ToList(); int order = orderMax.Max(o => o.Order) + 1; int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying ministry import ({0:N0} found).", totalRows ) ); //ReportProgress(0, string.Format("Previously Imported Ministries ({0:N0} found).", importedMinistriesCount)); //ReportProgress(0, string.Format("Previously Imported Activities ({0:N0} found).", importedActivitiesCount)); var newAreas = new List<GroupType>(); var newCategories = new List<GroupType>(); foreach ( var row in tableData ) { int? ministryId = row["Ministry_ID"] as int?; string ministryName = row["Ministry_Name"] as string; string ministryIdString = Convert.ToString( ministryId ); //GroupType importedMinistriesGTList = new GroupTypeService( lookupContext ).Queryable().Where( g => g.Name == ministryName && g.ForeignId == ( Convert.ToString( ministryId ) + 'm' ) ).FirstOrDefault(); int? importedMinistry = new GroupTypeService( lookupContext ).Queryable().Where( a => a.ForeignId == ministryIdString ).Select( a => a.Id ).FirstOrDefault(); //AttributeValue importedMinistry = new AttributeValueService(lookupContext).Queryable().Where(a => a.Value == Convert.ToString(ministryId) && a.ForeignId == ministryName).FirstOrDefault(); //AttributeValue importedMinistry = importedMinistriesAVList.Where(av => av.Value == Convert.ToString(ministryId)).FirstOrDefault(); // if (ministryId != null && !importedMinistries.ContainsKey(ministryId)) //Checks AttributeValue table to see if it has already been imported. //if ( ministryId != null && importedMinistriesAVList.Find( x => x.Value == Convert.ToString( ministryId ) ) == null ) //Checks AttributeValue table to see if it has already been imported. if ( ministryId != null && importedMinistry == 0 ) //Checks AttributeValue table to see if it has already been imported. { bool? ministryIsActive = row["Ministry_Active"] as bool?; if ( ministryName != null ) { var ministryCategory = new GroupType(); var ministryAttribute = new AttributeValue(); var ministryAttributeList = new List<AttributeValue>(); //Creates the GroupType data ministryCategory.IsSystem = false; ministryCategory.Name = ministryName.Trim(); ministryCategory.GroupTerm = "Group"; ministryCategory.GroupMemberTerm = "Member"; ministryCategory.AllowMultipleLocations = false; ministryCategory.ShowInGroupList = true; ministryCategory.ShowInNavigation = false; ministryCategory.TakesAttendance = false; ministryCategory.AttendanceRule = 0; ministryCategory.AttendancePrintTo = 0; ministryCategory.Order = order; ministryCategory.LocationSelectionMode = 0; ministryCategory.Guid = Guid.NewGuid(); ministryCategory.ForeignId = ministryIdString; //F1 Ministry ID ministryCategory.GroupTypePurposeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE ).Id; // ID = 142 in my db //Creates the AttributeValue data for the Ministry //ministryAttribute.IsSystem = false; //ministryAttribute.AttributeId = ministryAttributeId; //ministryAttribute.Value = ministryId.ToString(); //So the Value is the F1MinistryID //ministryAttribute.Guid = Guid.NewGuid(); //ministryAttribute.ForeignId = ministryName.Trim(); newCategories.Add( ministryCategory ); //ministryAttributeList.Add(ministryAttribute); //Saves it to the DB so that I can check for its ID in the table if ( newCategories.Any() || ministryAttributeList.Any() ) { //var rockContext = new RockContext(); if ( newCategories.Any() ) { //var rockContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.GroupTypes.AddRange( newCategories ); rockContext.SaveChanges( DisableAudit ); } ); newCategories.Clear(); order++; } //if ( ministryAttributeList.Any() ) //{ // //var rockContext = new RockContext(); // rockContext.WrapTransaction( () => // { // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.AttributeValues.AddRange( ministryAttributeList ); // rockContext.SaveChanges( DisableAudit ); // } ); // ministryAttributeList.Clear(); //} } } } //Checks AttributeValue table to see if it has already been imported. int? activityId = row["Activity_ID"] as int?; string activityName = row["Activity_Name"] as string; string activityIdString = Convert.ToString( activityId ); ReportProgress( 0, string.Format( "Ministry ID {0} Activity ID {1}.", ministryId, activityId ) ); //if (activityId != null && !importedActivities.ContainsKey(activityId)) int? importedActivity = new GroupTypeService( lookupContext ).Queryable().Where( a => a.ForeignId == activityIdString ).Select( a => a.Id ).FirstOrDefault(); //AttributeValue importedActivity = new AttributeValueService( lookupContext ).Queryable().Where( a => a.Value == Convert.ToString( activityId ) && a.ForeignId == activityName ).FirstOrDefault(); //AttributeValue importedActivity = importedActivitiesAVList.Where( av => av.Value == Convert.ToString( activityId ) ).FirstOrDefault(); //if ( activityId != null && importedActivitiesAVList.Find(x => x.Value == Convert.ToString(activityId)) == null ) if ( activityId != null && importedActivity == 0 ) { bool? activityIsActive = row["Activity_Active"] as bool?; //Looking up the Ministry GroupType ID so it can be used as the ParentGroupTypeId for the Activity GroupType/Area var gtService = new GroupTypeService( lookupContext ); int parentGroupTypeId; string ministryID = ministryId.ToString(); parentGroupTypeId = gtService.Queryable().Where( gt => gt.ForeignId == ministryID ).FirstOrDefault().Id; var parentGroupType = new GroupTypeService( rockContext ).Get( parentGroupTypeId ); var activityArea = new GroupType(); var activityAV = new AttributeValue(); var activityAVList = new List<AttributeValue>(); // create new GroupType for activity (will set this as child to Ministry/Category) activityArea.IsSystem = false; activityArea.Name = activityName.Trim(); activityArea.GroupTerm = "Group"; activityArea.GroupMemberTerm = "Member"; //Setup Group role Id var memberRole = new GroupTypeRole(); memberRole.Name = "Member"; memberRole.Description = "Member of Group Type: " + activityName.Trim(); activityArea.Roles.Add( memberRole ); //activityArea.DefaultGroupRoleId = activityArea.Roles.ElementAt(0).Id; activityArea.AllowMultipleLocations = true; activityArea.ShowInGroupList = true; activityArea.ShowInNavigation = false; activityArea.TakesAttendance = true; activityArea.AttendanceRule = 0; activityArea.AttendancePrintTo = 0; activityArea.Order = order; activityArea.LocationSelectionMode = 0; activityArea.Guid = Guid.NewGuid(); activityArea.ForeignId = activityIdString; //F1 Activity ID //Sets GroupTypeAssociation for the Categories and Areas activityArea.ParentGroupTypes = new List<GroupType>(); activityArea.ParentGroupTypes.Add( parentGroupType ); //Create Activity AttributeValue Data //activityAV.IsSystem = false; //activityAV.Guid = Guid.NewGuid(); //activityAV.AttributeId = activityAttributeId; //activityAV.Value = activityId.ToString(); //activityAV.ForeignId = activityName; //activityAVList.Add(activityAV); newAreas.Add( activityArea ); completed++; if ( newAreas.Any() || activityAVList.Any() ) { //var rockContext = new RockContext(); if ( newAreas.Any() ) { rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.GroupTypes.AddRange( newAreas ); rockContext.SaveChanges( DisableAudit ); } ); newAreas.Clear(); order++; } //if ( activityAVList.Any() ) //{ // //var rockContext = new RockContext(); // rockContext.WrapTransaction( () => // { // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.AttributeValues.AddRange( activityAVList ); // rockContext.SaveChanges( DisableAudit ); // } ); // activityAVList.Clear(); //} } } if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} ministries imported ({1}% complete). Categories: {2:N0} Areas: {3:N0}", completed, percentComplete, newCategories.Count, newAreas.Count ) ); } else if ( completed % ReportingNumber < 1 ) { //var rockContext = new RockContext(); //rockContext.WrapTransaction(() => //{ // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.GroupTypes.AddRange(newCategories); // rockContext.GroupTypes.AddRange(newAreas); // rockContext.SaveChanges(DisableAudit); //}); ReportPartialProgress(); } } //if (newAreas.Any()) //{ // //var rockContext = new RockContext(); // rockContext.WrapTransaction(() => // { // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.GroupTypes.AddRange(newAreas); // rockContext.SaveChanges(DisableAudit); // }); //} ReportProgress(100, string.Format("Finished ministry import: {0:N0} ministries imported. ", completed) ); //ReportProgress( 0, string.Format( "Categories: {0} Areas: {1}", importedMinistriesAVList.Count(), importedActivitiesAVList.Count() ) ); }
/// <summary> /// Loads the group type data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadGroupType(CSVInstance csvData) { // Required variables var lookupContext = new RockContext(); var newGroupTypeList = new List <GroupType>(); var purposeTypeValues = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.GROUPTYPE_PURPOSE), lookupContext).DefinedValues; var locationMeetingId = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION), lookupContext).Id; var numImportedGroupTypes = ImportedGroupTypes.Count(); var completed = 0; ReportProgress(0, $"Starting group type import ({numImportedGroupTypes:N0} already exist)."); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { var rowGroupTypeKey = row[GroupTypeId]; var groupTypeForeignId = rowGroupTypeKey.AsType <int?>(); // Check that this group type isn't already in our data var groupTypeExists = false; if (numImportedGroupTypes > 0) { groupTypeExists = ImportedGroupTypes.Any(t => t.ForeignKey == rowGroupTypeKey); } if (!groupTypeExists) { var rowGroupTypeName = row[GroupTypeName].Left(100); var newGroupType = new GroupType { // set required properties (terms set by default) IsSystem = false, Name = rowGroupTypeName, Order = 1000 + completed, // set optional properties CreatedDateTime = ParseDateOrDefault(row[GroupTypeCreatedDate], ImportDateTime), ModifiedDateTime = ImportDateTime, CreatedByPersonAliasId = ImportPersonAliasId, ModifiedByPersonAliasId = ImportPersonAliasId, ForeignKey = rowGroupTypeKey, ForeignId = groupTypeForeignId }; // set meeting location var definedValueService = new DefinedValueService(lookupContext); newGroupType.LocationTypes = new List <GroupTypeLocationType>(); newGroupType.LocationTypes.Clear(); var meetingLocationType = definedValueService.Get(locationMeetingId); if (meetingLocationType != null) { newGroupType.LocationTypes.Add(new GroupTypeLocationType { LocationTypeValueId = meetingLocationType.Id }); } // set provided optional properties newGroupType.TakesAttendance = ( bool )ParseBoolOrDefault(row[GroupTypeTakesAttendance], false); newGroupType.AttendanceCountsAsWeekendService = ( bool )ParseBoolOrDefault(row[GroupTypeWeekendService], false); newGroupType.ShowInGroupList = ( bool )ParseBoolOrDefault(row[GroupTypeShowInGroupList], false); newGroupType.ShowInNavigation = ( bool )ParseBoolOrDefault(row[GroupTypeShowInNav], false); // set schedule var allowGroupScheduleWeekly = ( bool )ParseBoolOrDefault(row[GroupTypeWeeklySchedule], false); if (allowGroupScheduleWeekly) { newGroupType.AllowedScheduleTypes = ScheduleType.Weekly; } var rowGroupTypePurpose = row[GroupTypePurpose]; if (!string.IsNullOrWhiteSpace(rowGroupTypePurpose)) { var purposeId = purposeTypeValues.Where(v => v.Value.Equals(rowGroupTypePurpose) || v.Id.Equals(rowGroupTypePurpose) || v.Guid.ToString().ToLower().Equals(rowGroupTypePurpose.ToLower())) .Select(v => ( int? )v.Id).FirstOrDefault(); newGroupType.GroupTypePurposeValueId = purposeId; } var inheritedGroupType = GroupTypeCache.Get(LoadGroupTypeId(lookupContext, row[GroupTypeInheritedGroupType])); if (inheritedGroupType.Id != GroupTypeCache.Get(new Guid("8400497B-C52F-40AE-A529-3FCCB9587101"), lookupContext).Id) { newGroupType.InheritedGroupTypeId = inheritedGroupType.Id; } // add default role of member var defaultRoleGuid = Guid.NewGuid(); var memberRole = new GroupTypeRole { Guid = defaultRoleGuid, Name = "Member" }; newGroupType.Roles.Add(memberRole); // save changes each loop newGroupTypeList.Add(newGroupType); lookupContext.WrapTransaction(() => { lookupContext.GroupTypes.AddRange(newGroupTypeList); lookupContext.SaveChanges(DisableAuditing); }); // Set Parent Group Type var rowGroupTypeParentId = row[GroupTypeParentId]; if (!string.IsNullOrWhiteSpace(rowGroupTypeParentId)) { var parentGroupType = ImportedGroupTypes.FirstOrDefault(t => t.ForeignKey.Equals(rowGroupTypeParentId)); var parentGroupTypeList = new List <GroupType>(); parentGroupTypeList.Add(parentGroupType); newGroupType.ParentGroupTypes = parentGroupTypeList; } // Set Self Reference bool selfRef; TryParseBool(row[GroupTypeSelfReference], out selfRef); if (selfRef) { var selfReferenceList = new List <GroupType>(); selfReferenceList.Add(newGroupType); newGroupType.ChildGroupTypes = selfReferenceList; } // set default role newGroupType.DefaultGroupRole = newGroupType.Roles.FirstOrDefault(); // save changes lookupContext.SaveChanges(); // add these new groups to the global list ImportedGroupTypes.AddRange(newGroupTypeList); newGroupTypeList.Clear(); // // Keep the user informed as to what is going on and save in batches. // completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, $"{completed:N0} groups imported."); } if (completed % ReportingNumber < 1) { ReportPartialProgress(); } } } ReportProgress(0, $"Finished group type import: {completed:N0} group types added or updated."); return(completed); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { RockContext rockContext = new RockContext(); Group group = null; Guid personGuid = Guid.Empty; GroupTypeRole groupMemberRole = null; // get group id from url if (Request["GroupId"] != null) { int groupId = 0; if (Int32.TryParse(Request["GroupId"], out groupId)) { group = new GroupService(rockContext).Queryable("GroupType,GroupType.Roles").Where(g => g.Id == groupId).FirstOrDefault(); } } else { Guid groupGuid = Guid.Empty; if (Guid.TryParse(GetAttributeValue("DefaultGroup"), out groupGuid)) { group = new GroupService(rockContext).Queryable("GroupType,GroupType.Roles").Where(g => g.Guid == groupGuid).FirstOrDefault();; } } if (group == null) { lAlerts.Text = "Could not determine the group to add to."; return; } // get group role id from url if (Request["GroupMemberRoleId"] != null) { int groupMemberRoleId = 0; if (Int32.TryParse(Request["GroupMemberRoleId"], out groupMemberRoleId)) { groupMemberRole = new GroupTypeRoleService(rockContext).Get(groupMemberRoleId); } } else { Guid groupMemberRoleGuid = Guid.Empty; if (Guid.TryParse(GetAttributeValue("DefaultGroupMemberRole"), out groupMemberRoleGuid)) { groupMemberRole = new GroupTypeRoleService(rockContext).Get(groupMemberRoleGuid); } } if (groupMemberRole == null) { lAlerts.Text += "Could not determine the group role to use for the add."; return; } // get person if (Request["PersonGuid"] != null) { Guid.TryParse(Request["PersonGuid"], out personGuid); } if (personGuid == Guid.Empty) { lAlerts.Text += "A valid person identifier was not found in the page address."; return; } // ensure that the group type has this role if (!group.GroupType.Roles.Contains(groupMemberRole)) { lAlerts.Text += "The group you have provided does not have the group member role configured."; return; } // get person Person person = new PersonService(rockContext).Get(personGuid); if (person == null) { lAlerts.Text += "A person could not be found for the identifier provided."; return; } // hide alert divAlert.Visible = false; // get status var groupMemberStatus = this.GetAttributeValue("GroupMemberStatus").ConvertToEnum <GroupMemberStatus>(GroupMemberStatus.Active); // load merge fields var mergeFields = new Dictionary <string, object>(); mergeFields.Add("GroupMemberStatus", groupMemberStatus.ToString()); mergeFields.Add("Group", group); mergeFields.Add("Person", person); mergeFields.Add("Role", groupMemberRole); mergeFields.Add("CurrentPerson", CurrentPerson); // show debug info? bool enableDebug = GetAttributeValue("EnableDebug").AsBoolean(); if (enableDebug && IsUserAuthorized(Authorization.EDIT)) { lDebug.Visible = true; lDebug.Text = mergeFields.lavaDebugInfo(); } // ensure that the person is not already in the group if (group.Members.Where(m => m.PersonId == person.Id && m.GroupRoleId == groupMemberRole.Id).Count() != 0) { string templateInGroup = GetAttributeValue("AlreadyInGroupMessage"); lContent.Text = templateInGroup.ResolveMergeFields(mergeFields); return; } // add person to group GroupMember groupMember = new GroupMember(); groupMember.GroupId = group.Id; groupMember.PersonId = person.Id; groupMember.GroupRoleId = groupMemberRole.Id; groupMember.GroupMemberStatus = groupMemberStatus; group.Members.Add(groupMember); try { rockContext.SaveChanges(); } catch (Exception ex) { divAlert.Visible = true; lAlerts.Text = String.Format("An error occurred adding {0} to the group {1}. Message: {2}.", person.FullName, group.Name, ex.Message); } string templateSuccess = GetAttributeValue("SuccessMessage"); lContent.Text = templateSuccess.ResolveMergeFields(mergeFields); } }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); RockContext rockContext = new RockContext(); // get person Person person = null; if (!string.IsNullOrWhiteSpace(Request["PersonGuid"])) { person = new PersonService(rockContext).Get(Request["PersonGuid"].AsGuid()); } if (person == null && CurrentPerson != null) { person = CurrentPerson; } if (person == null) { lAlerts.Text += "A person could not be found for the identifier provided."; return; } _person = person; bool ExpandDescriptionSetting = GetAttributeValue("ExpandDescription").AsBoolean(); if (!ExpandDescriptionSetting) { LiteralControl expandDescriptions = new LiteralControl("<script src='/Plugins/rocks_kfs/Groups/js/expandDescription.js'></script>"); this.Page.Header.Controls.Add(expandDescriptions); } if (!Page.IsPostBack) { Group group = null; Guid personGuid = Guid.Empty; GroupTypeRole groupMemberRole = null; // get group from url if (Request["GroupId"] != null || Request["GroupGuid"] != null) { if (Request["GroupId"] != null) { int groupId = 0; if (Int32.TryParse(Request["GroupId"], out groupId)) { group = new GroupService(rockContext).Queryable().Where(g => g.Id == groupId).FirstOrDefault(); } } else { Guid groupGuid = Request["GroupGuid"].AsGuid(); group = new GroupService(rockContext).Queryable().Where(g => g.Guid == groupGuid).FirstOrDefault(); } } else { Guid groupGuid = Guid.Empty; if (Guid.TryParse(GetAttributeValue("ParentGroup"), out groupGuid)) { group = new GroupService(rockContext).Queryable().Where(g => g.Guid == groupGuid).FirstOrDefault(); } } if (group == null) { lAlerts.Text = "Could not determine the group to add/remove from."; return; } _action = Request.QueryString["action"] != string.Empty && Request.QueryString["action"] != null ? Request.QueryString["action"] : string.Empty; // get status var groupMemberStatus = this.GetAttributeValue("GroupMemberStatus").ConvertToEnum <GroupMemberStatus>(GroupMemberStatus.Active); // load merge fields var mergeFields = new Dictionary <string, object>(); mergeFields.Add("Group", group); mergeFields.Add("Person", person); mergeFields.Add("CurrentPerson", CurrentPerson); mergeFields.Add("GroupMemberStatus", groupMemberStatus.ToString()); var groupMemberService = new GroupMemberService(rockContext); if (_action == "unsubscribe") { var groupMemberList = groupMemberService.Queryable() .Where(m => m.GroupId == group.Id && m.PersonId == person.Id) .ToList(); if (groupMemberList.Count > 0) { foreach (var groupMember in groupMemberList) { if (GetAttributeValue("Inactivate").AsBoolean()) { groupMember.GroupMemberStatus = GroupMemberStatus.Inactive; } else { groupMemberService.Delete(groupMember); } rockContext.SaveChanges(); } lContent.Text = GetAttributeValue("RemoveSuccessMessage").ResolveMergeFields(mergeFields); } else { if (GetAttributeValue("WarnWhenNotInGroup").AsBoolean()) { lContent.Text = GetAttributeValue("NotInGroupMessage").ResolveMergeFields(mergeFields); } else { lContent.Text = GetAttributeValue("RemoveSuccessMessage").ResolveMergeFields(mergeFields); } } } else if (_action == "subscribe") { // get group role id from url if (Request["GroupMemberRoleId"] != null) { int groupMemberRoleId = 0; if (Int32.TryParse(Request["GroupMemberRoleId"], out groupMemberRoleId)) { groupMemberRole = new GroupTypeRoleService(rockContext).Get(groupMemberRoleId); } } else { Guid groupMemberRoleGuid = Guid.Empty; if (Guid.TryParse(GetAttributeValue("DefaultGroupMemberRole"), out groupMemberRoleGuid)) { groupMemberRole = new GroupTypeRoleService(rockContext).Get(groupMemberRoleGuid); } if (groupMemberRole == null && group != null && group.GroupType.DefaultGroupRoleId.HasValue) { groupMemberRole = group.GroupType.DefaultGroupRole; } } if (groupMemberRole == null) { lAlerts.Text += "Could not determine the group role to use for the add."; return; } mergeFields.Add("Role", groupMemberRole); var groupMemberList = groupMemberService.Queryable() .Where(m => m.PersonId == person.Id && m.Group.Id == group.Id && m.GroupRoleId == groupMemberRole.Id) .ToList(); // ensure that the person is not already in the group if (groupMemberList.Count() != 0) { foreach (var groupMemberExisting in groupMemberList) { if (GetAttributeValue("Inactivate").AsBoolean()) { groupMemberExisting.GroupMemberStatus = groupMemberStatus; } else { string templateInGroup = GetAttributeValue("AlreadyInGroupMessage"); lContent.Text = templateInGroup.ResolveMergeFields(mergeFields); divAlert.Visible = false; return; } } } else { // add person to group GroupMember groupMember = new GroupMember(); groupMember.GroupId = group.Id; groupMember.PersonId = person.Id; groupMember.GroupRoleId = groupMemberRole.Id; groupMember.GroupMemberStatus = groupMemberStatus; group.Members.Add(groupMember); } try { rockContext.SaveChanges(); } catch (Exception ex) { divAlert.Visible = true; lAlerts.Text = String.Format("An error occurred adding {0} to the group {1}. Message: {2}.", person.FullName, group.Name, ex.Message); } string templateSuccess = GetAttributeValue("AddSuccessMessage"); lContent.Text = templateSuccess.ResolveMergeFields(mergeFields); } // hide alert divAlert.Visible = false; // show debug info? bool enableDebug = GetAttributeValue("EnableDebug").AsBoolean(); if (enableDebug && IsUserAuthorized(Authorization.EDIT)) { lDebug.Visible = true; lDebug.Text = mergeFields.lavaDebugInfo(); } } if (_action != "unsubscribe" && _action != "subscribe") { loadProfiles(); divActions.Visible = true; } }
protected void SaveSelections(Control c) { CheckBox cbox; int groupID; GroupTypeRole groupMemberRole = null; Guid personGuid = Guid.Empty; // // If the control is not a checkbox or radio button then // ignore it. // if (c.GetType() != typeof(CheckBox) && c.GetType() != typeof(RadioButton)) { return; } // // Pretend the control is a checkbox, if it is a radio button // it will cast fine since the radio button inherits from a // check box. // cbox = ( CheckBox )c; if (cbox.ID.Contains("_none")) { return; } groupID = 0; if (!Int32.TryParse(cbox.ID, out groupID)) { int stFrom = cbox.ID.IndexOf("profile_") + "profile_".Length; int stTo = cbox.ID.LastIndexOf("_field"); groupID = Int32.Parse(cbox.ID.Substring(stFrom, stTo - stFrom)); } RockContext rockContext = new RockContext(); GroupService groupService = new GroupService(rockContext); var groupMemberService = new GroupMemberService(rockContext); var groupMemberStatus = this.GetAttributeValue("GroupMemberStatus").ConvertToEnum <GroupMemberStatus>(GroupMemberStatus.Active); var qry = groupService .Queryable() .Where(g => g.Id == groupID); var group = qry.FirstOrDefault(); if (group != null) { // get person Person person = null; if (!string.IsNullOrWhiteSpace(Request["PersonGuid"])) { person = new PersonService(rockContext).Get(Request["PersonGuid"].AsGuid()); } if (person == null && CurrentPerson != null) { person = CurrentPerson; } if (person == null) { lAlerts.Text += "A person could not be found for the identifier provided."; } _person = person; var mergeFields = new Dictionary <string, object>(); mergeFields.Add("Group", group); mergeFields.Add("Person", person); mergeFields.Add("CurrentPerson", CurrentPerson); mergeFields.Add("GroupMemberStatus", groupMemberStatus.ToString()); if (cbox.Checked == true) { // get group role id from url Guid groupMemberRoleGuid = Guid.Empty; if (Guid.TryParse(GetAttributeValue("DefaultGroupMemberRole"), out groupMemberRoleGuid)) { groupMemberRole = new GroupTypeRoleService(rockContext).Get(groupMemberRoleGuid); } if (groupMemberRole == null && group != null && group.GroupType.DefaultGroupRoleId.HasValue) { groupMemberRole = group.GroupType.DefaultGroupRole; } if (groupMemberRole == null) { lAlerts.Text += "Could not determine the group role to use for the add."; } mergeFields.Add("Role", groupMemberRole); var groupMemberList = groupMemberService.Queryable() .Where(m => m.PersonId == person.Id && m.GroupId == group.Id && m.GroupRoleId == groupMemberRole.Id) .ToList(); // ensure that the person is not already in the group if (groupMemberList.Count() != 0) { foreach (var groupMemberExisting in groupMemberList) { if (GetAttributeValue("Inactivate").AsBoolean()) { groupMemberExisting.GroupMemberStatus = groupMemberStatus; } else { string templateInGroup = GetAttributeValue("AlreadyInGroupMessage"); lContent.Text += templateInGroup.ResolveMergeFields(mergeFields); divAlert.Visible = false; } } } else { // add person to group GroupMember groupMember = new GroupMember(); groupMember.GroupId = group.Id; groupMember.PersonId = person.Id; groupMember.GroupRoleId = groupMemberRole.Id; groupMember.GroupMemberStatus = groupMemberStatus; group.Members.Add(groupMember); } try { rockContext.SaveChanges(); } catch (Exception ex) { divAlert.Visible = true; lAlerts.Text += String.Format("An error occurred adding {0} to the group {1}. Message: {2}.", person.FullName, group.Name, ex.Message); } string templateSuccess = GetAttributeValue("AddSuccessMessage"); lContent.Text = templateSuccess.ResolveMergeFields(mergeFields); } if (!cbox.Checked) { var groupMemberList = groupMemberService.Queryable() .Where(m => m.GroupId == group.Id && m.PersonId == person.Id) .ToList(); if (groupMemberList.Count > 0) { foreach (var groupMember in groupMemberList) { if (GetAttributeValue("Inactivate").AsBoolean()) { groupMember.GroupMemberStatus = GroupMemberStatus.Inactive; } else { groupMemberService.Delete(groupMember); } rockContext.SaveChanges(); } lContent.Text = GetAttributeValue("RemoveSuccessMessage").ResolveMergeFields(mergeFields); } else { if (GetAttributeValue("WarnWhenNotInGroup").AsBoolean()) { lContent.Text = GetAttributeValue("NotInGroupMessage").ResolveMergeFields(mergeFields); } else { lContent.Text = GetAttributeValue("RemoveSuccessMessage").ResolveMergeFields(mergeFields); } } } } }
/// <summary> /// Gs the group attributes_ show edit. /// </summary> /// <param name="attributeGuid">The attribute GUID.</param> protected void gGroupTypeRoles_ShowEdit( Guid groupTypeRoleGuid ) { GroupTypeRole groupTypeRole = GroupTypeRolesState.FirstOrDefault( a => a.Guid.Equals( groupTypeRoleGuid ) ); if (groupTypeRole == null) { groupTypeRole = new GroupTypeRole(); dlgGroupTypeRoles.Title = "Add Role"; } else { dlgGroupTypeRoles.Title = "Edit Role"; } hfRoleGuid.Value = groupTypeRole.Guid.ToString(); tbRoleName.Text = groupTypeRole.Name; tbRoleDescription.Text = groupTypeRole.Description; string groupTerm = string.IsNullOrWhiteSpace( tbGroupTerm.Text ) ? "Group" : tbGroupTerm.Text; string memberTerm = string.IsNullOrWhiteSpace( tbGroupMemberTerm.Text ) ? "Member" : tbGroupMemberTerm.Text; cbIsLeader.Checked = groupTypeRole.IsLeader; cbCanView.Checked = groupTypeRole.CanView; cbCanEdit.Checked = groupTypeRole.CanEdit; nbMinimumRequired.Text = groupTypeRole.MinCount.HasValue ? groupTypeRole.MinCount.ToString() : string.Empty; nbMinimumRequired.Help = string.Format( "The minimum number of {0} in this {1} that are required to have this role.", memberTerm.Pluralize(), groupTerm ); nbMaximumAllowed.Text = groupTypeRole.MaxCount.HasValue ? groupTypeRole.MaxCount.ToString() : string.Empty; nbMaximumAllowed.Help = string.Format( "The maximum number of {0} in this {1} that are allowed to have this role.", memberTerm.Pluralize(), groupTerm ); ShowDialog( "GroupTypeRoles", true ); }
private void LoadSettings() { using (var context = new RockContext()) { GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(context); ScheduleService scheduleService = new ScheduleService(context); if (Settings.SignupPage() != null) { ppSignupPage.SetValue(Settings.SignupPage().Id); } // Load all the partition settings if (Settings.EntityGuid != Guid.Empty) { pnlPartitions.Visible = true; } rptPartions.DataSource = Settings.Partitions; rptPartions.DataBind(); // Remove all existing dynamic columns while (gCounts.Columns.Count > 1) { gCounts.Columns.RemoveAt(0); } DataTable dt = new DataTable(); dt.Columns.Add("RowId"); foreach (var partition in Settings.Partitions) { DataTable dtTmp = dt.Copy(); dt.Clear(); String column = partition.PartitionType; if (partition.PartitionType == "DefinedType") { var definedType = Rock.Web.Cache.DefinedTypeCache.Read(partition.PartitionValue.AsGuid()); if (definedType == null) { break; } column = definedType.Name; } var boundField = new BoundField() { HeaderText = column, DataField = column + partition.Guid }; gCounts.Columns.Insert(gCounts.Columns.Count - 1, boundField); dt.Columns.Add(column + partition.Guid); switch (partition.PartitionType) { case "DefinedType": var definedType = Rock.Web.Cache.DefinedTypeCache.Read(partition.PartitionValue.AsGuid()); foreach (var value in definedType.DefinedValues) { AddRowColumnPartition(dtTmp, dt, column + partition.Guid, value.Guid, value.Value); } break; case "Campus": if (partition.PartitionValue != null) { var selectedCampuses = partition.PartitionValue.Split(','); foreach (string campusGuid in selectedCampuses) { var campus = CampusCache.Read(campusGuid.AsGuid()); if (campus != null) { AddRowColumnPartition(dtTmp, dt, column + partition.Guid, campus.Guid, campus.Name); } } } break; case "Schedule": if (partition.PartitionValue != null) { var selectedSchedules = partition.PartitionValue.Split(','); foreach (string scheduleGuid in selectedSchedules) { var schedule = scheduleService.Get(scheduleGuid.AsGuid()); if (schedule != null) { AddRowColumnPartition(dtTmp, dt, column + partition.Guid, schedule.Guid, schedule.Name); } } } break; case "Role": if (partition.PartitionValue != null) { var selectedRoles = partition.PartitionValue.Split(','); List <GroupTypeRole> roles = new List <GroupTypeRole>(); foreach (string roleGuid in selectedRoles) { GroupTypeRole role = groupTypeRoleService.Get(roleGuid.AsGuid()); if (role != null) { roles.Add(role); } } roles.OrderBy(r => r.GroupTypeId).ThenBy(r => r.Order); foreach (GroupTypeRole role in roles) { AddRowColumnPartition(dtTmp, dt, column + partition.Guid, role.Guid, role.Name); } } break; } } if (Settings.Partitions.Count > 0 && dt.Rows.Count > 0) { var dv = dt.AsEnumerable(); var dvOrdered = dv.OrderBy(r => r.Field <String>(dt.Columns.Cast <DataColumn>().Select(c => c.ColumnName).Skip(1).FirstOrDefault())); foreach (var column in dt.Columns.Cast <DataColumn>().Select(c => c.ColumnName).Skip(2)) { dvOrdered = dvOrdered.ThenBy(r => r.Field <String>(column)); break; } dt = dvOrdered.CopyToDataTable(); gCounts.DataSource = dt; gCounts.DataBind(); } } }
/// <summary> /// Shows the edit. /// </summary> /// <param name="groupTypeId">The group type identifier.</param> public void ShowDetail( int groupTypeId ) { pnlDetails.Visible = false; GroupType groupType = null; if ( !groupTypeId.Equals( 0 ) ) { groupType = new GroupTypeService( new RockContext() ).Get( groupTypeId ); } if ( groupType == null ) { groupType = new GroupType { Id = 0, ShowInGroupList = true, GroupTerm = "Group", GroupMemberTerm = "Member" }; groupType.ChildGroupTypes = new List<GroupType>(); groupType.LocationTypes = new List<GroupTypeLocationType>(); Guid defaultRoleGuid = Guid.NewGuid(); var memberRole = new GroupTypeRole { Guid = defaultRoleGuid, Name = "Member" }; groupType.Roles.Add( memberRole ); groupType.DefaultGroupRole = memberRole; groupType.AllowedScheduleTypes = ScheduleType.None; groupType.LocationSelectionMode = GroupLocationPickerMode.None; } bool editAllowed = groupType.IsAuthorized( Authorization.EDIT, CurrentPerson ); DefaultRoleGuid = groupType.DefaultGroupRole != null ? groupType.DefaultGroupRole.Guid : Guid.Empty; pnlDetails.Visible = true; hfGroupTypeId.Value = groupType.Id.ToString(); bool readOnly = false; nbEditModeMessage.Text = string.Empty; if ( !editAllowed || !IsUserAuthorized( Authorization.EDIT ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( GroupType.FriendlyTypeName ); } if ( groupType.IsSystem ) { nbEditModeMessage.Text = EditModeMessage.System( GroupType.FriendlyTypeName ); } if ( readOnly ) { ShowReadonlyDetails( groupType ); } else { ShowEditDetails( groupType ); } }
/// <summary> /// Shows the edit. /// </summary> /// <param name="groupTypeId">The group type identifier.</param> public void ShowDetail( int groupTypeId ) { pnlDetails.Visible = false; // determine if indexing is enabled var groupEntityType = EntityTypeCache.Read( Rock.SystemGuid.EntityType.GROUP.AsGuid() ); cbEnableIndexing.Visible = (IndexContainer.IndexingEnabled && groupEntityType.IsIndexingEnabled); GroupType groupType = null; if ( !groupTypeId.Equals( 0 ) ) { groupType = new GroupTypeService( new RockContext() ).Get( groupTypeId ); pdAuditDetails.SetEntity( groupType, ResolveRockUrl( "~" ) ); } if ( groupType == null ) { groupType = new GroupType { Id = 0, ShowInGroupList = true, GroupTerm = "Group", GroupMemberTerm = "Member" }; groupType.ChildGroupTypes = new List<GroupType>(); groupType.LocationTypes = new List<GroupTypeLocationType>(); Guid defaultRoleGuid = Guid.NewGuid(); var memberRole = new GroupTypeRole { Guid = defaultRoleGuid, Name = "Member" }; groupType.Roles.Add( memberRole ); groupType.DefaultGroupRole = memberRole; groupType.AllowedScheduleTypes = ScheduleType.None; groupType.LocationSelectionMode = GroupLocationPickerMode.None; // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } bool editAllowed = groupType.IsAuthorized( Authorization.EDIT, CurrentPerson ); DefaultRoleGuid = groupType.DefaultGroupRole != null ? groupType.DefaultGroupRole.Guid : Guid.Empty; pnlDetails.Visible = true; hfGroupTypeId.Value = groupType.Id.ToString(); bool readOnly = false; nbEditModeMessage.Text = string.Empty; if ( !editAllowed || !IsUserAuthorized( Authorization.EDIT ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( GroupType.FriendlyTypeName ); } if ( groupType.IsSystem ) { nbEditModeMessage.Text = EditModeMessage.System( GroupType.FriendlyTypeName ); } if ( readOnly ) { ShowReadonlyDetails( groupType ); } else { ShowEditDetails( groupType ); } }
/// <summary> /// Maps the activity ministry. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapActivityMinistry(IQueryable <Row> tableData) { var lookupContext = new RockContext(); var rockContext = new RockContext(); // Add an Attribute for the unique F1 Ministry Id //int groupEntityTypeId = EntityTypeCache.Read("Rock.Model.Group").Id; //var ministryAttributeId = new AttributeService(lookupContext).Queryable().Where(a => a.EntityTypeId == groupEntityTypeId // && a.Key == "F1MinistryId").Select(a => a.Id).FirstOrDefault(); //var activityAttributeId = new AttributeService(lookupContext).Queryable().Where(a => a.EntityTypeId == groupEntityTypeId // && a.Key == "F1ActivityId").Select(a => a.Id).FirstOrDefault(); //if (ministryAttributeId == 0) //{ // var newMinistryAttribute = new Rock.Model.Attribute(); // newMinistryAttribute.Key = "F1MinistryId"; // newMinistryAttribute.Name = "F1 Ministry Id"; // newMinistryAttribute.FieldTypeId = IntegerFieldTypeId; // newMinistryAttribute.EntityTypeId = groupEntityTypeId; // newMinistryAttribute.EntityTypeQualifierValue = string.Empty; // newMinistryAttribute.EntityTypeQualifierColumn = string.Empty; // newMinistryAttribute.Description = "The FellowshipOne identifier for the ministry that was imported"; // newMinistryAttribute.DefaultValue = string.Empty; // newMinistryAttribute.IsMultiValue = false; // newMinistryAttribute.IsRequired = false; // newMinistryAttribute.Order = 0; // lookupContext.Attributes.Add(newMinistryAttribute); // lookupContext.SaveChanges(DisableAudit); // ministryAttributeId = newMinistryAttribute.Id; //} //if (activityAttributeId == 0) //{ // var newActivityAttribute = new Rock.Model.Attribute(); // newActivityAttribute.Key = "F1ActivityId"; // newActivityAttribute.Name = "F1 Activity Id"; // newActivityAttribute.FieldTypeId = IntegerFieldTypeId; // newActivityAttribute.EntityTypeId = groupEntityTypeId; // newActivityAttribute.EntityTypeQualifierValue = string.Empty; // newActivityAttribute.EntityTypeQualifierColumn = string.Empty; // newActivityAttribute.Description = "The FellowshipOne identifier for the activity that was imported"; // newActivityAttribute.DefaultValue = string.Empty; // newActivityAttribute.IsMultiValue = false; // newActivityAttribute.IsRequired = false; // newActivityAttribute.Order = 0; // lookupContext.Attributes.Add(newActivityAttribute); // lookupContext.SaveChanges(DisableAudit); // activityAttributeId = newActivityAttribute.Id; //} //// Get previously imported Ministries //List<AttributeValue> importedMinistriesAVList = new AttributeValueService(lookupContext).GetByAttributeId(ministryAttributeId).ToList(); //// Get previously imported Activities //List<AttributeValue> importedActivitiesAVList = new AttributeValueService( lookupContext ).GetByAttributeId( activityAttributeId ).ToList(); //int importedMinistriesCount = 0; //int importedActivitiesCount = 0; //if ( importedMinistriesAVList.Any() ) { importedMinistriesCount = importedMinistriesAVList.Count(); } //if ( importedActivitiesAVList.Any() ) { importedActivitiesCount = importedActivitiesAVList.Count(); } var orderMax = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Order != 0).ToList(); int order = orderMax.Max(o => o.Order) + 1; int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying ministry import ({0:N0} found).", totalRows)); //ReportProgress(0, string.Format("Previously Imported Ministries ({0:N0} found).", importedMinistriesCount)); //ReportProgress(0, string.Format("Previously Imported Activities ({0:N0} found).", importedActivitiesCount)); var newAreas = new List <GroupType>(); var newCategories = new List <GroupType>(); foreach (var row in tableData) { int? ministryId = row["Ministry_ID"] as int?; string ministryName = row["Ministry_Name"] as string; string ministryIdString = Convert.ToString(ministryId); //GroupType importedMinistriesGTList = new GroupTypeService( lookupContext ).Queryable().Where( g => g.Name == ministryName && g.ForeignId == ( Convert.ToString( ministryId ) + 'm' ) ).FirstOrDefault(); int?importedMinistry = new GroupTypeService(lookupContext).Queryable().Where(a => a.ForeignId == ministryIdString).Select(a => a.Id).FirstOrDefault(); //AttributeValue importedMinistry = new AttributeValueService(lookupContext).Queryable().Where(a => a.Value == Convert.ToString(ministryId) && a.ForeignId == ministryName).FirstOrDefault(); //AttributeValue importedMinistry = importedMinistriesAVList.Where(av => av.Value == Convert.ToString(ministryId)).FirstOrDefault(); // if (ministryId != null && !importedMinistries.ContainsKey(ministryId)) //Checks AttributeValue table to see if it has already been imported. //if ( ministryId != null && importedMinistriesAVList.Find( x => x.Value == Convert.ToString( ministryId ) ) == null ) //Checks AttributeValue table to see if it has already been imported. if (ministryId != null && importedMinistry == 0) //Checks AttributeValue table to see if it has already been imported. { bool?ministryIsActive = row["Ministry_Active"] as bool?; if (ministryName != null) { var ministryCategory = new GroupType(); var ministryAttribute = new AttributeValue(); var ministryAttributeList = new List <AttributeValue>(); //Creates the GroupType data ministryCategory.IsSystem = false; ministryCategory.Name = ministryName.Trim(); ministryCategory.GroupTerm = "Group"; ministryCategory.GroupMemberTerm = "Member"; ministryCategory.AllowMultipleLocations = false; ministryCategory.ShowInGroupList = true; ministryCategory.ShowInNavigation = false; ministryCategory.TakesAttendance = false; ministryCategory.AttendanceRule = 0; ministryCategory.AttendancePrintTo = 0; ministryCategory.Order = order; ministryCategory.LocationSelectionMode = 0; ministryCategory.Guid = Guid.NewGuid(); ministryCategory.ForeignId = ministryIdString; //F1 Ministry ID ministryCategory.GroupTypePurposeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE).Id; // ID = 142 in my db //Creates the AttributeValue data for the Ministry //ministryAttribute.IsSystem = false; //ministryAttribute.AttributeId = ministryAttributeId; //ministryAttribute.Value = ministryId.ToString(); //So the Value is the F1MinistryID //ministryAttribute.Guid = Guid.NewGuid(); //ministryAttribute.ForeignId = ministryName.Trim(); newCategories.Add(ministryCategory); //ministryAttributeList.Add(ministryAttribute); //Saves it to the DB so that I can check for its ID in the table if (newCategories.Any() || ministryAttributeList.Any()) { //var rockContext = new RockContext(); if (newCategories.Any()) { //var rockContext = new RockContext(); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.GroupTypes.AddRange(newCategories); rockContext.SaveChanges(DisableAudit); }); newCategories.Clear(); order++; } //if ( ministryAttributeList.Any() ) //{ // //var rockContext = new RockContext(); // rockContext.WrapTransaction( () => // { // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.AttributeValues.AddRange( ministryAttributeList ); // rockContext.SaveChanges( DisableAudit ); // } ); // ministryAttributeList.Clear(); //} } } } //Checks AttributeValue table to see if it has already been imported. int? activityId = row["Activity_ID"] as int?; string activityName = row["Activity_Name"] as string; string activityIdString = Convert.ToString(activityId); ReportProgress(0, string.Format("Ministry ID {0} Activity ID {1}.", ministryId, activityId)); //if (activityId != null && !importedActivities.ContainsKey(activityId)) int?importedActivity = new GroupTypeService(lookupContext).Queryable().Where(a => a.ForeignId == activityIdString).Select(a => a.Id).FirstOrDefault(); //AttributeValue importedActivity = new AttributeValueService( lookupContext ).Queryable().Where( a => a.Value == Convert.ToString( activityId ) && a.ForeignId == activityName ).FirstOrDefault(); //AttributeValue importedActivity = importedActivitiesAVList.Where( av => av.Value == Convert.ToString( activityId ) ).FirstOrDefault(); //if ( activityId != null && importedActivitiesAVList.Find(x => x.Value == Convert.ToString(activityId)) == null ) if (activityId != null && importedActivity == 0) { bool?activityIsActive = row["Activity_Active"] as bool?; //Looking up the Ministry GroupType ID so it can be used as the ParentGroupTypeId for the Activity GroupType/Area var gtService = new GroupTypeService(lookupContext); int parentGroupTypeId; string ministryID = ministryId.ToString(); parentGroupTypeId = gtService.Queryable().Where(gt => gt.ForeignId == ministryID).FirstOrDefault().Id; var parentGroupType = new GroupTypeService(rockContext).Get(parentGroupTypeId); var activityArea = new GroupType(); var activityAV = new AttributeValue(); var activityAVList = new List <AttributeValue>(); // create new GroupType for activity (will set this as child to Ministry/Category) activityArea.IsSystem = false; activityArea.Name = activityName.Trim(); activityArea.GroupTerm = "Group"; activityArea.GroupMemberTerm = "Member"; //Setup Group role Id var memberRole = new GroupTypeRole(); memberRole.Name = "Member"; memberRole.Description = "Member of Group Type: " + activityName.Trim(); activityArea.Roles.Add(memberRole); //activityArea.DefaultGroupRoleId = activityArea.Roles.ElementAt(0).Id; activityArea.AllowMultipleLocations = true; activityArea.ShowInGroupList = true; activityArea.ShowInNavigation = false; activityArea.TakesAttendance = true; activityArea.AttendanceRule = 0; activityArea.AttendancePrintTo = 0; activityArea.Order = order; activityArea.LocationSelectionMode = 0; activityArea.Guid = Guid.NewGuid(); activityArea.ForeignId = activityIdString; //F1 Activity ID //Sets GroupTypeAssociation for the Categories and Areas activityArea.ParentGroupTypes = new List <GroupType>(); activityArea.ParentGroupTypes.Add(parentGroupType); //Create Activity AttributeValue Data //activityAV.IsSystem = false; //activityAV.Guid = Guid.NewGuid(); //activityAV.AttributeId = activityAttributeId; //activityAV.Value = activityId.ToString(); //activityAV.ForeignId = activityName; //activityAVList.Add(activityAV); newAreas.Add(activityArea); completed++; if (newAreas.Any() || activityAVList.Any()) { //var rockContext = new RockContext(); if (newAreas.Any()) { rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.GroupTypes.AddRange(newAreas); rockContext.SaveChanges(DisableAudit); }); newAreas.Clear(); order++; } //if ( activityAVList.Any() ) //{ // //var rockContext = new RockContext(); // rockContext.WrapTransaction( () => // { // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.AttributeValues.AddRange( activityAVList ); // rockContext.SaveChanges( DisableAudit ); // } ); // activityAVList.Clear(); //} } } if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} ministries imported ({1}% complete). Categories: {2:N0} Areas: {3:N0}", completed, percentComplete, newCategories.Count, newAreas.Count)); } else if (completed % ReportingNumber < 1) { //var rockContext = new RockContext(); //rockContext.WrapTransaction(() => //{ // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.GroupTypes.AddRange(newCategories); // rockContext.GroupTypes.AddRange(newAreas); // rockContext.SaveChanges(DisableAudit); //}); ReportPartialProgress(); } } //if (newAreas.Any()) //{ // //var rockContext = new RockContext(); // rockContext.WrapTransaction(() => // { // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.GroupTypes.AddRange(newAreas); // rockContext.SaveChanges(DisableAudit); // }); //} ReportProgress(100, string.Format("Finished ministry import: {0:N0} ministries imported. ", completed)); //ReportProgress( 0, string.Format( "Categories: {0} Areas: {1}", importedMinistriesAVList.Count(), importedActivitiesAVList.Count() ) ); }
/// <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 ) { bool hasValidationErrors = false; var rockContext = new RockContext(); GroupTypeService groupTypeService = new GroupTypeService( rockContext ); GroupService groupService = new GroupService( rockContext ); AttributeService attributeService = new AttributeService( rockContext ); GroupLocationService groupLocationService = new GroupLocationService( rockContext ); int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt(); var groupTypeUIList = new List<GroupType>(); foreach ( var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType<CheckinGroupTypeEditor>().ToList() ) { var groupType = checkinGroupTypeEditor.GetCheckinGroupType( rockContext ); groupTypeUIList.Add( groupType ); } var groupTypeDBList = new List<GroupType>(); var groupTypesToDelete = new List<GroupType>(); var groupsToDelete = new List<Group>(); var groupTypesToAddUpdate = new List<GroupType>(); var groupsToAddUpdate = new List<Group>(); GroupType parentGroupTypeDB = groupTypeService.Get( parentGroupTypeId ); GroupType parentGroupTypeUI = parentGroupTypeDB.Clone( false ); parentGroupTypeUI.ChildGroupTypes = groupTypeUIList; PopulateDeleteLists( groupTypesToDelete, groupsToDelete, parentGroupTypeDB, parentGroupTypeUI ); PopulateAddUpdateLists( groupTypesToAddUpdate, groupsToAddUpdate, parentGroupTypeUI ); int binaryFileFieldTypeID = FieldTypeCache.Read( Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid() ).Id; rockContext.WrapTransaction( () => { // delete in reverse order to get deepest child items first groupsToDelete.Reverse(); foreach ( var groupToDelete in groupsToDelete ) { groupService.Delete( groupToDelete ); } // delete in reverse order to get deepest child items first groupTypesToDelete.Reverse(); foreach ( var groupTypeToDelete in groupTypesToDelete ) { groupTypeService.Delete( groupTypeToDelete ); } rockContext.SaveChanges(); // Add/Update grouptypes and groups that are in the UI // Note: We'll have to save all the groupTypes without changing the DB value of ChildGroupTypes, then come around again and save the ChildGroupTypes // since the ChildGroupTypes may not exist in the database yet foreach ( GroupType groupTypeUI in groupTypesToAddUpdate ) { GroupType groupTypeDB = groupTypeService.Get( groupTypeUI.Guid ); if ( groupTypeDB == null ) { groupTypeDB = new GroupType(); groupTypeDB.Id = 0; groupTypeDB.Guid = groupTypeUI.Guid; groupTypeDB.IsSystem = false; groupTypeDB.ShowInNavigation = false; groupTypeDB.ShowInGroupList = false; groupTypeDB.TakesAttendance = true; groupTypeDB.AttendanceRule = AttendanceRule.None; groupTypeDB.AttendancePrintTo = PrintTo.Default; groupTypeDB.AllowMultipleLocations = true; groupTypeDB.EnableLocationSchedules = true; GroupTypeRole defaultRole = new GroupTypeRole(); defaultRole.Name = "Member"; groupTypeDB.Roles.Add( defaultRole ); } groupTypeDB.Name = groupTypeUI.Name; groupTypeDB.Order = groupTypeUI.Order; groupTypeDB.InheritedGroupTypeId = groupTypeUI.InheritedGroupTypeId; groupTypeDB.Attributes = groupTypeUI.Attributes; groupTypeDB.AttributeValues = groupTypeUI.AttributeValues; if ( groupTypeDB.Id == 0 ) { groupTypeService.Add( groupTypeDB ); } if ( !groupTypeDB.IsValid ) { hasValidationErrors = true; CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>().First( a => a.GroupTypeGuid == groupTypeDB.Guid ); groupTypeEditor.Expanded = true; return; } rockContext.SaveChanges(); groupTypeDB.SaveAttributeValues( rockContext ); // get fresh from database to make sure we have Id so we can update the CheckinLabel Attributes groupTypeDB = groupTypeService.Get( groupTypeDB.Guid ); // rebuild the CheckinLabel attributes from the UI (brute-force) foreach ( var labelAttributeDB in CheckinGroupTypeEditor.GetCheckinLabelAttributes( groupTypeDB.Attributes, rockContext ) ) { var attribute = attributeService.Get( labelAttributeDB.Value.Guid ); Rock.Web.Cache.AttributeCache.Flush( attribute.Id ); attributeService.Delete( attribute ); } // Make sure default role is set if ( !groupTypeDB.DefaultGroupRoleId.HasValue && groupTypeDB.Roles.Any() ) { groupTypeDB.DefaultGroupRoleId = groupTypeDB.Roles.First().Id; } rockContext.SaveChanges(); int labelOrder = 0; foreach ( var checkinLabelAttributeInfo in GroupTypeCheckinLabelAttributesState[groupTypeUI.Guid] ) { var attribute = new Rock.Model.Attribute(); attribute.AttributeQualifiers.Add( new AttributeQualifier { Key = "binaryFileType", Value = Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL } ); attribute.Guid = Guid.NewGuid(); attribute.FieldTypeId = binaryFileFieldTypeID; attribute.EntityTypeId = EntityTypeCache.GetId( typeof( GroupType ) ); attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = groupTypeDB.Id.ToString(); attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileGuid.ToString(); attribute.Key = checkinLabelAttributeInfo.AttributeKey; attribute.Name = checkinLabelAttributeInfo.FileName; attribute.Order = labelOrder++; if ( !attribute.IsValid ) { hasValidationErrors = true; CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>().First( a => a.GroupTypeGuid == groupTypeDB.Guid ); groupTypeEditor.Expanded = true; return; } attributeService.Add( attribute ); } rockContext.SaveChanges(); } // Add/Update Groups foreach ( var groupUI in groupsToAddUpdate ) { Group groupDB = groupService.Get( groupUI.Guid ); if ( groupDB == null ) { groupDB = new Group(); groupDB.Guid = groupUI.Guid; } groupDB.Name = groupUI.Name; // delete any GroupLocations that were removed in the UI foreach ( var groupLocationDB in groupDB.GroupLocations.ToList() ) { if ( !groupUI.GroupLocations.Select( a => a.LocationId ).Contains( groupLocationDB.LocationId ) ) { groupLocationService.Delete( groupLocationDB ); } } // add any GroupLocations that were added in the UI foreach ( var groupLocationUI in groupUI.GroupLocations ) { if ( !groupDB.GroupLocations.Select( a => a.LocationId ).Contains( groupLocationUI.LocationId ) ) { GroupLocation groupLocationDB = new GroupLocation { LocationId = groupLocationUI.LocationId }; groupDB.GroupLocations.Add( groupLocationDB ); } } groupDB.Order = groupUI.Order; // get GroupTypeId from database in case the groupType is new groupDB.GroupTypeId = groupTypeService.Get( groupUI.GroupType.Guid ).Id; var parentGroupUI = groupsToAddUpdate.Where( g => g.Groups.Any( g2 => g2.Guid.Equals( groupUI.Guid ) ) ).FirstOrDefault(); if ( parentGroupUI != null ) { groupDB.ParentGroupId = groupService.Get( parentGroupUI.Guid ).Id; } groupDB.Attributes = groupUI.Attributes; groupDB.AttributeValues = groupUI.AttributeValues; if ( groupDB.Id == 0 ) { groupService.Add( groupDB ); } if ( !groupDB.IsValid ) { hasValidationErrors = true; hasValidationErrors = true; CheckinGroupEditor groupEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupEditor>().First( a => a.GroupGuid == groupDB.Guid ); groupEditor.Expanded = true; return; } rockContext.SaveChanges(); groupDB.SaveAttributeValues(); } /* now that we have all the grouptypes saved, now lets go back and save them again with the current UI ChildGroupTypes */ // save main parentGroupType with current UI ChildGroupTypes parentGroupTypeDB.ChildGroupTypes = new List<GroupType>(); parentGroupTypeDB.ChildGroupTypes.Clear(); foreach ( var childGroupTypeUI in parentGroupTypeUI.ChildGroupTypes ) { var childGroupTypeDB = groupTypeService.Get( childGroupTypeUI.Guid ); parentGroupTypeDB.ChildGroupTypes.Add( childGroupTypeDB ); } rockContext.SaveChanges(); // loop thru all the other GroupTypes in the UI and save their childgrouptypes foreach ( var groupTypeUI in groupTypesToAddUpdate ) { var groupTypeDB = groupTypeService.Get( groupTypeUI.Guid ); groupTypeDB.ChildGroupTypes = new List<GroupType>(); groupTypeDB.ChildGroupTypes.Clear(); groupTypeDB.ChildGroupTypes.Add( groupTypeDB ); foreach ( var childGroupTypeUI in groupTypeUI.ChildGroupTypes ) { var childGroupTypeDB = groupTypeService.Get( childGroupTypeUI.Guid ); groupTypeDB.ChildGroupTypes.Add( childGroupTypeDB ); } } rockContext.SaveChanges(); AttributeCache.FlushEntityAttributes(); } ); if ( !hasValidationErrors ) { NavigateToParentPage(); } }