/// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            GroupType groupType = null;

            var rockContext = new RockContext();
            GroupTypeService          groupTypeService          = new GroupTypeService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);

            int?groupTypeId = hfGroupTypeId.ValueAsInt();

            if (groupTypeId.HasValue && groupTypeId.Value > 0)
            {
                groupType = groupTypeService.Get(groupTypeId.Value);
            }

            bool newGroupType = false;

            if (groupType == null)
            {
                groupType = new GroupType();
                groupTypeService.Add(groupType);

                var templatePurpose = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid());
                if (templatePurpose != null)
                {
                    groupType.GroupTypePurposeValueId = templatePurpose.Id;
                }

                newGroupType = true;
            }

            if (groupType != null)
            {
                groupType.Name        = tbName.Text;
                groupType.Description = tbDescription.Text;

                groupType.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributeEdits, groupType);

                groupType.SetAttributeValue("core_checkin_AgeRequired", cbAgeRequired.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_GradeRequired", cbGradeRequired.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_HidePhotos", cbHidePhotos.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PreventDuplicateCheckin", cbPreventDuplicateCheckin.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PreventInactivePeople", cbPreventInactivePeople.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_CheckInType", ddlType.SelectedValue);
                groupType.SetAttributeValue("core_checkin_DisplayLocationCount", cbDisplayLocCount.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_EnableManagerOption", cbEnableManager.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_EnableOverride", cbEnableOverride.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_MaximumPhoneSearchLength", nbMaxPhoneLength.Text);
                groupType.SetAttributeValue("core_checkin_MaxSearchResults", nbMaxResults.Text);
                groupType.SetAttributeValue("core_checkin_MinimumPhoneSearchLength", nbMinPhoneLength.Text);
                groupType.SetAttributeValue("core_checkin_UseSameOptions", cbUseSameOptions.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PhoneSearchType", ddlPhoneSearchType.SelectedValue);
                groupType.SetAttributeValue("core_checkin_RefreshInterval", nbRefreshInterval.Text);
                groupType.SetAttributeValue("core_checkin_RegularExpressionFilter", tbSearchRegex.Text);
                groupType.SetAttributeValue("core_checkin_ReuseSameCode", cbReuseCode.Checked.ToString());

                var searchType = DefinedValueCache.Read(ddlSearchType.SelectedValueAsInt() ?? 0);
                if (searchType != null)
                {
                    groupType.SetAttributeValue("core_checkin_SearchType", searchType.Guid.ToString());
                }
                else
                {
                    groupType.SetAttributeValue("core_checkin_SearchType", Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER);
                }

                groupType.SetAttributeValue("core_checkin_SecurityCodeLength", nbCodeAlphaNumericLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeAlphaLength", nbCodeAlphaLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeNumericLength", nbCodeNumericLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeNumericRandom", cbCodeRandom.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_AutoSelectDaysBack", nbAutoSelectDaysBack.Text);

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    groupType.SaveAttributeValues(rockContext);
                });

                if (newGroupType)
                {
                    var pageRef = new PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId);
                    pageRef.Parameters.Add("CheckinTypeId", groupType.Id.ToString());
                    NavigateToPage(pageRef);
                }
                else
                {
                    groupType = groupTypeService.Get(groupType.Id);
                    ShowReadonlyDetails(groupType);
                }

                GroupTypeCache.Flush(groupType.Id);
                Rock.CheckIn.KioskDevice.FlushAll();
            }
        }
        /// <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;

            using (new UnitOfWorkScope())
            {
                GroupTypeService groupTypeService = new GroupTypeService();
                GroupService     groupService     = new GroupService();
                AttributeService attributeService = new AttributeService();

                int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt();

                var groupTypeUIList = new List <GroupType>();

                foreach (var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType <CheckinGroupTypeEditor>().ToList())
                {
                    var groupType = checkinGroupTypeEditor.GetCheckinGroupType();
                    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 = new FieldTypeService().Get(new Guid(Rock.SystemGuid.FieldType.BINARY_FILE)).Id;
                int binaryFileTypeId      = new BinaryFileTypeService().Get(new Guid(Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL)).Id;

                RockTransactionScope.WrapTransaction(() =>
                {
                    // delete in reverse order to get deepest child items first
                    groupsToDelete.Reverse();
                    foreach (var groupToDelete in groupsToDelete)
                    {
                        groupService.Delete(groupToDelete, this.CurrentPersonId);
                        groupService.Save(groupToDelete, this.CurrentPersonId);
                    }

                    // delete in reverse order to get deepest child items first
                    groupTypesToDelete.Reverse();
                    foreach (var groupTypeToDelete in groupTypesToDelete)
                    {
                        groupTypeService.Delete(groupTypeToDelete, this.CurrentPersonId);
                        groupTypeService.Save(groupTypeToDelete, this.CurrentPersonId);
                    }

                    // 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.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, this.CurrentPersonId);
                        }

                        if (!groupTypeDB.IsValid)
                        {
                            hasValidationErrors = true;
                            CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid);
                            groupTypeEditor.ForceContentVisible    = true;

                            return;
                        }

                        groupTypeService.Save(groupTypeDB, this.CurrentPersonId);

                        Rock.Attribute.Helper.SaveAttributeValues(groupTypeDB, this.CurrentPersonId);

                        // 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))
                        {
                            var attribute = attributeService.Get(labelAttributeDB.Value.Guid);
                            Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                            attributeService.Delete(attribute, this.CurrentPersonId);
                        }

                        foreach (var checkinLabelAttributeInfo in GroupTypeCheckinLabelAttributesState[groupTypeUI.Guid])
                        {
                            var attribute = new Rock.Model.Attribute();
                            attribute.AttributeQualifiers.Add(new AttributeQualifier {
                                Key = "binaryFileType", Value = binaryFileTypeId.ToString()
                            });
                            attribute.Guid         = Guid.NewGuid();
                            attribute.FieldTypeId  = binaryFileFieldTypeID;
                            attribute.EntityTypeId = EntityTypeCache.GetId(typeof(GroupType));
                            attribute.EntityTypeQualifierColumn = "Id";
                            attribute.EntityTypeQualifierValue  = groupTypeDB.Id.ToString();
                            attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileId.ToString();
                            attribute.Key          = checkinLabelAttributeInfo.AttributeKey;
                            attribute.Name         = checkinLabelAttributeInfo.FileName;

                            if (!attribute.IsValid)
                            {
                                hasValidationErrors = true;
                                CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid);
                                groupTypeEditor.ForceContentVisible    = true;

                                return;
                            }

                            attributeService.Add(attribute, this.CurrentPersonId);
                            attributeService.Save(attribute, this.CurrentPersonId);
                        }
                    }

                    // 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))
                            {
                                groupDB.GroupLocations.Remove(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;
                        groupDB.Attributes      = groupUI.Attributes;
                        groupDB.AttributeValues = groupUI.AttributeValues;

                        if (groupDB.Id == 0)
                        {
                            groupService.Add(groupDB, this.CurrentPersonId);
                        }

                        if (!groupDB.IsValid)
                        {
                            hasValidationErrors             = true;
                            hasValidationErrors             = true;
                            CheckinGroupEditor groupEditor  = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupEditor>().First(a => a.GroupGuid == groupDB.Guid);
                            groupEditor.ForceContentVisible = true;

                            return;
                        }

                        groupService.Save(groupDB, this.CurrentPersonId);

                        Rock.Attribute.Helper.SaveAttributeValues(groupDB, this.CurrentPersonId);
                    }

                    /* 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);
                    }

                    groupTypeService.Save(parentGroupTypeDB, this.CurrentPersonId);

                    // 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();
                        foreach (var childGroupTypeUI in groupTypeUI.ChildGroupTypes)
                        {
                            var childGroupTypeDB = groupTypeService.Get(childGroupTypeUI.Guid);
                            groupTypeDB.ChildGroupTypes.Add(childGroupTypeDB);
                        }

                        groupTypeService.Save(groupTypeDB, this.CurrentPersonId);
                    }
                });
            }

            if (!hasValidationErrors)
            {
                NavigateToParentPage();
            }
        }
Exemple #3
0
        private void RebuildAttributeLists(int?inheritedGroupTypeId, GroupTypeService groupTypeService, AttributeService attributeService,
                                           bool clearList)
        {
            string qualifierValue = PageParameter("GroupTypeId");

            if (clearList)
            {
                var attributes = new List <Attribute>();
                foreach (var attribute in GroupTypeAttributesState)
                {
                    if (string.IsNullOrWhiteSpace(attribute.EntityTypeQualifierValue) ||
                        attribute.EntityTypeQualifierValue == qualifierValue)
                    {
                        attributes.Add(attribute);
                    }
                }
                GroupTypeAttributesState.Clear();
                GroupTypeAttributesState.AddAll(attributes);

                attributes = new List <Attribute>();
                foreach (var attribute in GroupAttributesState)
                {
                    if (string.IsNullOrWhiteSpace(attribute.EntityTypeQualifierValue) ||
                        attribute.EntityTypeQualifierValue == qualifierValue)
                    {
                        attributes.Add(attribute);
                    }
                }
                GroupAttributesState.Clear();
                GroupAttributesState.AddAll(attributes);
            }

            while (inheritedGroupTypeId.HasValue)
            {
                var inheritedGroupType = groupTypeService.Get(inheritedGroupTypeId.Value);
                if (inheritedGroupType != null)
                {
                    qualifierValue = inheritedGroupType.Id.ToString();

                    var qryGroupTypeAttributes = attributeService.GetByEntityTypeId(new GroupType().TypeId).AsQueryable()
                                                 .Where(a =>
                                                        a.EntityTypeQualifierColumn.Equals("Id", StringComparison.OrdinalIgnoreCase) &&
                                                        a.EntityTypeQualifierValue.Equals(qualifierValue));

                    var qryGroupAttributes = attributeService.GetByEntityTypeId(new Group().TypeId).AsQueryable()
                                             .Where(a =>
                                                    a.EntityTypeQualifierColumn.Equals("GroupTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(qualifierValue));

                    // TODO: Should probably add GroupTypeCache object so that it can be used during the
                    // databind of the attribute grids, instead of having to do this hack of putting
                    // the inherited group type name into the description property of the attribute
                    // (which is currently how the databound method gets the inherited attributes group type)
                    qryGroupTypeAttributes
                    .ToList()
                    .ForEach(a => a.Description = inheritedGroupType.Name);

                    qryGroupAttributes
                    .ToList()
                    .ForEach(a => a.Description = inheritedGroupType.Name);

                    GroupTypeAttributesState.InsertAll(qryGroupTypeAttributes
                                                       .OrderBy(a => a.Order)
                                                       .ThenBy(a => a.Name)
                                                       .ToList());

                    GroupAttributesState.InsertAll(qryGroupAttributes
                                                   .OrderBy(a => a.Order)
                                                   .ThenBy(a => a.Name)
                                                   .ToList());

                    inheritedGroupTypeId = inheritedGroupType.InheritedGroupTypeId;
                }
                else
                {
                    inheritedGroupTypeId = null;
                }
            }
        }
Exemple #4
0
        /// <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)
        {
            using (new UnitOfWorkScope())
            {
                GroupType        groupType;
                GroupTypeService groupTypeService = new GroupTypeService();
                AttributeService attributeService = new AttributeService();

                int groupTypeId = int.Parse(hfGroupTypeId.Value);

                if (groupTypeId == 0)
                {
                    groupType = new GroupType();
                    groupTypeService.Add(groupType, CurrentPersonId);
                }
                else
                {
                    groupType = groupTypeService.Get(groupTypeId);
                }

                groupType.Name = tbName.Text;

                groupType.Description            = tbDescription.Text;
                groupType.GroupTerm              = tbGroupTerm.Text;
                groupType.GroupMemberTerm        = tbGroupMemberTerm.Text;
                groupType.DefaultGroupRoleId     = ddlDefaultGroupRole.SelectedValueAsInt();
                groupType.ShowInGroupList        = cbShowInGroupList.Checked;
                groupType.ShowInNavigation       = cbShowInNavigation.Checked;
                groupType.IconCssClass           = tbIconCssClass.Text;
                groupType.IconSmallFileId        = imgIconSmall.ImageId;
                groupType.IconLargeFileId        = imgIconLarge.ImageId;
                groupType.TakesAttendance        = cbTakesAttendance.Checked;
                groupType.AttendanceRule         = ddlAttendanceRule.SelectedValueAsEnum <AttendanceRule>();
                groupType.AttendancePrintTo      = ddlAttendancePrintTo.SelectedValueAsEnum <PrintTo>();
                groupType.LocationSelectionMode  = ddlLocationSelectionMode.SelectedValueAsEnum <LocationPickerMode>();
                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);

                    // get it back to make sure we have a good Id for it for the Attributes
                    groupType = groupTypeService.Get(groupType.Guid);

                    /* Take care of Group Type Attributes */

                    // delete GroupTypeAttributes that are no longer configured in the UI
                    var groupTypeAttributesQry = attributeService.Get(new GroupType().TypeId, "Id", groupType.Id.ToString());
                    var selectedAttributes     = GroupTypeAttributesState.Select(a => a.Guid);
                    foreach (var attr in groupTypeAttributesQry.Where(a => !selectedAttributes.Contains(a.Guid)))
                    {
                        Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                        attributeService.Delete(attr, CurrentPersonId);
                        attributeService.Save(attr, CurrentPersonId);
                    }

                    string qualifierValue = groupType.Id.ToString();

                    // add/update the GroupTypeAttributes that are assigned in the UI
                    foreach (var attributeState in GroupTypeAttributesState
                             .Where(a =>
                                    a.EntityTypeQualifierValue == null ||
                                    a.EntityTypeQualifierValue.Trim() == string.Empty ||
                                    a.EntityTypeQualifierValue.Equals(qualifierValue)))
                    {
                        // remove old qualifiers in case they changed
                        var qualifierService = new AttributeQualifierService();
                        foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList())
                        {
                            qualifierService.Delete(oldQualifier, CurrentPersonId);
                            qualifierService.Save(oldQualifier, CurrentPersonId);
                        }

                        Attribute attribute = groupTypeAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid));
                        if (attribute == null)
                        {
                            attribute = attributeState.Clone() as Rock.Model.Attribute;
                            attributeService.Add(attribute, CurrentPersonId);
                        }
                        else
                        {
                            attributeState.Id = attribute.Id;
                            attribute.FromDictionary(attributeState.ToDictionary());

                            foreach (var qualifier in attributeState.AttributeQualifiers)
                            {
                                attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier);
                            }
                        }

                        attribute.EntityTypeQualifierColumn = "Id";
                        attribute.EntityTypeQualifierValue  = qualifierValue;
                        attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(GroupType)).Id;
                        Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                        attributeService.Save(attribute, CurrentPersonId);
                    }

                    /* Take care of Group Attributes */

                    // delete GroupAttributes that are no longer configured in the UI
                    var groupAttributesQry = attributeService.Get(new Group().TypeId, "GroupTypeId", groupType.Id.ToString());
                    selectedAttributes     = GroupAttributesState.Select(a => a.Guid);
                    foreach (var attr in groupAttributesQry.Where(a => !selectedAttributes.Contains(a.Guid)))
                    {
                        Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                        attributeService.Delete(attr, CurrentPersonId);
                        attributeService.Save(attr, CurrentPersonId);
                    }

                    // add/update the GroupAttributes that are assigned in the UI
                    foreach (var attributeState in GroupAttributesState
                             .Where(a =>
                                    a.EntityTypeQualifierValue == null ||
                                    a.EntityTypeQualifierValue.Trim() == string.Empty ||
                                    a.EntityTypeQualifierValue.Equals(qualifierValue)))
                    {
                        // remove old qualifiers in case they changed
                        var qualifierService = new AttributeQualifierService();
                        foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList())
                        {
                            qualifierService.Delete(oldQualifier, CurrentPersonId);
                            qualifierService.Save(oldQualifier, CurrentPersonId);
                        }

                        Attribute attribute = groupAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid));
                        if (attribute == null)
                        {
                            attribute = attributeState.Clone() as Rock.Model.Attribute;
                            attributeService.Add(attribute, CurrentPersonId);
                        }
                        else
                        {
                            attributeState.Id = attribute.Id;
                            attribute.FromDictionary(attributeState.ToDictionary());

                            foreach (var qualifier in attributeState.AttributeQualifiers)
                            {
                                attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier);
                            }
                        }

                        attribute.EntityTypeQualifierColumn = "GroupTypeId";
                        attribute.EntityTypeQualifierValue  = qualifierValue;
                        attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(Group)).Id;
                        Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                        attributeService.Save(attribute, CurrentPersonId);
                    }
                });
            }
            NavigateToParentPage();
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            GroupType groupType = null;

            var rockContext = new RockContext();
            GroupTypeService          groupTypeService          = new GroupTypeService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);

            int?groupTypeId = hfGroupTypeId.ValueAsInt();

            if (groupTypeId.HasValue && groupTypeId.Value > 0)
            {
                groupType = groupTypeService.Get(groupTypeId.Value);
            }

            bool newGroupType = false;

            if (groupType == null)
            {
                groupType = new GroupType();
                groupTypeService.Add(groupType);

                var templatePurpose = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid());
                if (templatePurpose != null)
                {
                    groupType.GroupTypePurposeValueId = templatePurpose.Id;
                }

                newGroupType = true;
            }

            if (groupType != null)
            {
                groupType.Name        = tbName.Text;
                groupType.Description = tbDescription.Text;

                groupType.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributeEdits, groupType);

                groupType.SetAttributeValue("core_checkin_AgeRequired", cbAgeRequired.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_GradeRequired", cbGradeRequired.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_HidePhotos", cbHidePhotos.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PreventDuplicateCheckin", cbPreventDuplicateCheckin.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PreventInactivePeople", cbPreventInactivePeople.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_CheckInType", ddlType.SelectedValue);
                groupType.SetAttributeValue("core_checkin_DisplayLocationCount", cbDisplayLocCount.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_EnableManagerOption", cbEnableManager.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_EnableOverride", cbEnableOverride.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_MaximumPhoneSearchLength", nbMaxPhoneLength.Text);
                groupType.SetAttributeValue("core_checkin_MaxSearchResults", nbMaxResults.Text);
                groupType.SetAttributeValue("core_checkin_MinimumPhoneSearchLength", nbMinPhoneLength.Text);
                groupType.SetAttributeValue("core_checkin_UseSameOptions", cbUseSameOptions.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PhoneSearchType", ddlPhoneSearchType.SelectedValue);
                groupType.SetAttributeValue("core_checkin_RefreshInterval", nbRefreshInterval.Text);
                groupType.SetAttributeValue("core_checkin_RegularExpressionFilter", tbSearchRegex.Text);
                groupType.SetAttributeValue("core_checkin_ReuseSameCode", cbReuseCode.Checked.ToString());

                var searchType = DefinedValueCache.Get(ddlSearchType.SelectedValueAsInt() ?? 0);
                if (searchType != null)
                {
                    groupType.SetAttributeValue("core_checkin_SearchType", searchType.Guid.ToString());
                }
                else
                {
                    groupType.SetAttributeValue("core_checkin_SearchType", Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER);
                }

                groupType.SetAttributeValue("core_checkin_SecurityCodeLength", nbCodeAlphaNumericLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeAlphaLength", nbCodeAlphaLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeNumericLength", nbCodeNumericLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeNumericRandom", cbCodeRandom.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_AllowCheckout", cbAllowCheckout.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_AutoSelectDaysBack", nbAutoSelectDaysBack.Text);
                groupType.SetAttributeValue("core_checkin_AutoSelectOptions", ddlAutoSelectOptions.SelectedValueAsInt());

                // Registration Settings

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORADULTS, cbRegistrationDisplayAlternateIdFieldForAdults.Checked.ToTrueFalse());
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORCHILDREN, cbRegistrationDisplayAlternateIdFieldForChildren.Checked.ToTrueFalse());

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORADULTS,
                    lbRegistrationRequiredAttributesForAdults.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORADULTS,
                    lbRegistrationOptionalAttributesForAdults.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORCHILDREN,
                    lbRegistrationRequiredAttributesForChildren.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORCHILDREN,
                    lbRegistrationOptionalAttributesForChildren.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORFAMILIES,
                    lbRegistrationRequiredAttributesForFamilies.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORFAMILIES,
                    lbRegistrationOptionalAttributesForFamilies.SelectedValues.AsDelimited(","));

                Guid?defaultPersonConnectionStatusValueGuid = null;
                var  defaultPersonConnectionStatusValueId   = dvpRegistrationDefaultPersonConnectionStatus.SelectedValue.AsIntegerOrNull();
                if (defaultPersonConnectionStatusValueId.HasValue)
                {
                    var defaultPersonConnectionStatusValue = DefinedValueCache.Get(defaultPersonConnectionStatusValueId.Value);
                    if (defaultPersonConnectionStatusValue != null)
                    {
                        defaultPersonConnectionStatusValueGuid = defaultPersonConnectionStatusValue.Guid;
                    }
                }

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTPERSONCONNECTIONSTATUS,
                    defaultPersonConnectionStatusValueGuid.ToString());

                var workflowTypeService = new WorkflowTypeService(rockContext);

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDFAMILYWORKFLOWTYPES,
                    workflowTypeService.GetByIds(wftpRegistrationAddFamilyWorkflowTypes.SelectedValuesAsInt().ToList()).Select(a => a.Guid).ToList().AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDPERSONWORKFLOWTYPES,
                    workflowTypeService.GetByIds(wftpRegistrationAddPersonWorkflowTypes.SelectedValuesAsInt().ToList()).Select(a => a.Guid).ToList().AsDelimited(","));

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ENABLECHECKINAFTERREGISTRATION, cbEnableCheckInAfterRegistration.Checked.ToTrueFalse());

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_KNOWNRELATIONSHIPTYPES, lbKnownRelationshipTypes.SelectedValues.AsDelimited(","));
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_SAMEFAMILYKNOWNRELATIONSHIPTYPES, lbSameFamilyKnownRelationshipTypes.SelectedValues.AsDelimited(","));
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_CANCHECKINKNOWNRELATIONSHIPTYPES, lbCanCheckInKnownRelationshipTypes.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_START_LAVA_TEMPLATE, ceStartTemplate.Text);
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_FAMILYSELECT_LAVA_TEMPLATE, ceFamilySelectTemplate.Text);
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_SUCCESS_LAVA_TEMPLATE, ceSuccessTemplate.Text);

                // Save group type and attributes
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    groupType.SaveAttributeValues(rockContext);
                });

                if (newGroupType)
                {
                    var pageRef = new PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId);
                    pageRef.Parameters.Add("CheckinTypeId", groupType.Id.ToString());
                    NavigateToPage(pageRef);
                }
                else
                {
                    groupType = groupTypeService.Get(groupType.Id);
                    ShowReadonlyDetails(groupType);
                }

                Rock.CheckIn.KioskDevice.Clear();
            }
        }
