/// <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 ) { Group group; GroupService groupService = new GroupService(); int groupId = int.Parse( hfGroupId.Value ); if ( groupId == 0 ) { group = new Group(); group.IsSystem = false; groupService.Add( group, CurrentPersonId ); } else { // just in case this group is or was a SecurityRole Rock.Security.Role.Flush( groupId ); group = groupService.Get( groupId ); } group.Name = tbName.Text; group.Description = tbDescription.Text; group.CampusId = ddlCampus.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( ddlCampus.SelectedValue ); group.GroupTypeId = int.Parse( ddlGroupType.SelectedValue ); group.ParentGroupId = ddlParentGroup.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( ddlParentGroup.SelectedValue ); group.IsSecurityRole = cbIsSecurityRole.Checked; // check for duplicates within GroupType if ( groupService.Queryable().Where( g => g.GroupTypeId.Equals( group.GroupTypeId ) ).Count( a => a.Name.Equals( group.Name, StringComparison.OrdinalIgnoreCase ) && !a.Id.Equals( group.Id ) ) > 0 ) { tbName.ShowErrorMessage( WarningMessage.DuplicateFoundMessage( "name", Group.FriendlyTypeName ) ); return; } if ( !group.IsValid ) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction( () => { groupService.Save( group, CurrentPersonId ); } ); // just in case this group is or was a SecurityRole Rock.Security.Authorization.Flush(); NavigateToParentPage(); }
protected void btnSave_Click(object sender, EventArgs e) { if (lopAddress.Location == null || string.IsNullOrWhiteSpace(lopAddress.Location.Street1) || string.IsNullOrWhiteSpace(lopAddress.Location.PostalCode)) { nbValidation.Visible = true; ScriptManager.RegisterStartupScript(Page, this.GetType(), "ScrollPage", "setTimeout(function(){window.scroll(0,0);},200)", true); return; } else { nbValidation.Visible = false; } if (_group == null) { ShowMessage("There was an issue with the viewstate. Please reload and try again. If the problem perssits contact an administrator.", "Error", "panel panel-danger"); return; } GroupService groupService = new GroupService(_rockContext); //Add basic information Group group; if (_group.Id == 0) { group = new Group() { GroupTypeId = _groupType.Id }; var destinationGroup = groupService.Get(GetAttributeValue("DestinationGroup").AsGuid()); if (destinationGroup != null) { group.ParentGroupId = destinationGroup.Id; } var parentMapping = GetAttributeValue("CampusGroupMap").ToKeyValuePairList(); foreach (var pair in parentMapping) { if (pair.Key.AsInteger() == cpCampus.SelectedValueAsId()) { group.ParentGroupId = (( string )pair.Value).AsInteger(); } } var zip = "No Zip"; if (lopAddress.Location != null && !string.IsNullOrWhiteSpace(lopAddress.Location.PostalCode)) { zip = lopAddress.Location.PostalCode; } group.Name = string.Format("{0} - {1}", tbName.Text, zip); groupService.Add(group); group.CreatedByPersonAliasId = _person.PrimaryAliasId; group.IsActive = true; } else { group = groupService.Get(_group.Id); group.IsActive = true; } group.CampusId = cpCampus.SelectedValueAsId(); group.Description = tbDescription.Text; //Set location if (lopAddress.Location != null && lopAddress.Location.Id != 0) { if (group.GroupLocations != null && !group.GroupLocations.Select(gl => gl.LocationId).Contains(lopAddress.Location.Id)) { // Disassociate the old address(es) GroupLocationService groupLocationService = new GroupLocationService(_rockContext); var meetingLocationDv = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION); var homeLocationDv = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME); groupLocationService.DeleteRange(group.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == meetingLocationDv.Id || gl.GroupLocationTypeValueId == homeLocationDv.Id || gl.GroupLocationTypeValueId == null)); group.GroupLocations.Add(new GroupLocation() { LocationId = lopAddress.Location.Id, GroupLocationTypeValueId = meetingLocationDv.Id }); } } //Set Schedule if (_groupType.AllowedScheduleTypes != ScheduleType.None) { switch (rblSchedule.SelectedValueAsEnum <ScheduleType>()) { case ScheduleType.None: group.ScheduleId = null; break; case ScheduleType.Weekly: var weeklySchedule = new Schedule() { WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek, WeeklyTimeOfDay = timeWeekly.SelectedTime }; group.Schedule = weeklySchedule; break; case ScheduleType.Custom: var customSchedule = new Schedule() { iCalendarContent = sbSchedule.iCalendarContent }; group.Schedule = customSchedule; break; case ScheduleType.Named: if (spSchedule.SelectedValue.AsInteger() != 0) { group.ScheduleId = spSchedule.SelectedValue.AsInteger(); } break; default: break; } } if (group.Members != null && group.Members.Any()) { foreach (var member in group.Members.Where(gm => gm.PersonId != _person.Id)) { member.GroupMemberStatus = GroupMemberStatus.Inactive; } foreach (int groupMemberId in gMembers.SelectedKeys) { var groupMember = group.Members.Where(m => m.Id == groupMemberId).FirstOrDefault(); if (groupMember != null) { groupMember.GroupMemberStatus = GroupMemberStatus.Active; } } } else { var groupRoleId = new GroupTypeRoleService(_rockContext).Get(GetAttributeValue("GroupRole").AsGuid()).Id; group.Members.Add(new GroupMember() { PersonId = _person.Id, GroupRoleId = groupRoleId }); } //Save attributes _rockContext.SaveChanges(); group.LoadAttributes(); Rock.Attribute.Helper.GetEditValues(phAttributes, group); var attributeGuid = GetAttributeValue("MultiSelectAttribute"); var multiselectAttribute = new AttributeService(_rockContext).Get(attributeGuid.AsGuid()); if (multiselectAttribute != null) { var attributeValue = group.GetAttributeValue(multiselectAttribute.Key) .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .ToList(); var newAttributeText = GetAttributeValue("AttributeText"); if (!attributeValue.Contains(newAttributeText)) { attributeValue.Add(newAttributeText); } group.SetAttributeValue(multiselectAttribute.Key, string.Join(",", attributeValue)); } group.SaveAttributeValues(); //Update cache var availableGroupIds = (List <int>)GetCacheItem(GetAttributeValue("DestinationGroup")); if (availableGroupIds != null) { availableGroupIds.Add(group.Id); AddCacheItem(GetAttributeValue("DestinationGroup"), availableGroupIds); } var workflowTypeService = new WorkflowTypeService(_rockContext); WorkflowType workflowType = null; Guid? workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull(); if (workflowTypeGuid.HasValue) { workflowType = workflowTypeService.Get(workflowTypeGuid.Value); } GroupMember currentGroupMember = group.Members.Where(gm => gm.PersonId == _person.Id).FirstOrDefault(); if (currentGroupMember != null && workflowType != null && (workflowType.IsActive ?? true)) { try { List <string> workflowErrors; var workflow = Workflow.Activate(workflowType, _person.FullName); if (workflow.AttributeValues.ContainsKey("Group")) { if (group != null) { workflow.AttributeValues["Group"].Value = group.Guid.ToString(); } } if (workflow.AttributeValues.ContainsKey("Person")) { if (_person != null) { workflow.AttributeValues["Person"].Value = _person.PrimaryAlias.Guid.ToString(); } } new WorkflowService(_rockContext).Process(workflow, currentGroupMember, out workflowErrors); } catch (Exception ex) { ExceptionLogService.LogException(ex, this.Context); } } ShowMessage(GetAttributeValue("SuccessText"), "Thank you!", "panel panel-success"); }
/// <summary> /// Saves the family and persons to the database /// </summary> /// <param name="kioskCampusId">The kiosk campus identifier.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public SaveResult SaveFamilyAndPersonsToDatabase(int?kioskCampusId, RockContext rockContext) { SaveResult saveResult = new SaveResult(); FamilyRegistrationState editFamilyState = this; var personService = new PersonService(rockContext); var groupService = new GroupService(rockContext); var recordTypePersonId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; var maritalStatusMarried = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid()); var maritalStatusSingle = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_SINGLE.AsGuid()); var numberTypeValueMobile = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()); int groupTypeRoleAdultId = GroupTypeCache.GetFamilyGroupType().Roles.FirstOrDefault(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id; int groupTypeRoleChildId = GroupTypeCache.GetFamilyGroupType().Roles.FirstOrDefault(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id; int?groupTypeRoleCanCheckInId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid()) ?.Roles.FirstOrDefault(r => r.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_CAN_CHECK_IN.AsGuid())?.Id; bool?groupTypeDefaultSmsEnabled = GroupTypeCache.GetFamilyGroupType().GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTSMSENABLED).AsBooleanOrNull(); Group primaryFamily = null; if (editFamilyState.GroupId.HasValue) { primaryFamily = groupService.Get(editFamilyState.GroupId.Value); } // see if we can find matches for new people that were added, and also set the primary family if this is a new family, but a matching family was found foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.PersonId.HasValue && !a.IsDeleted)) { var personQuery = new PersonService.PersonMatchQuery(familyPersonState.FirstName, familyPersonState.LastName, familyPersonState.Email, familyPersonState.MobilePhoneNumber, familyPersonState.Gender, familyPersonState.BirthDate, familyPersonState.SuffixValueId); var matchingPerson = personService.FindPerson(personQuery, true); if (matchingPerson != null) { // newly added person, but a match was found, so set the PersonId, GroupId, and ConnectionStatusValueID to the matching person instead of creating a new person familyPersonState.PersonId = matchingPerson.Id; familyPersonState.GroupId = matchingPerson.GetFamily(rockContext)?.Id; familyPersonState.RecordStatusValueId = matchingPerson.RecordStatusValueId; familyPersonState.ConnectionStatusValueId = matchingPerson.ConnectionStatusValueId; familyPersonState.ConvertedToMatchedPerson = true; if (primaryFamily == null && familyPersonState.IsAdult) { // if this is a new family, but we found a matching adult person, use that person's family as the family primaryFamily = matchingPerson.GetFamily(rockContext); } } } // loop thru all people and add/update as needed foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted)) { Person person; if (!familyPersonState.PersonId.HasValue) { person = new Person(); personService.Add(person); saveResult.NewPersonList.Add(person); person.RecordTypeValueId = recordTypePersonId; person.FirstName = familyPersonState.FirstName; } else { person = personService.Get(familyPersonState.PersonId.Value); } // NOTE, Gender, MaritalStatusValueId, NickName, LastName are required fields so, always updated them to match the UI (even if a matched person was found) person.Gender = familyPersonState.Gender; person.MaritalStatusValueId = familyPersonState.IsMarried ? maritalStatusMarried.Id : maritalStatusSingle.Id; person.NickName = familyPersonState.FirstName; person.LastName = familyPersonState.LastName; // if the familyPersonState was converted to a Matched Person, don't overwrite existing values with blank values var saveEmptyValues = !familyPersonState.ConvertedToMatchedPerson; if (familyPersonState.SuffixValueId.HasValue || saveEmptyValues) { person.SuffixValueId = familyPersonState.SuffixValueId; } if (familyPersonState.BirthDate.HasValue || saveEmptyValues) { person.SetBirthDate(familyPersonState.BirthDate); } if (familyPersonState.Email.IsNotNullOrWhiteSpace() || saveEmptyValues) { person.Email = familyPersonState.Email; } if (familyPersonState.GradeOffset.HasValue || saveEmptyValues) { person.GradeOffset = familyPersonState.GradeOffset; } // if a matching person was found, the familyPersonState's RecordStatusValueId and ConnectinoStatusValueId was already updated to match the matched person person.RecordStatusValueId = familyPersonState.RecordStatusValueId; person.ConnectionStatusValueId = familyPersonState.ConnectionStatusValueId; rockContext.SaveChanges(); bool isNewPerson = !familyPersonState.PersonId.HasValue; if (!familyPersonState.PersonId.HasValue) { // if we added a new person, we know now the personId after SaveChanges, so set it familyPersonState.PersonId = person.Id; } if (familyPersonState.AlternateID.IsNotNullOrWhiteSpace()) { PersonSearchKey personAlternateValueIdSearchKey; PersonSearchKeyService personSearchKeyService = new PersonSearchKeyService(rockContext); if (isNewPerson) { // if we added a new person, a default AlternateId was probably added in the service layer. If a specific Alternate ID was specified, make sure that their SearchKey is updated personAlternateValueIdSearchKey = person.GetPersonSearchKeys(rockContext).Where(a => a.SearchTypeValueId == _personSearchAlternateValueId).FirstOrDefault(); } else { // see if the key already exists. If if it doesn't already exist, let a new one get created personAlternateValueIdSearchKey = person.GetPersonSearchKeys(rockContext).Where(a => a.SearchTypeValueId == _personSearchAlternateValueId && a.SearchValue == familyPersonState.AlternateID).FirstOrDefault(); } if (personAlternateValueIdSearchKey == null) { personAlternateValueIdSearchKey = new PersonSearchKey(); personAlternateValueIdSearchKey.PersonAliasId = person.PrimaryAliasId; personAlternateValueIdSearchKey.SearchTypeValueId = _personSearchAlternateValueId; personSearchKeyService.Add(personAlternateValueIdSearchKey); } if (personAlternateValueIdSearchKey.SearchValue != familyPersonState.AlternateID) { personAlternateValueIdSearchKey.SearchValue = familyPersonState.AlternateID; rockContext.SaveChanges(); } } person.LoadAttributes(); foreach (var attributeValue in familyPersonState.PersonAttributeValuesState) { // only set attribute values that are editable so we don't accidently delete any attribute values if (familyPersonState.EditableAttributes.Contains(attributeValue.Value.AttributeId)) { if (attributeValue.Value.Value.IsNotNullOrWhiteSpace() || saveEmptyValues) { person.SetAttributeValue(attributeValue.Key, attributeValue.Value.Value); } } } person.SaveAttributeValues(rockContext); if (familyPersonState.MobilePhoneNumber.IsNotNullOrWhiteSpace() || saveEmptyValues) { person.UpdatePhoneNumber(numberTypeValueMobile.Id, familyPersonState.MobilePhoneCountryCode, familyPersonState.MobilePhoneNumber, familyPersonState.MobilePhoneSmsEnabled ?? groupTypeDefaultSmsEnabled, false, rockContext); } rockContext.SaveChanges(); } if (primaryFamily == null) { // new family and no family found by looking up matching adults, so create a new family primaryFamily = new Group(); var familyLastName = editFamilyState.FamilyPersonListState.OrderBy(a => a.IsAdult).Where(a => !a.IsDeleted).Select(a => a.LastName).FirstOrDefault(); primaryFamily.Name = familyLastName + " Family"; primaryFamily.GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; // Set the Campus to the Campus of this Kiosk primaryFamily.CampusId = kioskCampusId; groupService.Add(primaryFamily); saveResult.NewFamilyList.Add(primaryFamily); rockContext.SaveChanges(); } if (!editFamilyState.GroupId.HasValue) { editFamilyState.GroupId = primaryFamily.Id; } primaryFamily.LoadAttributes(); foreach (var familyAttribute in editFamilyState.FamilyAttributeValuesState) { // only set attribute values that are editable so we don't accidently delete any attribute values if (editFamilyState.EditableFamilyAttributes.Contains(familyAttribute.Value.AttributeId)) { primaryFamily.SetAttributeValue(familyAttribute.Key, familyAttribute.Value.Value); } } primaryFamily.SaveAttributeValues(rockContext); var groupMemberService = new GroupMemberService(rockContext); // loop thru all people that are part of the same family (in the UI) and ensure they are all in the same primary family (in the database) foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted && a.InPrimaryFamily)) { var currentFamilyMember = primaryFamily.Members.FirstOrDefault(m => m.PersonId == familyPersonState.PersonId.Value); if (currentFamilyMember == null) { currentFamilyMember = new GroupMember { GroupId = primaryFamily.Id, PersonId = familyPersonState.PersonId.Value, GroupMemberStatus = GroupMemberStatus.Active }; if (familyPersonState.IsAdult) { currentFamilyMember.GroupRoleId = groupTypeRoleAdultId; } else { currentFamilyMember.GroupRoleId = groupTypeRoleChildId; } groupMemberService.Add(currentFamilyMember); rockContext.SaveChanges(); } } // make a dictionary of new related families (by lastname) so we can combine any new related children into a family with the same last name Dictionary <string, Group> newRelatedFamilies = new Dictionary <string, Group>(StringComparer.OrdinalIgnoreCase); // loop thru all people that are NOT part of the same family foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted && a.InPrimaryFamily == false)) { if (!familyPersonState.GroupId.HasValue) { // related person not in a family yet Group relatedFamily = newRelatedFamilies.GetValueOrNull(familyPersonState.LastName); if (relatedFamily == null) { relatedFamily = new Group(); relatedFamily.Name = familyPersonState.LastName + " Family"; relatedFamily.GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; // Set the Campus to the Campus of this Kiosk relatedFamily.CampusId = kioskCampusId; newRelatedFamilies.Add(familyPersonState.LastName, relatedFamily); groupService.Add(relatedFamily); saveResult.NewFamilyList.Add(relatedFamily); } rockContext.SaveChanges(); familyPersonState.GroupId = relatedFamily.Id; var familyMember = new GroupMember { GroupId = relatedFamily.Id, PersonId = familyPersonState.PersonId.Value, GroupMemberStatus = GroupMemberStatus.Active }; if (familyPersonState.IsAdult) { familyMember.GroupRoleId = groupTypeRoleAdultId; } else { familyMember.GroupRoleId = groupTypeRoleChildId; } groupMemberService.Add(familyMember); } // ensure there are known relationships between each adult in the primary family to this person that isn't in the primary family foreach (var primaryFamilyAdult in editFamilyState.FamilyPersonListState.Where(a => a.IsAdult && a.InPrimaryFamily)) { groupMemberService.CreateKnownRelationship(primaryFamilyAdult.PersonId.Value, familyPersonState.PersonId.Value, familyPersonState.ChildRelationshipToAdult); // if this is something other than the CanCheckIn relationship, but is a relationship that should ensure a CanCheckIn relationship, create a CanCheckinRelationship if (groupTypeRoleCanCheckInId.HasValue && familyPersonState.CanCheckIn && groupTypeRoleCanCheckInId != familyPersonState.ChildRelationshipToAdult) { groupMemberService.CreateKnownRelationship(primaryFamilyAdult.PersonId.Value, familyPersonState.PersonId.Value, groupTypeRoleCanCheckInId.Value); } } } return(saveResult); }
private Group SaveNewPerson(Rock.Model.Person person, Group existingFamily, int?defaultCampus, RockContext rockContext) { if (existingFamily == null) { return(PersonService.SaveNewPerson(person, rockContext, (defaultCampus != null ? defaultCampus : ( int? )null), false)); } else { person.FirstName = person.FirstName.FixCase(); person.NickName = person.NickName.FixCase(); person.MiddleName = person.MiddleName.FixCase(); person.LastName = person.LastName.FixCase(); // Create/Save Known Relationship Group var knownRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS); if (knownRelationshipGroupType != null) { var ownerRole = knownRelationshipGroupType.Roles .FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid())); if (ownerRole != null) { var groupMember = new GroupMember(); groupMember.Person = person; groupMember.GroupRoleId = ownerRole.Id; var group = new Group(); group.Name = knownRelationshipGroupType.Name; group.GroupTypeId = knownRelationshipGroupType.Id; group.Members.Add(groupMember); var groupService = new GroupService(rockContext); groupService.Add(group); } } // Create/Save Implied Relationship Group var impliedRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK); if (impliedRelationshipGroupType != null) { var ownerRole = impliedRelationshipGroupType.Roles .FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid())); if (ownerRole != null) { var groupMember = new GroupMember(); groupMember.Person = person; groupMember.GroupRoleId = ownerRole.Id; var group = new Group(); group.Name = impliedRelationshipGroupType.Name; group.GroupTypeId = impliedRelationshipGroupType.Id; group.Members.Add(groupMember); var groupService = new GroupService(rockContext); groupService.Add(group); } } var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY); var adultRole = familyGroupType?.Roles .FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())); var childRole = familyGroupType?.Roles .FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid())); var age = person.Age; var familyRole = age.HasValue && age < 18 ? childRole : adultRole; // Add to the existing family PersonService.AddPersonToFamily(person, true, existingFamily.Id, familyRole.Id, rockContext); return(existingFamily); } }
public void GroupAdd() { groups.Add(121); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { // confirmation was disabled by btnSave on client-side. So if returning without a redirect, // it should be enabled. If returning with a redirect, the control won't be updated to reflect // confirmation being enabled, so it's ok to enable it here confirmExit.Enabled = true; if (Page.IsValid) { confirmExit.Enabled = true; using (new UnitOfWorkScope()) { var familyService = new GroupService(); var familyMemberService = new GroupMemberService(); var personService = new PersonService(); // SAVE FAMILY _family = familyService.Get(_family.Id); _family.Name = tbFamilyName.Text; _family.CampusId = cpCampus.SelectedValueAsInt(); var familyGroupTypeId = _family.GroupTypeId; familyService.Save(_family, CurrentPersonId); // SAVE FAMILY MEMBERS int?recordStatusValueID = ddlRecordStatus.SelectedValueAsInt(); int?reasonValueId = ddlReason.SelectedValueAsInt(); var newFamilies = new List <Group>(); foreach (var familyMember in FamilyMembers) { var role = familyRoles.Where(r => r.Guid.Equals(familyMember.RoleGuid)).FirstOrDefault(); if (role == null) { role = familyRoles.FirstOrDefault(); } // People added to family (new or from other family) if (!familyMember.ExistingFamilyMember) { var groupMember = new GroupMember(); if (familyMember.Id == -1) { // added new person groupMember.Person = new Person(); groupMember.Person.GivenName = familyMember.FirstName; groupMember.Person.LastName = familyMember.LastName; groupMember.Person.Gender = familyMember.Gender; groupMember.Person.BirthDate = familyMember.BirthDate; } else { // added from other family groupMember.Person = personService.Get(familyMember.Id); } groupMember.Person.RecordStatusValueId = recordStatusValueID; groupMember.Person.RecordStatusReasonValueId = reasonValueId; groupMember.GroupId = _family.Id; if (role != null) { groupMember.GroupRoleId = role.Id; } if (groupMember.Person != null) { familyMemberService.Add(groupMember, CurrentPersonId); familyMemberService.Save(groupMember, CurrentPersonId); } } else { // existing family members var groupMember = familyMemberService.Queryable().Where(m => m.PersonId == familyMember.Id && m.Group.GroupTypeId == familyGroupTypeId && m.GroupId == _family.Id).FirstOrDefault(); if (groupMember != null) { if (familyMember.Removed) { // Family member was removed and should be created in their own new family var newFamily = new Group(); newFamily.Name = familyMember.LastName + " Family"; newFamily.GroupTypeId = familyGroupTypeId; newFamily.CampusId = _family.CampusId; familyService.Add(newFamily, CurrentPersonId); familyService.Save(newFamily, CurrentPersonId); groupMember.Group = newFamily; familyMemberService.Save(groupMember, CurrentPersonId); newFamilies.Add(newFamily); } else { // Existing member was not remvoved if (role != null) { groupMember.GroupRoleId = role.Id; groupMember.Person.RecordStatusValueId = recordStatusValueID; groupMember.Person.RecordStatusReasonValueId = reasonValueId; familyMemberService.Save(groupMember, CurrentPersonId); } } } } // Remove anyone that was moved from another family if (familyMember.RemoveFromOtherFamilies) { var otherFamilies = familyMemberService.Queryable() .Where(m => m.PersonId == familyMember.Id && m.Group.GroupTypeId == familyGroupTypeId && m.GroupId != _family.Id) .ToList(); foreach (var otherFamilyMember in otherFamilies) { var fm = familyMemberService.Get(otherFamilyMember.Id); familyMemberService.Delete(fm, CurrentPersonId); familyMemberService.Save(fm, CurrentPersonId); var f = familyService.Queryable() .Where(g => g.Id == otherFamilyMember.GroupId && !g.Members.Any()) .FirstOrDefault(); if (f != null) { familyService.Delete(f, CurrentPersonId); familyService.Save(f, CurrentPersonId); } } } } // SAVE LOCATIONS var groupLocationService = new GroupLocationService(); // delete any group locations that were removed var remainingLocationIds = FamilyAddresses.Where(a => a.Id > 0).Select(a => a.Id).ToList(); foreach (var removedLocation in groupLocationService.Queryable() .Where(l => l.GroupId == _family.Id && !remainingLocationIds.Contains(l.Id))) { groupLocationService.Delete(removedLocation, CurrentPersonId); groupLocationService.Save(removedLocation, CurrentPersonId); } foreach (var familyAddress in FamilyAddresses) { GroupLocation groupLocation = null; if (familyAddress.Id > 0) { groupLocation = groupLocationService.Get(familyAddress.Id); } if (groupLocation == null) { groupLocation = new GroupLocation(); groupLocation.GroupId = _family.Id; groupLocationService.Add(groupLocation, CurrentPersonId); } groupLocation.GroupLocationTypeValueId = familyAddress.LocationTypeId; groupLocation.IsMailing = familyAddress.IsMailing; groupLocation.IsLocation = familyAddress.IsLocation; if (familyAddress.LocationIsDirty) { groupLocation.Location = new LocationService().Get( familyAddress.Street1, familyAddress.Street2, familyAddress.City, familyAddress.State, familyAddress.Zip); } groupLocationService.Save(groupLocation, CurrentPersonId); // Add the same locations to any new families created by removing an existing family member if (newFamilies.Any()) { //reload grouplocation for access to child properties groupLocation = groupLocationService.Get(groupLocation.Id); foreach (var newFamily in newFamilies) { var newFamilyLocation = new GroupLocation(); newFamilyLocation.GroupId = newFamily.Id; newFamilyLocation.LocationId = groupLocation.LocationId; newFamilyLocation.GroupLocationTypeValueId = groupLocation.GroupLocationTypeValueId; newFamilyLocation.IsMailing = groupLocation.IsMailing; newFamilyLocation.IsLocation = groupLocation.IsLocation; groupLocationService.Add(newFamilyLocation, CurrentPersonId); groupLocationService.Save(newFamilyLocation, CurrentPersonId); } } } _family = familyService.Get(_family.Id); if (_family.Members.Any(m => m.PersonId == Person.Id)) { Response.Redirect(string.Format("~/Person/{0}", Person.Id), false); } else { var fm = _family.Members .Where(m => m.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)) && m.Person.Gender == Gender.Male) .OrderByDescending(m => m.Person.Age) .FirstOrDefault(); if (fm == null) { fm = _family.Members .Where(m => m.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT))) .OrderByDescending(m => m.Person.Age) .FirstOrDefault(); } if (fm == null) { fm = _family.Members .OrderByDescending(m => m.Person.Age) .FirstOrDefault(); } if (fm != null) { Response.Redirect(string.Format("~/Person/{0}", fm.PersonId), false); } else { Response.Redirect("~", false); } } } } }
/// <summary> /// 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 wasSecurityRole = false; bool triggersUpdated = false; RockContext rockContext = new RockContext(); GroupService groupService = new GroupService(rockContext); ScheduleService scheduleService = new ScheduleService(rockContext); var roleGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()); int roleGroupTypeId = roleGroupType != null ? roleGroupType.Id : int.MinValue; int?parentGroupId = hfParentGroupId.Value.AsIntegerOrNull(); if (parentGroupId != null) { var allowedGroupIds = LineQuery.GetCellGroupIdsInLine(CurrentPerson, rockContext); if (!allowedGroupIds.Contains(parentGroupId.Value)) { nbMessage.Text = "You are not allowed to add a group to this parent group."; nbMessage.Visible = true; pnlEditDetails.Visible = false; btnSave.Enabled = false; return; } var parentGroup = groupService.Get(parentGroupId.Value); if (parentGroup != null) { CurrentGroupTypeId = parentGroup.GroupTypeId; if (!lppLeader.PersonId.HasValue) { nbMessage.Text = "A Leader is required."; nbMessage.Visible = true; return; } if (!GroupLocationsState.Any()) { nbMessage.Text = "A location is required."; nbMessage.Visible = true; return; } if (CurrentGroupTypeId == 0) { return; } Group group = new Group(); group.IsSystem = false; group.Name = string.Empty; // add/update any group locations that were added or changed in the UI (we already removed the ones that were removed above) foreach (var groupLocationState in GroupLocationsState) { GroupLocation groupLocation = group.GroupLocations.Where(l => l.Guid == groupLocationState.Guid).FirstOrDefault(); if (groupLocation == null) { groupLocation = new GroupLocation(); group.GroupLocations.Add(groupLocation); } else { groupLocationState.Id = groupLocation.Id; groupLocationState.Guid = groupLocation.Guid; var selectedSchedules = groupLocationState.Schedules.Select(s => s.Guid).ToList(); foreach (var schedule in groupLocation.Schedules.Where(s => !selectedSchedules.Contains(s.Guid)).ToList()) { groupLocation.Schedules.Remove(schedule); } } groupLocation.CopyPropertiesFrom(groupLocationState); var existingSchedules = groupLocation.Schedules.Select(s => s.Guid).ToList(); foreach (var scheduleState in groupLocationState.Schedules.Where(s => !existingSchedules.Contains(s.Guid)).ToList()) { var schedule = scheduleService.Get(scheduleState.Guid); if (schedule != null) { groupLocation.Schedules.Add(schedule); } } } GroupMember leader = new GroupMember(); leader.GroupMemberStatus = GroupMemberStatus.Active; leader.PersonId = lppLeader.PersonId.Value; leader.Person = new PersonService(rockContext).Get(lppLeader.PersonId.Value); leader.GroupRole = parentGroup.GroupType.Roles.Where(r => r.IsLeader).FirstOrDefault() ?? parentGroup.GroupType.DefaultGroupRole; group.Name = String.Format("{0}, {1}", leader.Person.NickName, leader.Person.LastName); group.Description = tbDescription.Text; group.CampusId = parentGroup.CampusId; group.GroupTypeId = CurrentGroupTypeId; group.ParentGroupId = parentGroupId; group.IsSecurityRole = false; group.IsActive = true; group.IsPublic = true; if (dpStartDate.SelectedDate.HasValue) { group.CreatedDateTime = dpStartDate.SelectedDate.Value; } group.Members.Add(leader); string iCalendarContent = string.Empty; // If unique schedule option was selected, but a schedule was not defined, set option to 'None' var scheduleType = rblScheduleSelect.SelectedValueAsEnum <ScheduleType>(ScheduleType.None); if (scheduleType == ScheduleType.Custom) { iCalendarContent = sbSchedule.iCalendarContent; var calEvent = ScheduleICalHelper.GetCalenderEvent(iCalendarContent); if (calEvent == null || calEvent.DTStart == null) { scheduleType = ScheduleType.None; } } if (scheduleType == ScheduleType.Weekly) { if (!dowWeekly.SelectedDayOfWeek.HasValue) { scheduleType = ScheduleType.None; } } int?oldScheduleId = hfUniqueScheduleId.Value.AsIntegerOrNull(); if (scheduleType == ScheduleType.Custom || scheduleType == ScheduleType.Weekly) { if (!oldScheduleId.HasValue || group.Schedule == null) { group.Schedule = new Schedule(); } if (scheduleType == ScheduleType.Custom) { group.Schedule.iCalendarContent = iCalendarContent; group.Schedule.WeeklyDayOfWeek = null; group.Schedule.WeeklyTimeOfDay = null; } else { group.Schedule.iCalendarContent = null; group.Schedule.WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek; group.Schedule.WeeklyTimeOfDay = timeWeekly.SelectedTime; } } else { // If group did have a unique schedule, delete that schedule if (oldScheduleId.HasValue) { var schedule = scheduleService.Get(oldScheduleId.Value); if (schedule != null && string.IsNullOrEmpty(schedule.Name)) { scheduleService.Delete(schedule); } } if (scheduleType == ScheduleType.Named) { group.ScheduleId = spSchedule.SelectedValueAsId(); } else { group.ScheduleId = null; } } group.LoadAttributes(); Rock.Attribute.Helper.GetEditValues(phGroupAttributes, group); group.GroupType = new GroupTypeService(rockContext).Get(group.GroupTypeId); if (group.ParentGroupId.HasValue) { group.ParentGroup = groupService.Get(group.ParentGroupId.Value); } if (!Page.IsValid) { return; } // if the groupMember IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass. // So, make sure a message is displayed in the validation summary cvGroup.IsValid = group.IsValid; if (!cvGroup.IsValid) { cvGroup.ErrorMessage = group.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />"); return; } // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges() rockContext.WrapTransaction(() => { var adding = group.Id.Equals(0); if (adding) { groupService.Add(group); } rockContext.SaveChanges(); if (adding) { // add ADMINISTRATE to the person who added the group Rock.Security.Authorization.AllowPerson(group, Authorization.ADMINISTRATE, this.CurrentPerson, rockContext); } group.SaveAttributeValues(rockContext); }); bool isNowSecurityRole = group.IsActive && (group.GroupTypeId == roleGroupTypeId); if (isNowSecurityRole) { // new security role, flush Rock.Security.Authorization.Flush(); } AttributeCache.FlushEntityAttributes(); pnlDetails.Visible = false; pnlSuccess.Visible = true; nbSuccess.Text = string.Format("Your group ({0}) has been created", group.Name); string linkedPage = LinkedPageRoute("RedirectPage"); int secondsBeforeRedirect = GetAttributeValue("SecondsBeforeRedirect").AsInteger() * 1000; ScriptManager.RegisterClientScriptBlock(upnlGroupDetail, typeof(UpdatePanel), "Redirect", string.Format("console.log('{0}'); setTimeout(function() {{ window.location.replace('{0}?GroupId={2}') }}, {1});", linkedPage, secondsBeforeRedirect, group.Id), true); } } }
/// <summary> /// Handles the Click event of the btnGive 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 btnGive_Click(object sender, EventArgs e) { Person person = FindPerson(); using (new UnitOfWorkScope()) { RockTransactionScope.WrapTransaction(() => { var groupLocationService = new GroupLocationService(); var groupMemberService = new GroupMemberService(); var phoneService = new PhoneNumberService(); var locationService = new LocationService(); var groupService = new GroupService(); GroupLocation groupLocation; Location homeAddress; Group familyGroup; var homeLocationType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.LOCATION_TYPE_HOME); var addressList = locationService.Queryable().Where(l => l.Street1 == txtStreet.Text && l.City == txtCity.Text && l.State == ddlState.SelectedValue && l.Zip == txtZip.Text && l.LocationTypeValueId == homeLocationType.Id).ToList(); if (!addressList.Any()) { homeAddress = new Location(); locationService.Add(homeAddress, person.Id); } else { homeAddress = addressList.FirstOrDefault(); } homeAddress.Street1 = txtStreet.Text ?? homeAddress.Street1; homeAddress.City = txtCity.Text ?? homeAddress.City; homeAddress.State = ddlState.SelectedValue ?? homeAddress.State; homeAddress.Zip = txtZip.Text ?? homeAddress.Zip; homeAddress.IsActive = true; homeAddress.IsLocation = true; homeAddress.Country = "US"; homeAddress.LocationTypeValueId = homeLocationType.Id; locationService.Save(homeAddress, person.Id); GroupType familyGroupType = new GroupTypeService().Get(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY)); var familyGroupList = groupMemberService.Queryable().Where(g => g.PersonId == person.Id && g.Group.GroupType.Guid == familyGroupType.Guid).Select(g => g.Group).ToList(); if (!familyGroupList.Any()) { familyGroup = new Group(); familyGroup.IsActive = true; familyGroup.IsSystem = false; familyGroup.IsSecurityRole = false; familyGroup.Name = "The " + txtLastName.Text + " Family"; familyGroup.GroupTypeId = familyGroupType.Id; groupService.Add(familyGroup, person.Id); groupService.Save(familyGroup, person.Id); var familyMember = new GroupMember(); familyMember.IsSystem = false; familyMember.GroupId = familyGroup.Id; familyMember.PersonId = person.Id; familyMember.GroupRoleId = new GroupRoleService().Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id; groupMemberService.Add(familyMember, person.Id); groupMemberService.Save(familyMember, person.Id); } else { familyGroup = familyGroupList.FirstOrDefault(); } var groupLocationList = groupLocationService.Queryable().Where(g => g.GroupLocationTypeValueId == familyGroupType.Id && g.GroupId == familyGroup.Id).ToList(); if (!groupLocationList.Any()) { groupLocation = new GroupLocation(); groupLocation.GroupId = familyGroup.Id; groupLocation.LocationId = homeAddress.Id; groupLocation.IsMailing = true; groupLocation.IsLocation = true; groupLocation.GroupLocationTypeValueId = homeLocationType.Id; groupLocationService.Add(groupLocation, person.Id); groupLocationService.Save(groupLocation, person.Id); } else { groupLocation = groupLocationList.FirstOrDefault(); } groupLocation.LocationId = homeAddress.Id; groupLocationService.Save(groupLocation, person.Id); var homePhoneType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME); string phoneNumeric = txtPhone.Text.AsNumeric(); if (!phoneService.Queryable().Where(n => n.PersonId == person.Id && n.NumberTypeValueId == homePhoneType.Id && n.Number == phoneNumeric).Any()) { var homePhone = new PhoneNumber(); homePhone.Number = phoneNumeric; homePhone.PersonId = person.Id; homePhone.IsSystem = false; homePhone.IsMessagingEnabled = false; homePhone.IsUnlisted = false; homePhone.NumberTypeValueId = homePhoneType.Id; phoneService.Add(homePhone, person.Id); phoneService.Save(homePhone, person.Id); } }); } var amountList = (Dictionary <FinancialAccount, Decimal>)Session["CachedAmounts"]; var profileId = (int)Session["CachedProfileId"]; Location giftLocation = new Location(); var configValues = (Dictionary <string, object>)Session["CachedMergeFields"]; configValues.Add("Date", DateTimeOffset.Now.ToString("MM/dd/yyyy hh:mm tt")); var receiptTemplate = GetAttributeValue("ReceiptMessage"); lReceipt.Text = receiptTemplate.ResolveMergeFields(configValues); var summaryTemplate = GetAttributeValue("SummaryMessage"); string summaryMessage = summaryTemplate.ResolveMergeFields(configValues); // #TODO test card through gateway if (btnFrequency.SelectedIndex > -1 && btnFrequency.SelectedValueAsInt() > 0) { using (new UnitOfWorkScope()) { RockTransactionScope.WrapTransaction(() => { var scheduledTransactionDetailService = new FinancialScheduledTransactionDetailService(); var scheduledTransactionService = new FinancialScheduledTransactionService(); FinancialScheduledTransaction scheduledTransaction; var detailList = amountList.ToList(); if (profileId > 0) { scheduledTransaction = scheduledTransactionService.Get(profileId); } else { scheduledTransaction = new FinancialScheduledTransaction(); scheduledTransactionService.Add(scheduledTransaction, person.Id); } DateTime startDate = (DateTime)dtpStartDate.SelectedDate; if (startDate != null) { scheduledTransaction.StartDate = startDate; } scheduledTransaction.TransactionFrequencyValueId = (int)btnFrequency.SelectedValueAsInt(); scheduledTransaction.AuthorizedPersonId = person.Id; scheduledTransaction.IsActive = true; if (!string.IsNullOrEmpty(txtCreditCard.Text)) { scheduledTransaction.CardReminderDate = mypExpiration.SelectedDate; } if (chkLimitGifts.Checked && !string.IsNullOrWhiteSpace(txtLimitNumber.Text)) { scheduledTransaction.NumberOfPayments = Convert.ToInt32(txtLimitNumber.Text); } foreach (var detail in amountList.ToList()) { var scheduledTransactionDetail = new FinancialScheduledTransactionDetail(); scheduledTransactionDetail.AccountId = detail.Key.Id; scheduledTransactionDetail.Amount = detail.Value; scheduledTransactionDetail.ScheduledTransactionId = scheduledTransaction.Id; scheduledTransactionDetailService.Add(scheduledTransactionDetail, person.Id); scheduledTransactionDetailService.Save(scheduledTransactionDetail, person.Id); } // implement gateway charge() scheduledTransactionService.Save(scheduledTransaction, person.Id); }); } } else { using (new UnitOfWorkScope()) { RockTransactionScope.WrapTransaction(() => { var transactionService = new FinancialTransactionService(); var tdService = new FinancialTransactionDetailService(); var transaction = new FinancialTransaction(); var detailList = amountList.ToList(); transaction.Summary = summaryMessage; transaction.Amount = detailList.Sum(d => d.Value); transaction.TransactionTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION).Id; transaction.TransactionDateTime = DateTimeOffset.Now.DateTime; transaction.AuthorizedPersonId = person.Id; transactionService.Add(transaction, person.Id); foreach (var detail in detailList) { var td = new FinancialTransactionDetail(); td.TransactionId = transaction.Id; td.AccountId = detail.Key.Id; td.Amount = detail.Value; td.TransactionId = transaction.Id; tdService.Add(td, person.Id); tdService.Save(td, person.Id); } // #TODO implement gateway.charge() transactionService.Save(transaction, person.Id); }); } } Session["CachedMergeFields"] = configValues; pnlConfirm.Visible = false; pnlComplete.Visible = true; pnlContribution.Update(); }
protected void btnNext_Click( object sender, EventArgs e ) { if ( Page.IsValid ) { if ( CurrentCategoryIndex < attributeControls.Count ) { CurrentCategoryIndex++; ShowAttributeCategory( CurrentCategoryIndex ); } else { var familyMembers = GetControlData(); if ( familyMembers.Any() ) { RockTransactionScope.WrapTransaction( () => { using ( new UnitOfWorkScope() ) { var groupTypeService = new GroupTypeService(); var familyGroupType = groupTypeService.Get( new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY ) ); if ( familyGroupType != null ) { var groupService = new GroupService(); var familyGroup = new Group(); familyGroup.Name = tbFamilyName.Text; familyGroup.GroupTypeId = familyGroupType.Id; familyGroup.CampusId = cpCampus.SelectedValueAsInt(); familyMembers.ForEach( m => familyGroup.Members.Add( m ) ); var groupLocation = new GroupLocation(); var location = new LocationService().Get( tbStreet1.Text, tbStreet2.Text, tbCity.Text, ddlState.SelectedValue, tbZip.Text ); groupLocation.Location = location; Guid locationTypeGuid = Guid.Empty; if ( Guid.TryParse( GetAttributeValue( "LocationType" ), out locationTypeGuid ) ) { var locationType = Rock.Web.Cache.DefinedValueCache.Read( locationTypeGuid ); if (locationType != null) { groupLocation.GroupLocationTypeValueId = locationType.Id; } } familyGroup.GroupLocations.Add( groupLocation ); groupService.Add( familyGroup, CurrentPersonId ); groupService.Save( familyGroup, CurrentPersonId ); var groupMemberService = new GroupMemberService(); foreach ( var person in familyMembers.Select( m => m.Person ) ) { foreach ( var attributeControl in attributeControls ) { foreach ( var attribute in attributeControl.AttributeList ) { Rock.Attribute.Helper.SaveAttributeValue( person, attribute, person.GetAttributeValue( attribute.Key ), CurrentPersonId ); } } } } } } ); Response.Redirect( string.Format( "~/Person/{0}", familyMembers[0].Person.Id ), false ); } } } }
/// <summary> /// Executes this instance. /// </summary> /// <param name="message"></param> public override void Execute(Message message) { using (var rockContext = new RockContext()) { var relationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid()); if (relationshipGroupType != null) { var ownerRole = relationshipGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid())) .FirstOrDefault(); var friendRole = relationshipGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_FACEBOOK_FRIEND.AsGuid())) .FirstOrDefault(); if (ownerRole != null && friendRole != null) { var userLoginService = new UserLoginService(rockContext); var groupMemberService = new GroupMemberService(rockContext); // Convert list of facebook ids into list of usernames var friendUserNames = message.FacebookIds.Select(i => "FACEBOOK_" + i).ToList(); // Get the list of person ids associated with friends usernames var friendPersonIds = userLoginService.Queryable() .Where(l => l.PersonId.HasValue && l.PersonId != message.PersonId && friendUserNames.Contains(l.UserName)) .Select(l => l.PersonId.Value) .Distinct() .ToList(); // Get the person's group id var personGroup = groupMemberService.Queryable() .Where(m => m.PersonId == message.PersonId && m.GroupRoleId == ownerRole.Id && m.Group.GroupTypeId == relationshipGroupType.Id) .Select(m => m.Group) .FirstOrDefault(); // Verify that a 'known relationships' type group existed for the person, if not create it if (personGroup == null) { var groupMember = new GroupMember(); groupMember.PersonId = message.PersonId; groupMember.GroupRoleId = ownerRole.Id; personGroup = new Group(); personGroup.Name = relationshipGroupType.Name; personGroup.GroupTypeId = relationshipGroupType.Id; personGroup.Members.Add(groupMember); var groupService = new GroupService(rockContext); groupService.Add(personGroup); rockContext.SaveChanges(); } // Get the person's relationship group id var personGroupId = personGroup.Id; // Get all of the friend's relationship group ids var friendGroupIds = groupMemberService.Queryable() .Where(m => m.Group.GroupTypeId == relationshipGroupType.Id && m.GroupRoleId == ownerRole.Id && friendPersonIds.Contains(m.PersonId)) .Select(m => m.GroupId) .Distinct() .ToList(); // Find all the existing friend relationships in Rock ( both directions ) var existingFriends = groupMemberService.Queryable() .Where(m => m.Group.GroupTypeId == relationshipGroupType.Id && ( (friendPersonIds.Contains(m.PersonId) && m.GroupId == personGroupId) || (m.PersonId == message.PersonId && m.GroupId != personGroupId) )) .ToList(); // Create temp group members for current Facebook friends var currentFriends = new List <GroupMember>(); // ( Person > Friend ) foreach (int personId in friendPersonIds) { var groupMember = new GroupMember(); groupMember.GroupId = personGroupId; groupMember.PersonId = personId; groupMember.GroupRoleId = friendRole.Id; groupMember.GroupMemberStatus = GroupMemberStatus.Active; currentFriends.Add(groupMember); } // ( Friend > Person ) foreach (int familyId in friendGroupIds) { var groupMember = new GroupMember(); groupMember.GroupId = familyId; groupMember.PersonId = message.PersonId; groupMember.GroupRoleId = friendRole.Id; groupMember.GroupMemberStatus = GroupMemberStatus.Active; currentFriends.Add(groupMember); } // Add any current friends that do not exist in Rock yet foreach (var groupMember in currentFriends .Where(f => !existingFriends.Any(e => e.IsEqualTo(f)))) { groupMemberService.Add(groupMember); } // Delete any existing friends that are no longer facebook friends foreach (var groupMember in existingFriends .Where(f => !currentFriends.Any(e => e.IsEqualTo(f)))) { groupMemberService.Delete(groupMember); } rockContext.SaveChanges(); } } } }
/// <summary> /// Binds the data. /// </summary> private void BindData() { if (Person != null && Person.Id > 0) { if (ownerRoleGuid != Guid.Empty) { using (var rockContext = new RockContext()) { var memberService = new GroupMemberService(rockContext); var group = memberService.Queryable(true) .Where(m => m.PersonId == Person.Id && m.GroupRole.Guid == ownerRoleGuid) .Select(m => m.Group) .FirstOrDefault(); if (group == null && GetAttributeValue("CreateGroup").AsBoolean()) { var role = new GroupTypeRoleService(rockContext).Get(ownerRoleGuid); if (role != null && role.GroupTypeId.HasValue) { var groupService = new GroupService(rockContext); group = new Group(); group.Name = role.GroupType.Name; group.GroupTypeId = role.GroupTypeId.Value; groupService.Add(group); rockContext.SaveChanges(); var groupMember = new GroupMember(); groupMember.PersonId = Person.Id; groupMember.GroupRoleId = role.Id; groupMember.GroupId = group.Id; group.Members.Add(groupMember); rockContext.SaveChanges(); group = groupService.Get(group.Id); } } if (group != null) { lGroupName.Text = group.Name.Pluralize(); lGroupTypeIcon.Text = string.Format("<i class='{0}'></i>", group.GroupType.IconCssClass); lGroupTypeIcon.Visible = group.GroupType.IconCssClass.IsNotNullOrWhiteSpace(); phEditActions.Visible = group.IsAuthorized(Authorization.EDIT, CurrentPerson); if (group.IsAuthorized(Authorization.VIEW, CurrentPerson)) { int?maxRelationshipsToDisplay = this.GetAttributeValue("MaxRelationshipsToDisplay").AsIntegerOrNull(); IQueryable <GroupMember> qryGroupMembers = new GroupMemberService(rockContext).GetByGroupId(group.Id, true) .Where(m => m.PersonId != Person.Id) .OrderBy(m => m.Person.LastName) .ThenBy(m => m.Person.FirstName); if (maxRelationshipsToDisplay.HasValue) { qryGroupMembers = qryGroupMembers.Take(maxRelationshipsToDisplay.Value); } rGroupMembers.DataSource = qryGroupMembers.ToList(); rGroupMembers.DataBind(); } else { lAccessWarning.Text = string.Format("<div class='alert alert-info'>You do not have security rights to view {0}.", group.Name.Pluralize()); } } else { lGroupName.Text = this.BlockCache.Name; } } } } }
/// <summary> /// Handles the Click event of the btnCopy 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 lbCopyButton_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var groupService = new GroupService(rockContext); var authService = new AuthService(rockContext); var attributeService = new AttributeService(rockContext); int groupId = hfGroupId.ValueAsInt(); var group = groupService.Queryable("GroupType") .Where(g => g.Id == groupId) .FirstOrDefault(); if (group != null) { group.LoadAttributes(rockContext); // clone the group var newGroup = group.Clone(false); newGroup.CreatedByPersonAlias = null; newGroup.CreatedByPersonAliasId = null; newGroup.CreatedDateTime = RockDateTime.Now; newGroup.ModifiedByPersonAlias = null; newGroup.ModifiedByPersonAliasId = null; newGroup.ModifiedDateTime = RockDateTime.Now; newGroup.Id = 0; newGroup.Guid = Guid.NewGuid(); newGroup.IsSystem = false; newGroup.Name = group.Name + " - Copy"; if (GetAttributeValue("CopyLocation").AsBoolean(true)) { foreach (GroupLocation location in group.GroupLocations) { newGroup.GroupLocations.Add(location); } } var auths = authService.GetByGroup(group.Id); rockContext.WrapTransaction(() => { groupService.Add(newGroup); rockContext.SaveChanges(); newGroup.LoadAttributes(rockContext); if (group.Attributes != null && group.Attributes.Any()) { foreach (var attributeKey in group.Attributes.Select(a => a.Key)) { string value = group.GetAttributeValue(attributeKey); newGroup.SetAttributeValue(attributeKey, value); } } newGroup.SaveAttributeValues(rockContext); /* Take care of Group Member Attributes */ var entityTypeId = EntityTypeCache.Get(typeof(GroupMember)).Id; string qualifierColumn = "GroupId"; string qualifierValue = group.Id.ToString(); // Get the existing attributes for this entity type and qualifier value var attributes = attributeService.Get(entityTypeId, qualifierColumn, qualifierValue); foreach (var attribute in attributes) { var newAttribute = attribute.Clone(false); newAttribute.Id = 0; newAttribute.Guid = Guid.NewGuid(); newAttribute.IsSystem = false; newAttribute.EntityTypeQualifierValue = newGroup.Id.ToString(); foreach (var qualifier in attribute.AttributeQualifiers) { var newQualifier = qualifier.Clone(false); newQualifier.Id = 0; newQualifier.Guid = Guid.NewGuid(); newQualifier.IsSystem = false; newAttribute.AttributeQualifiers.Add(qualifier); } attributeService.Add(newAttribute); } rockContext.SaveChanges(); var person = CurrentPerson; GroupMember currentGroupMember = null; if (person != null) { currentGroupMember = group.Members.Where(gm => gm.PersonId == person.Id).FirstOrDefault(); } if (currentGroupMember != null) { var newGroupMember = currentGroupMember.Clone(false); newGroupMember.Id = 0; newGroupMember.Guid = Guid.NewGuid(); newGroupMember.IsSystem = false; newGroup.Members.Add(newGroupMember); } rockContext.SaveChanges(); foreach (var auth in auths) { var newAuth = auth.Clone(false); newAuth.Id = 0; newAuth.Guid = Guid.NewGuid(); newAuth.GroupId = newGroup.Id; newAuth.CreatedByPersonAlias = null; newAuth.CreatedByPersonAliasId = null; newAuth.CreatedDateTime = RockDateTime.Now; newAuth.ModifiedByPersonAlias = null; newAuth.ModifiedByPersonAliasId = null; newAuth.ModifiedDateTime = RockDateTime.Now; authService.Add(newAuth); } rockContext.SaveChanges(); Rock.Security.Authorization.Clear(); }); NavigateToCurrentPage(new Dictionary <string, string> { { "GroupId", newGroup.Id.ToString() } }); } }