Exemple #6
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail(string itemKey, int itemKeyValue)
        {
            if (!itemKey.Equals("groupTypeId"))
            {
                return;
            }

            pnlDetails.Visible = true;
            GroupType groupType = null;

            using (new UnitOfWorkScope())
            {
                var groupTypeService = new GroupTypeService();
                var attributeService = new AttributeService();

                if (!itemKeyValue.Equals(0))
                {
                    groupType         = groupTypeService.Get(itemKeyValue);
                    lActionTitle.Text = ActionTitle.Edit(GroupType.FriendlyTypeName);
                }
                else
                {
                    groupType = new GroupType {
                        Id = 0, ShowInGroupList = true
                    };
                    groupType.ChildGroupTypes = new List <GroupType>();
                    groupType.LocationTypes   = new List <GroupTypeLocationType>();
                    lActionTitle.Text         = ActionTitle.Add(GroupType.FriendlyTypeName);
                }

                LoadDropDowns(groupType.Id);

                ChildGroupTypesDictionary = new Dictionary <int, string>();
                LocationTypesDictionary   = new Dictionary <int, string>();
                GroupTypeAttributesState  = new ViewStateList <Attribute>();
                GroupAttributesState      = new ViewStateList <Attribute>();

                hfGroupTypeId.Value    = groupType.Id.ToString();
                tbName.Text            = groupType.Name;
                tbDescription.Text     = groupType.Description;
                tbGroupTerm.Text       = groupType.GroupTerm;
                tbGroupMemberTerm.Text = groupType.GroupMemberTerm;
                ddlDefaultGroupRole.SetValue(groupType.DefaultGroupRoleId);
                cbShowInGroupList.Checked  = groupType.ShowInGroupList;
                cbShowInNavigation.Checked = groupType.ShowInNavigation;
                tbIconCssClass.Text        = groupType.IconCssClass;
                imgIconSmall.ImageId       = groupType.IconSmallFileId;
                imgIconLarge.ImageId       = groupType.IconLargeFileId;

                cbTakesAttendance.Checked = groupType.TakesAttendance;
                ddlAttendanceRule.SetValue((int)groupType.AttendanceRule);
                ddlAttendancePrintTo.SetValue((int)groupType.AttendancePrintTo);
                ddlLocationSelectionMode.SetValue((int)groupType.LocationSelectionMode);
                cbAllowMultipleLocations.Checked          = groupType.AllowMultipleLocations;
                gtpInheritedGroupType.SelectedGroupTypeId = groupType.InheritedGroupTypeId;
                groupType.ChildGroupTypes.ToList().ForEach(a => ChildGroupTypesDictionary.Add(a.Id, a.Name));
                groupType.LocationTypes.ToList().ForEach(a => LocationTypesDictionary.Add(a.LocationTypeValueId, a.LocationTypeValue.Name));

                string qualifierValue         = groupType.Id.ToString();
                var    qryGroupTypeAttributes = attributeService.GetByEntityTypeId(new GroupType().TypeId).AsQueryable()
                                                .Where(a =>
                                                       a.EntityTypeQualifierColumn.Equals("Id", StringComparison.OrdinalIgnoreCase) &&
                                                       a.EntityTypeQualifierValue.Equals(qualifierValue));

                var qryGroupAttributes = attributeService.GetByEntityTypeId(new Group().TypeId).AsQueryable()
                                         .Where(a =>
                                                a.EntityTypeQualifierColumn.Equals("GroupTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                a.EntityTypeQualifierValue.Equals(qualifierValue));

                GroupTypeAttributesState.AddAll(qryGroupTypeAttributes
                                                .OrderBy(a => a.Order)
                                                .ThenBy(a => a.Name)
                                                .ToList());

                GroupAttributesState.AddAll(qryGroupAttributes
                                            .OrderBy(a => a.Order)
                                            .ThenBy(a => a.Name)
                                            .ToList());

                if (groupType.InheritedGroupTypeId.HasValue)
                {
                    RebuildAttributeLists(groupType.InheritedGroupTypeId, groupTypeService, attributeService, false);
                }
            }

            BindGroupTypeAttributesGrid();
            BindGroupAttributesGrid();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized("Edit"))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(GroupType.FriendlyTypeName);
            }

            if (groupType.IsSystem)
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem(GroupType.FriendlyTypeName);
            }

            if (readOnly)
            {
                lActionTitle.Text = ActionTitle.View(GroupType.FriendlyTypeName);
                btnCancel.Text    = "Close";
            }

            ddlDefaultGroupRole.Enabled      = !readOnly;
            tbName.ReadOnly                  = readOnly;
            tbDescription.ReadOnly           = readOnly;
            tbGroupTerm.ReadOnly             = readOnly;
            tbGroupMemberTerm.ReadOnly       = readOnly;
            cbShowInGroupList.Enabled        = !readOnly;
            cbShowInNavigation.Enabled       = !readOnly;
            tbIconCssClass.ReadOnly          = readOnly;
            imgIconLarge.Enabled             = !readOnly;
            imgIconSmall.Enabled             = !readOnly;
            cbTakesAttendance.Enabled        = !readOnly;
            ddlAttendanceRule.Enabled        = !readOnly;
            ddlAttendancePrintTo.Enabled     = !readOnly;
            ddlLocationSelectionMode.Enabled = !readOnly;
            cbAllowMultipleLocations.Enabled = !readOnly;
            gtpInheritedGroupType.Enabled    = !readOnly;
            gGroupTypeAttributes.Enabled     = !readOnly;
            gGroupAttributes.Enabled         = !readOnly;

            gChildGroupTypes.Enabled = !readOnly;
            gLocationTypes.Enabled   = !readOnly;
            btnSave.Visible          = !readOnly;

            BindChildGroupTypesGrid();
            BindLocationTypesGrid();
        }
        private void SortRows(string eventParam, string[] values)
        {
            var groupTypeIds = new List <int>();

            using (var rockContext = new RockContext())
            {
                if (eventParam.Equals("re-order-area"))
                {
                    Guid groupTypeGuid = new Guid(values[0]);
                    int  newIndex      = int.Parse(values[1]);

                    var allRows   = phRows.ControlsOfTypeRecursive <CheckinAreaRow>();
                    var sortedRow = allRows.FirstOrDefault(a => a.GroupTypeGuid.Equals(groupTypeGuid));
                    if (sortedRow != null)
                    {
                        Control parentControl = sortedRow.Parent;

                        var siblingRows = allRows
                                          .Where(a => a.Parent.ClientID == sortedRow.Parent.ClientID)
                                          .ToList();

                        int oldIndex = siblingRows.IndexOf(sortedRow);

                        var groupTypeService = new GroupTypeService(rockContext);
                        var groupTypes       = new List <GroupType>();
                        foreach (var siblingGuid in siblingRows.Select(a => a.GroupTypeGuid))
                        {
                            var groupType = groupTypeService.Get(siblingGuid);
                            if (groupType != null)
                            {
                                groupTypes.Add(groupType);
                                groupTypeIds.Add(groupType.Id);
                            }
                        }

                        groupTypeService.Reorder(groupTypes, oldIndex, newIndex);
                    }
                }
                else if (eventParam.Equals("re-order-group"))
                {
                    Guid groupGuid = new Guid(values[0]);
                    int  newIndex  = int.Parse(values[1]);

                    var allRows   = phRows.ControlsOfTypeRecursive <CheckinGroupRow>();
                    var sortedRow = allRows.FirstOrDefault(a => a.GroupGuid.Equals(groupGuid));
                    if (sortedRow != null)
                    {
                        Control parentControl = sortedRow.Parent;

                        var siblingRows = allRows
                                          .Where(a => a.Parent.ClientID == sortedRow.Parent.ClientID)
                                          .ToList();

                        int oldIndex = siblingRows.IndexOf(sortedRow);

                        var groupService = new GroupService(rockContext);
                        var groups       = new List <Group>();
                        foreach (var siblingGuid in siblingRows.Select(a => a.GroupGuid))
                        {
                            var group = groupService.Get(siblingGuid);
                            if (group != null)
                            {
                                groups.Add(group);
                            }
                        }

                        groupService.Reorder(groups, oldIndex, newIndex);
                    }
                }

                rockContext.SaveChanges();
            }

            Rock.CheckIn.KioskDevice.Clear();

            BuildRows();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            KioskType kioskType = null;

            var rockContext      = new RockContext();
            var kioskTypeService = new KioskTypeService(rockContext);
            var attributeService = new AttributeService(rockContext);
            var locationService  = new LocationService(rockContext);
            var scheduleService  = new ScheduleService(rockContext);
            var groupTypeService = new GroupTypeService(rockContext);

            int kioskTypeId = int.Parse(hfKioskTypeId.Value);

            if (kioskTypeId != 0)
            {
                kioskType = kioskTypeService.Get(kioskTypeId);
            }

            if (kioskType == null)
            {
                kioskType = new KioskType();
                kioskTypeService.Add(kioskType);
            }

            if (kioskType != null)
            {
                kioskType.Name         = tbName.Text;
                kioskType.Description  = tbDescription.Text;
                kioskType.Message      = tbMessage.Text;
                kioskType.IsMobile     = cbIsMobile.Checked;
                kioskType.MinutesValid = tbMinutesValid.Text.AsIntegerOrNull();
                kioskType.GraceMinutes = tbGraceMinutes.Text.AsIntegerOrNull();
                kioskType.Theme        = ddlTheme.SelectedValue;

                if (!kioskType.IsValid || !Page.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                // Remove any deleted locations
                foreach (var location in kioskType.Locations
                         .Where(l =>
                                !Locations.Keys.Contains(l.Id))
                         .ToList())
                {
                    kioskType.Locations.Remove(location);
                }

                // Remove any deleted schedules
                foreach (var schedule in kioskType.Schedules
                         .Where(s =>
                                !Schedules.Keys.Contains(s.Id))
                         .ToList())
                {
                    kioskType.Schedules.Remove(schedule);
                }

                // Add any new locations
                var existingLocationIDs = kioskType.Locations.Select(l => l.Id).ToList();
                foreach (var location in locationService.Queryable()
                         .Where(l =>
                                Locations.Keys.Contains(l.Id) &&
                                !existingLocationIDs.Contains(l.Id)))
                {
                    kioskType.Locations.Add(location);
                }

                // Add any new schedules
                var existingScheduleIDs = kioskType.Schedules.Select(s => s.Id).ToList();
                foreach (var schedule in scheduleService.Queryable()
                         .Where(s =>
                                Schedules.Keys.Contains(s.Id) &&
                                !existingScheduleIDs.Contains(s.Id)))
                {
                    kioskType.Schedules.Add(schedule);
                }

                //Save checkin template
                kioskType.CheckinTemplateId = ddlTemplates.SelectedValue.AsInteger();


                var GroupTypes = kioskType.GroupTypes;
                GroupTypes.Clear();

                foreach (ListItem item in cblPrimaryGroupTypes.Items)
                {
                    if (item.Selected)
                    {
                        GroupTypes.Add(groupTypeService.Get(item.Value.AsInteger()));
                    }
                }

                kioskType.CampusId = ddlCampus.SelectedCampusId;

                rockContext.SaveChanges();

                KioskTypeCache.Remove(kioskType.Id);
                KioskTypeCache.Get(kioskType.Id);
                KioskDeviceHelpers.Clear(kioskType.GroupTypes.Select(gt => gt.Id).ToList());

                NavigateToParentPage();
            }
        }
Exemple #9
0
        /// <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;
            GroupTypeService groupTypeService = new GroupTypeService();

            int groupTypeId = int.Parse(hfGroupTypeId.Value);

            if (groupTypeId == 0)
            {
                groupType = new GroupType();
                groupTypeService.Add(groupType, CurrentPersonId);
            }
            else
            {
                groupType = groupTypeService.Get(groupTypeId);
            }

            groupType.Name = tbName.Text;
            if (ddlDefaultGroupRole.SelectedValue.Equals(None.Id.ToString()))
            {
                groupType.DefaultGroupRoleId = null;
            }
            else
            {
                groupType.DefaultGroupRoleId = int.Parse(ddlDefaultGroupRole.SelectedValue);
            }

            groupType.Description = tbDescription.Text;

            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
                    });
                }
            }

            // check for duplicates
            if (groupTypeService.Queryable().Count(a => a.Name.Equals(groupType.Name, StringComparison.OrdinalIgnoreCase) && !a.Id.Equals(groupType.Id)) > 0)
            {
                tbName.ShowErrorMessage(WarningMessage.DuplicateFoundMessage("name", GroupType.FriendlyTypeName));
                return;
            }

            if (!groupType.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            RockTransactionScope.WrapTransaction(() =>
            {
                groupTypeService.Save(groupType, CurrentPersonId);
            });

            BindGrid();
            pnlDetails.Visible = false;
            pnlList.Visible    = true;
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            hfAreaGroupClicked.Value = "true";

            using (var rockContext = new RockContext())
            {
                var attributeService = new AttributeService(rockContext);

                if (checkinArea.Visible)
                {
                    var groupTypeService = new GroupTypeService(rockContext);
                    var groupType        = groupTypeService.Get(checkinArea.GroupTypeGuid);
                    if (groupType != null)
                    {
                        groupType.LoadAttributes(rockContext);
                        checkinArea.GetGroupTypeValues(groupType);

                        if (groupType.IsValid)
                        {
                            rockContext.SaveChanges();
                            groupType.SaveAttributeValues(rockContext);

                            // rebuild the CheckinLabel attributes from the UI (brute-force)
                            foreach (var labelAttribute in CheckinArea.GetCheckinLabelAttributes(groupType.Attributes))
                            {
                                var attribute = attributeService.Get(labelAttribute.Value.Guid);
                                attributeService.Delete(attribute);
                            }

                            // Make sure default role is set
                            if (!groupType.DefaultGroupRoleId.HasValue && groupType.Roles.Any())
                            {
                                groupType.DefaultGroupRoleId = groupType.Roles.First().Id;
                            }

                            rockContext.SaveChanges();

                            int labelOrder            = 0;
                            int binaryFileFieldTypeID = FieldTypeCache.Get(Rock.SystemGuid.FieldType.LABEL.AsGuid()).Id;
                            foreach (var checkinLabelAttributeInfo in checkinArea.CheckinLabels)
                            {
                                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  = groupType.Id.ToString();
                                attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileGuid.ToString();
                                attribute.Key          = checkinLabelAttributeInfo.AttributeKey;
                                attribute.Name         = checkinLabelAttributeInfo.FileName;
                                attribute.Order        = labelOrder++;

                                if (!attribute.IsValid)
                                {
                                    return;
                                }

                                attributeService.Add(attribute);
                            }

                            rockContext.SaveChanges();

                            Rock.CheckIn.KioskDevice.Clear();

                            nbSaveSuccess.Visible = true;
                            BuildRows();
                        }
                        else
                        {
                            ShowInvalidResults(groupType.ValidationResults);
                        }
                    }
                }

                if (checkinGroup.Visible)
                {
                    var groupService         = new GroupService(rockContext);
                    var groupLocationService = new GroupLocationService(rockContext);

                    var group = groupService.Get(checkinGroup.GroupGuid);
                    if (group != null)
                    {
                        group.LoadAttributes(rockContext);
                        checkinGroup.GetGroupValues(group);

                        // populate groupLocations with whatever is currently in the grid, with just enough info to repopulate it and save it later
                        var newLocationIds = checkinGroup.Locations.Select(l => l.LocationId).ToList();
                        foreach (var groupLocation in group.GroupLocations.Where(l => !newLocationIds.Contains(l.LocationId)).ToList())
                        {
                            groupLocationService.Delete(groupLocation);
                            group.GroupLocations.Remove(groupLocation);
                        }

                        var existingLocationIds = group.GroupLocations.Select(g => g.LocationId).ToList();
                        foreach (var item in checkinGroup.Locations.Where(l => !existingLocationIds.Contains(l.LocationId)).ToList())
                        {
                            var groupLocation = new GroupLocation();
                            groupLocation.LocationId = item.LocationId;
                            group.GroupLocations.Add(groupLocation);
                        }

                        // Set the new order
                        foreach (var item in checkinGroup.Locations.OrderBy(l => l.Order).ToList())
                        {
                            var groupLocation = group.GroupLocations.FirstOrDefault(gl => gl.LocationId == item.LocationId);
                            groupLocation.Order = item.Order ?? 0;
                        }

                        if (group.IsValid)
                        {
                            rockContext.SaveChanges();
                            group.SaveAttributeValues(rockContext);

                            Rock.CheckIn.KioskDevice.Clear();
                            nbSaveSuccess.Visible = true;
                            BuildRows();
                        }
                        else
                        {
                            ShowInvalidResults(group.ValidationResults);
                        }
                    }
                }
            }

            hfIsDirty.Value = "false";
        }
Exemple #11
0
        /// <summary>
        /// Handels the Delete button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                if (checkinArea.Visible)
                {
                    GroupTypeService groupTypeService = new GroupTypeService(rockContext);
                    GroupType        groupType        = groupTypeService.Get(checkinArea.GroupTypeGuid);
                    if (groupType != null)
                    {
                        if (IsInheritedGroupTypeRecursive(groupType, groupTypeService))
                        {
                            nbDeleteWarning.Text    = "WARNING - Cannot delete. This group type or one of its child group types is assigned as an inherited group type.";
                            nbDeleteWarning.Visible = true;
                            return;
                        }

                        string errorMessage;
                        if (!groupTypeService.CanDelete(groupType, out errorMessage))
                        {
                            nbDeleteWarning.Text    = "WARNING - Cannot Delete: " + errorMessage;
                            nbDeleteWarning.Visible = true;
                            return;
                        }

                        int id = groupType.Id;

                        groupType.ParentGroupTypes.Clear();
                        groupType.ChildGroupTypes.Clear();
                        groupTypeService.Delete(groupType);
                        rockContext.SaveChanges();
                        GroupTypeCache.Flush(id);
                        Rock.CheckIn.KioskDevice.FlushAll();
                    }
                    SelectArea(null);
                }

                if (checkinGroup.Visible)
                {
                    GroupService groupService = new GroupService(rockContext);
                    Group        group        = groupService.Get(checkinGroup.GroupGuid);
                    if (group != null)
                    {
                        string errorMessage;
                        if (!groupService.CanDelete(group, out errorMessage))
                        {
                            nbDeleteWarning.Text    = "WARNING - Cannot Delete: " + errorMessage;
                            nbDeleteWarning.Visible = true;
                            return;
                        }


                        groupService.Delete(group);   //Delete if group isn't active
                        rockContext.SaveChanges();
                        Rock.CheckIn.KioskDevice.FlushAll();
                        SelectGroup(null);
                    }
                }
            }
            BuildRows();
        }
Exemple #12
0
        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>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            string[] options = selection.Split('|');
            if (options.Length < 4)
            {
                return(null);
            }

            Guid           groupTypeGuid  = options[0].AsGuid();
            ComparisonType comparisonType = options[1].ConvertToEnum <ComparisonType>(ComparisonType.GreaterThanOrEqualTo);
            int?           attended       = options[2].AsIntegerOrNull();
            string         slidingDelimitedValues;

            if (options[3].AsIntegerOrNull().HasValue)
            {
                //// selection was from when it just simply a LastXWeeks instead of Sliding Date Range
                // Last X Weeks was treated as "LastXWeeks * 7" days, so we have to convert it to a SlidingDateRange of Days to keep consistent behavior
                int lastXWeeks = options[3].AsIntegerOrNull() ?? 1;
                var fakeSlidingDateRangePicker = new SlidingDateRangePicker();
                fakeSlidingDateRangePicker.SlidingDateRangeMode = SlidingDateRangePicker.SlidingDateRangeType.Last;
                fakeSlidingDateRangePicker.TimeUnit             = SlidingDateRangePicker.TimeUnitType.Day;
                fakeSlidingDateRangePicker.NumberOfTimeUnits    = lastXWeeks * 7;
                slidingDelimitedValues = fakeSlidingDateRangePicker.DelimitedValues;
            }
            else
            {
                slidingDelimitedValues = options[3].Replace(',', '|');
            }

            var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues);

            bool includeChildGroupTypes = options.Length >= 5 ? options[4].AsBooleanOrNull() ?? false : false;

            var groupTypeService = new GroupTypeService(new RockContext());

            var        groupType    = groupTypeService.Get(groupTypeGuid);
            List <int> groupTypeIds = new List <int>();

            if (groupType != null)
            {
                groupTypeIds.Add(groupType.Id);

                if (includeChildGroupTypes)
                {
                    var childGroupTypes = groupTypeService.GetAllAssociatedDescendents(groupType.Guid);
                    if (childGroupTypes.Any())
                    {
                        groupTypeIds.AddRange(childGroupTypes.Select(a => a.Id));

                        // get rid of any duplicates
                        groupTypeIds = groupTypeIds.Distinct().ToList();
                    }
                }
            }

            var rockContext   = serviceInstance.Context as RockContext;
            var attendanceQry = new AttendanceService(rockContext).Queryable().Where(a => a.DidAttend.HasValue && a.DidAttend.Value);

            if (dateRange.Start.HasValue)
            {
                var startDate = dateRange.Start.Value;
                attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate >= startDate);
            }

            if (dateRange.End.HasValue)
            {
                var endDate = dateRange.End.Value;
                attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate < endDate);
            }

            if (groupTypeIds.Count == 1)
            {
                int groupTypeId = groupTypeIds[0];
                attendanceQry = attendanceQry.Where(a => a.Occurrence.Group.GroupTypeId == groupTypeId);
            }
            else if (groupTypeIds.Count > 1)
            {
                attendanceQry = attendanceQry.Where(a => groupTypeIds.Contains(a.Occurrence.Group.GroupTypeId));
            }
            else
            {
                // no group type selected, so return nothing
                return(Expression.Constant(false));
            }

            var qry = new PersonService(rockContext).Queryable()
                      .Where(p => attendanceQry.Where(xx => xx.PersonAlias.PersonId == p.Id).Count() == attended);

            BinaryExpression compareEqualExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p") as BinaryExpression;
            BinaryExpression result = FilterExpressionExtractor.AlterComparisonType(comparisonType, compareEqualExpression, null);

            return(result);
        }
Exemple #14
0
        /// <summary>
        /// Loads the <see cref="P:IHasAttributes.Attributes"/> and <see cref="P:IHasAttributes.AttributeValues"/> of any <see cref="IHasAttributes"/> object
        /// </summary>
        /// <param name="entity">The item.</param>
        public static void LoadAttributes(Rock.Attribute.IHasAttributes entity)
        {
            Dictionary <string, PropertyInfo> properties = new Dictionary <string, PropertyInfo>();

            Type entityType = entity.GetType();

            if (entityType.Namespace == "System.Data.Entity.DynamicProxies")
            {
                entityType = entityType.BaseType;
            }

            // Check for group type attributes
            var groupTypeIds = new List <int>();

            if (entity is GroupMember || entity is Group || entity is GroupType)
            {
                // Can't use GroupTypeCache here since it loads attributes and would result in a recursive stack overflow situation
                var       groupTypeService = new GroupTypeService();
                GroupType groupType        = null;

                if (entity is GroupMember)
                {
                    var group = ((GroupMember)entity).Group ?? new GroupService().Get(((GroupMember)entity).GroupId);
                    groupType = group.GroupType ?? groupTypeService.Get(group.GroupTypeId);
                }
                else if (entity is Group)
                {
                    groupType = ((Group)entity).GroupType ?? groupTypeService.Get(((Group)entity).GroupTypeId);
                }
                else
                {
                    groupType = ((GroupType)entity);
                }

                while (groupType != null)
                {
                    groupTypeIds.Insert(0, groupType.Id);

                    // Check for inherited group type id's
                    groupType = groupType.InheritedGroupType ?? groupTypeService.Get(groupType.InheritedGroupTypeId ?? 0);
                }
            }

            foreach (PropertyInfo propertyInfo in entityType.GetProperties())
            {
                properties.Add(propertyInfo.Name.ToLower(), propertyInfo);
            }

            Rock.Model.AttributeService      attributeService      = new Rock.Model.AttributeService();
            Rock.Model.AttributeValueService attributeValueService = new Rock.Model.AttributeValueService();

            var inheritedAttributes = new Dictionary <int, List <Rock.Web.Cache.AttributeCache> >();

            if (groupTypeIds.Any())
            {
                groupTypeIds.ForEach(g => inheritedAttributes.Add(g, new List <Rock.Web.Cache.AttributeCache>()));
            }
            else
            {
                inheritedAttributes.Add(0, new List <Rock.Web.Cache.AttributeCache>());
            }

            var attributes = new List <Rock.Web.Cache.AttributeCache>();

            // Get all the attributes that apply to this entity type and this entity's properties match any attribute qualifiers
            int?entityTypeId = Rock.Web.Cache.EntityTypeCache.Read(entityType).Id;

            foreach (Rock.Model.Attribute attribute in attributeService.GetByEntityTypeId(entityTypeId))
            {
                // group type ids exist (entity is either GroupMember, Group, or GroupType) and qualifier is for a group type id
                if (groupTypeIds.Any() && (
                        (entity is GroupMember && string.Compare(attribute.EntityTypeQualifierColumn, "GroupTypeId", true) == 0) ||
                        (entity is Group && string.Compare(attribute.EntityTypeQualifierColumn, "GroupTypeId", true) == 0) ||
                        (entity is GroupType && string.Compare(attribute.EntityTypeQualifierColumn, "Id", true) == 0)))
                {
                    int groupTypeIdValue = int.MinValue;
                    if (int.TryParse(attribute.EntityTypeQualifierValue, out groupTypeIdValue) && groupTypeIds.Contains(groupTypeIdValue))
                    {
                        inheritedAttributes[groupTypeIdValue].Add(Rock.Web.Cache.AttributeCache.Read(attribute));
                    }
                }

                else if (string.IsNullOrEmpty(attribute.EntityTypeQualifierColumn) ||
                         (properties.ContainsKey(attribute.EntityTypeQualifierColumn.ToLower()) &&
                          (string.IsNullOrEmpty(attribute.EntityTypeQualifierValue) ||
                           (properties[attribute.EntityTypeQualifierColumn.ToLower()].GetValue(entity, null) ?? "").ToString() == attribute.EntityTypeQualifierValue)))
                {
                    attributes.Add(Rock.Web.Cache.AttributeCache.Read(attribute));
                }
            }

            var allAttributes = new List <Rock.Web.Cache.AttributeCache>();

            foreach (var attributeGroup in inheritedAttributes)
            {
                foreach (var attribute in attributeGroup.Value)
                {
                    allAttributes.Add(attribute);
                }
            }
            foreach (var attribute in attributes)
            {
                allAttributes.Add(attribute);
            }

            var attributeValues = new Dictionary <string, List <Rock.Model.AttributeValue> >();

            if (allAttributes.Any())
            {
                foreach (var attribute in allAttributes)
                {
                    // Add a placeholder for this item's value for each attribute
                    attributeValues.Add(attribute.Key, new List <Rock.Model.AttributeValue>());
                }

                // Read this item's value(s) for each attribute
                List <int> attributeIds = allAttributes.Select(a => a.Id).ToList();
                foreach (var attributeValue in attributeValueService.Queryable("Attribute")
                         .Where(v => v.EntityId == entity.Id && attributeIds.Contains(v.AttributeId)))
                {
                    attributeValues[attributeValue.Attribute.Key].Add(attributeValue.Clone(false) as Rock.Model.AttributeValue);
                }

                // Look for any attributes that don't have a value and create a default value entry
                foreach (var attribute in allAttributes)
                {
                    if (attributeValues[attribute.Key].Count == 0)
                    {
                        var attributeValue = new Rock.Model.AttributeValue();
                        attributeValue.AttributeId = attribute.Id;
                        if (entity.AttributeValueDefaults != null && entity.AttributeValueDefaults.ContainsKey(attribute.Name))
                        {
                            attributeValue.Value = entity.AttributeValueDefaults[attribute.Name];
                        }
                        else
                        {
                            attributeValue.Value = attribute.DefaultValue;
                        }
                        attributeValues[attribute.Key].Add(attributeValue);
                    }
                    else
                    {
                        if (!String.IsNullOrWhiteSpace(attribute.DefaultValue))
                        {
                            foreach (var value in attributeValues[attribute.Key])
                            {
                                if (String.IsNullOrWhiteSpace(value.Value))
                                {
                                    value.Value = attribute.DefaultValue;
                                }
                            }
                        }
                    }
                }
            }

            entity.Attributes = new Dictionary <string, Web.Cache.AttributeCache>();
            allAttributes.ForEach(a => entity.Attributes.Add(a.Key, a));

            entity.AttributeValues = attributeValues;
        }
Exemple #15
0
        /// <summary>
        /// Loads the group data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadGroup(CSVInstance csvData)
        {
            // Required variables
            var lookupContext    = new RockContext();
            var locationService  = new LocationService(lookupContext);
            var groupTypeService = new GroupTypeService(lookupContext);

            var topicTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.SMALL_GROUP_TOPIC), lookupContext).DefinedValues;

            var numImportedGroups = ImportedGroups.Count();

            var newGroupLocations = new Dictionary <GroupLocation, string>();
            var currentGroup      = new Group();
            var newGroupList      = new List <Group>();

            // Look for custom attributes in the Individual file
            var allFields        = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList();
            var customAttributes = allFields
                                   .Where(f => f.index > GroupCapacity)
                                   .ToDictionary(f => f.index, f => f.node.Name);

            var groupAttributes = new AttributeService(lookupContext).GetByEntityTypeId(new Group().TypeId).ToList();
            var completed       = 0;

            ReportProgress(0, $"Starting group import ({numImportedGroups: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 rowGroupKey = row[GroupId];

                //
                // Determine if we are still working with the same group or not.
                //
                if (rowGroupKey != null && rowGroupKey != currentGroup.ForeignKey)
                {
                    currentGroup = LoadGroupBasic(lookupContext, rowGroupKey, row[GroupName], row[GroupCreatedDate], row[GroupType], row[GroupParentGroupId], row[GroupActive], row[GroupDescription]);

                    //
                    // Set the group campus
                    //
                    var campusName = row[GroupCampus];
                    if (!string.IsNullOrWhiteSpace(campusName))
                    {
                        var groupCampus = CampusList.FirstOrDefault(c => c.Name.Equals(campusName, StringComparison.InvariantCultureIgnoreCase) ||
                                                                    c.ShortCode.Equals(campusName, StringComparison.InvariantCultureIgnoreCase));
                        if (groupCampus == null)
                        {
                            groupCampus = new Campus
                            {
                                IsSystem  = false,
                                Name      = campusName,
                                ShortCode = campusName.RemoveWhitespace(),
                                IsActive  = true
                            };
                            lookupContext.Campuses.Add(groupCampus);
                            lookupContext.SaveChanges(DisableAuditing);
                            CampusList.Add(groupCampus);
                        }

                        currentGroup.CampusId = groupCampus.Id;
                    }

                    //
                    // If the group type has one or more location types defined then import the
                    // primary address as the first location type.
                    //
                    var groupType = groupTypeService.Get(currentGroup.GroupTypeId);
                    if (groupType.LocationTypes.Count > 0 && (!string.IsNullOrWhiteSpace(row[GroupAddress]) || !string.IsNullOrWhiteSpace(row[GroupNamedLocation])) && currentGroup.GroupLocations.Count == 0)
                    {
                        var primaryLocationTypeId = groupType.LocationTypes.ToList()[0].LocationTypeValueId;

                        var grpAddress  = row[GroupAddress];
                        var grpAddress2 = row[GroupAddress2];
                        var grpCity     = row[GroupCity];
                        var grpState    = row[GroupState];
                        var grpZip      = row[GroupZip];
                        var grpCountry  = row[GroupCountry];

                        var namedLocation = row[GroupNamedLocation];

                        if (string.IsNullOrWhiteSpace(namedLocation))
                        {
                            var primaryAddress = locationService.Get(grpAddress, grpAddress2, grpCity, grpState, grpZip, grpCountry, verifyLocation: false);

                            if (primaryAddress != null)
                            {
                                var primaryLocation = new GroupLocation
                                {
                                    LocationId               = primaryAddress.Id,
                                    IsMailingLocation        = true,
                                    IsMappedLocation         = true,
                                    GroupLocationTypeValueId = primaryLocationTypeId
                                };
                                newGroupLocations.Add(primaryLocation, rowGroupKey);
                            }
                        }
                        else
                        {
                            var primaryAddress = locationService.Queryable().FirstOrDefault(l => l.Name.Equals(namedLocation) || l.ForeignKey.Equals(namedLocation));
                            if (primaryAddress != null)
                            {
                                var primaryLocation = new GroupLocation
                                {
                                    LocationId               = primaryAddress.Id,
                                    IsMailingLocation        = true,
                                    IsMappedLocation         = true,
                                    GroupLocationTypeValueId = primaryLocationTypeId
                                };
                                newGroupLocations.Add(primaryLocation, rowGroupKey);
                            }
                            else
                            {
                                LogException("Group Import", string.Format("The named location {0} was not found and will not be mapped.", namedLocation));
                            }
                        }
                    }

                    //
                    // If the group type has two or more location types defined then import the
                    // secondary address as the group type's second location type.
                    //
                    if (groupType.LocationTypes.Count > 1 && !string.IsNullOrWhiteSpace(row[GroupSecondaryAddress]) && currentGroup.GroupLocations.Count < 2)
                    {
                        var secondaryLocationTypeId = groupType.LocationTypes.ToList()[1].LocationTypeValueId;

                        var grpSecondAddress  = row[GroupSecondaryAddress];
                        var grpSecondAddress2 = row[GroupSecondaryAddress2];
                        var grpSecondCity     = row[GroupSecondaryCity];
                        var grpSecondState    = row[GroupSecondaryState];
                        var grpSecondZip      = row[GroupSecondaryZip];
                        var grpSecondCountry  = row[GroupSecondaryCountry];

                        var secondaryAddress = locationService.Get(grpSecondAddress, grpSecondAddress2, grpSecondCity, grpSecondState, grpSecondZip, grpSecondCountry, verifyLocation: false);

                        if (secondaryAddress != null)
                        {
                            var secondaryLocation = new GroupLocation
                            {
                                LocationId               = secondaryAddress.Id,
                                IsMailingLocation        = true,
                                IsMappedLocation         = true,
                                GroupLocationTypeValueId = secondaryLocationTypeId
                            };
                            newGroupLocations.Add(secondaryLocation, rowGroupKey);
                        }
                    }

                    //
                    // Set the group's sorting order.
                    //
                    var groupOrder = 9999;
                    int.TryParse(row[GroupOrder], out groupOrder);
                    currentGroup.Order = groupOrder;

                    //
                    // Set the group's capacity
                    //
                    var capacity = row[GroupCapacity].AsIntegerOrNull();
                    if (capacity.HasValue)
                    {
                        currentGroup.GroupCapacity = capacity;

                        if (groupType.GroupCapacityRule == GroupCapacityRule.None)
                        {
                            groupType.GroupCapacityRule = GroupCapacityRule.Hard;
                        }
                    }

                    //
                    // Set the group's schedule
                    //
                    if (!string.IsNullOrWhiteSpace(row[GroupDayOfWeek]))
                    {
                        DayOfWeek dayEnum;
                        if (Enum.TryParse(row[GroupDayOfWeek], true, out dayEnum))
                        {
                            if (groupType.AllowedScheduleTypes != ScheduleType.Weekly)
                            {
                                groupType.AllowedScheduleTypes = ScheduleType.Weekly;
                            }
                            var day  = dayEnum;
                            var time = row[GroupTime].AsDateTime();
                            currentGroup.ScheduleId = AddNamedSchedule(lookupContext, string.Empty, string.Empty, day, time, null, rowGroupKey).Id;
                        }
                    }

                    //
                    // Assign Attributes
                    //
                    if (customAttributes.Any())
                    {
                        lookupContext.SaveChanges();

                        foreach (var attributePair in customAttributes)
                        {
                            var pairs                  = attributePair.Value.Split('^');
                            var categoryName           = string.Empty;
                            var attributeName          = string.Empty;
                            var attributeTypeString    = string.Empty;
                            var attributeForeignKey    = string.Empty;
                            var definedValueForeignKey = string.Empty;
                            var fieldTypeId            = TextFieldTypeId;

                            if (pairs.Length == 1)
                            {
                                attributeName = pairs[0];
                            }
                            else if (pairs.Length == 2)
                            {
                                attributeName       = pairs[0];
                                attributeTypeString = pairs[1];
                            }
                            else if (pairs.Length >= 3)
                            {
                                categoryName  = pairs[1];
                                attributeName = pairs[2];
                                if (pairs.Length >= 4)
                                {
                                    attributeTypeString = pairs[3];
                                }
                                if (pairs.Length >= 5)
                                {
                                    attributeForeignKey = pairs[4];
                                }
                                if (pairs.Length >= 6)
                                {
                                    definedValueForeignKey = pairs[5];
                                }
                            }

                            var definedValueForeignId = definedValueForeignKey.AsType <int?>();

                            //
                            // Translate the provided attribute type into one we know about.
                            //
                            fieldTypeId = GetAttributeFieldType(attributeTypeString);

                            Rock.Model.Attribute currentAttribute = null;
                            if (string.IsNullOrEmpty(attributeName))
                            {
                                LogException("Group Attribute", string.Format("Group Attribute Name cannot be blank '{0}'.", attributePair.Value));
                            }
                            else
                            {
                                if (string.IsNullOrWhiteSpace(attributeForeignKey))
                                {
                                    attributeForeignKey = string.Format("Bulldozer_{0}_{1}_{2}", groupType.Id, categoryName.RemoveWhitespace(), attributeName.RemoveWhitespace()).Left(100);
                                }
                                currentAttribute = groupAttributes.FirstOrDefault(a =>
                                                                                  a.Name.Equals(attributeName, StringComparison.OrdinalIgnoreCase) &&
                                                                                  a.FieldTypeId == fieldTypeId &&
                                                                                  a.EntityTypeId == currentGroup.TypeId &&
                                                                                  a.EntityTypeQualifierValue == groupType.Id.ToString()
                                                                                  );
                                if (currentAttribute == null)
                                {
                                    currentAttribute = AddEntityAttribute(lookupContext, currentGroup.TypeId, "GroupTypeId", groupType.Id.ToString(), attributeForeignKey, categoryName, attributeName, string.Empty, fieldTypeId, true, definedValueForeignId, definedValueForeignKey, attributeTypeString: attributeTypeString);
                                    groupAttributes.Add(currentAttribute);
                                }

                                var attributeValue = row[attributePair.Key];
                                if (!string.IsNullOrEmpty(attributeValue))
                                {
                                    AddEntityAttributeValue(lookupContext, currentAttribute, currentGroup, row[attributePair.Key], null, true);
                                }
                            }
                        }
                    }

                    //
                    // Changes to groups need to be saved right away since one group
                    // will reference another group.
                    //
                    lookupContext.SaveChanges();

                    //
                    // 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)
                    {
                        SaveGroups(newGroupList, newGroupLocations);
                        ReportPartialProgress();

                        // Reset lookup context
                        lookupContext.SaveChanges();
                        lookupContext    = new RockContext();
                        locationService  = new LocationService(lookupContext);
                        groupTypeService = new GroupTypeService(lookupContext);
                        newGroupList.Clear();
                        newGroupLocations.Clear();
                    }
                }
            }

            //
            // Check to see if any rows didn't get saved to the database
            //
            if (newGroupLocations.Any())
            {
                SaveGroups(newGroupList, newGroupLocations);
            }

            lookupContext.SaveChanges();
            lookupContext.Dispose();

            ReportProgress(0, $"Finished group import: {completed:N0} groups added or updated.");

            return(completed);
        }