示例#1
0
        /// <summary>
        /// Creates the control(s) neccessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns>
        /// The control
        /// </returns>
        public override System.Web.UI.Control EditControl( Dictionary<string, ConfigurationValue> configurationValues )
        {
            CheckBoxList editControl = new CheckBoxList();

            GroupTypeService groupTypeService = new GroupTypeService();
            var groupTypes = groupTypeService.Queryable().OrderBy( a => a.Name ).ToList();
            foreach ( var groupType in groupTypes )
            {
                editControl.Items.Add(new ListItem(groupType.Name, groupType.Id.ToString()));
            }

            return editControl;
        }
        /// <summary>
        /// Creates the HTML controls required to configure this type of field
        /// </summary>
        /// <returns></returns>
        public override List<Control> ConfigurationControls()
        {
            var controls = base.ConfigurationControls();

            // build a drop down list of defined types (the one that gets selected is
            // used to build a list of defined values) 
            var ddl = new RockDropDownList();
            controls.Add( ddl );
            ddl.AutoPostBack = true;
            ddl.SelectedIndexChanged += OnQualifierUpdated;
            ddl.Label = "Group Type";
            ddl.Help = "Type of group to select roles from, if left blank any group type's role can be selected.";

            ddl.Items.Add( new ListItem() );

            var groupTypeService = new GroupTypeService( new RockContext() );
            var groupTypes = groupTypeService.Queryable().OrderBy( a => a.Name ).ToList();
            groupTypes.ForEach( g =>
                ddl.Items.Add( new ListItem( g.Name, g.Id.ToString().ToUpper() ) )
            );

            return controls;
        }
示例#3
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>
        /// <param name="rockContext">The rock context.</param>
        public static void LoadAttributes( Rock.Attribute.IHasAttributes entity, RockContext rockContext )
        {
            if ( entity != null )
            {
                Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>();

                Type entityType = entity.GetType();
                if ( entityType.Namespace == "System.Data.Entity.DynamicProxies" )
                    entityType = entityType.BaseType;

                rockContext = rockContext ?? new RockContext();

                // 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( rockContext );
                    GroupType groupType = null;

                    if ( entity is GroupMember )
                    {
                        var group = ( (GroupMember)entity ).Group ?? new GroupService( rockContext )
                            .Queryable().AsNoTracking().FirstOrDefault(g => g.Id == ( (GroupMember)entity ).GroupId );
                        if ( group != null )
                        {
                            groupType = group.GroupType ?? groupTypeService
                                .Queryable().AsNoTracking().FirstOrDefault( t => t.Id == group.GroupTypeId );
                        }
                    }
                    else if ( entity is Group )
                    {
                        groupType = ( (Group)entity ).GroupType ?? groupTypeService
                            .Queryable().AsNoTracking().FirstOrDefault( t => t.Id == ( (Group)entity ).GroupTypeId );
                    }
                    else
                    {
                        groupType = ( (GroupType)entity );
                    }

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

                        // Check for inherited group type id's
                        if ( groupType.InheritedGroupTypeId.HasValue )
                        {
                            groupType = groupType.InheritedGroupType ?? groupTypeService
                                .Queryable().AsNoTracking().FirstOrDefault( t => t.Id == ( groupType.InheritedGroupTypeId ?? 0 ) );
                        }
                        else
                        {
                            groupType = null;
                        }
                    }

                }

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

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

                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
                var entityTypeCache = Rock.Web.Cache.EntityTypeCache.Read( entityType);
                if ( entityTypeCache != null )
                {
                    int entityTypeId = entityTypeCache.Id;
                    foreach ( var attribute in attributeService.Queryable()
                        .AsNoTracking()
                        .Where( a => a.EntityTypeId == entityTypeCache.Id )
                        .Select( a => new
                        {
                            a.Id,
                            a.EntityTypeQualifierColumn,
                            a.EntityTypeQualifierValue
                        }
                        ) )
                    {
                        // 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.Id ) );
                            }
                        }

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

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

                    // If loading attributes for a saved item, read the item's value(s) for each attribute 
                    if ( !entityTypeCache.IsEntity || entity.Id != 0 )
                    {
                        List<int> attributeIds = allAttributes.Select( a => a.Id ).ToList();
                        foreach ( var attributeValue in attributeValueService.Queryable().AsNoTracking()
                            .Where( v => v.EntityId == entity.Id && attributeIds.Contains( v.AttributeId ) ) )
                        {
                            var attributeKey = AttributeCache.Read( attributeValue.AttributeId ).Key;
                            attributeValues[attributeKey] = 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] == null )
                        {
                            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] = attributeValue;
                        }
                        else
                        {
                            if ( !String.IsNullOrWhiteSpace( attribute.DefaultValue ) &&
                                String.IsNullOrWhiteSpace( attributeValues[attribute.Key].Value ) )
                            {
                                attributeValues[attribute.Key].Value = attribute.DefaultValue;
                            }
                        }
                    }
                }

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

                entity.AttributeValues = attributeValues;
            }
        }
示例#4
0
        /// <summary>
        /// Maps the RLC data to rooms, locations & classes -- Mapping RLC Names as groups under check-in
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapRLC( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();

            // Add an Attribute for the unique F1 Ministry Id
            //int groupEntityTypeId = EntityTypeCache.Read("Rock.Model.Group").Id;
            //var rlcAttributeId = new AttributeService(lookupContext).Queryable().Where(a => a.EntityTypeId == groupEntityTypeId
            //    && a.Key == "F1RLCId").Select(a => a.Id).FirstOrDefault();

            //if (rlcAttributeId == 0)
            //{
            //    var newRLCAttribute = new Rock.Model.Attribute();
            //    newRLCAttribute.Key = "F1RLCId";
            //    newRLCAttribute.Name = "F1 RLC Id";
            //    newRLCAttribute.FieldTypeId = IntegerFieldTypeId;
            //    newRLCAttribute.EntityTypeId = groupEntityTypeId;
            //    newRLCAttribute.EntityTypeQualifierValue = string.Empty;
            //    newRLCAttribute.EntityTypeQualifierColumn = string.Empty;
            //    newRLCAttribute.Description = "The FellowshipOne identifier for the RLC Group that was imported";
            //    newRLCAttribute.DefaultValue = string.Empty;
            //    newRLCAttribute.IsMultiValue = false;
            //    newRLCAttribute.IsRequired = false;
            //    newRLCAttribute.Order = 0;

            //    lookupContext.Attributes.Add(newRLCAttribute);
            //    lookupContext.SaveChanges(DisableAudit);
            //    rlcAttributeId = newRLCAttribute.Id;
            //}

            // Get previously imported Ministries
            //var importedRLCs = new AttributeValueService(lookupContext).GetByAttributeId(rlcAttributeId)
            //    .Select(av => new { RLCId = av.Value.AsType<int?>(), RLCName = av.ForeignId })
            //    .ToDictionary(t => t.RLCId, t => t.RLCName);

            //List<AttributeValue> importedRLCAVList = new AttributeValueService( lookupContext ).GetByAttributeId( rlcAttributeId ).ToList(); //Not in use

            var newRLCGroupList = new List<Group>();

            var rlcAttributeValueList = new List<AttributeValue>();

            //Need a list of GroupTypes
            var gtService = new GroupTypeService( lookupContext );
            var existingGroupTypes = new List<GroupType>();
            existingGroupTypes = gtService.Queryable().ToList();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying RLC Group import ({0:N0} found).", totalRows ) );

            foreach ( var row in tableData )
            {
                int? rlcId = row["RLC_ID"] as int?;
                string rlcName = row["RLC_Name"] as string;
                string rlcStringId = Convert.ToString( rlcId );

                int? importedRLCs = new GroupService( lookupContext ).Queryable().Where( a => a.ForeignId == rlcStringId ).Select( a => a.Id ).FirstOrDefault();

                if ( rlcId != null && importedRLCs == 0 )
                {

                    if ( rlcName != null )
                    {
                        bool? rlcIsActive = row["Is_Active"] as bool?;
                        string roomName = row["Room_Name"] as string;
                        string maxCapacity = row["Max_Capacity"] as string;
                        string roomDescription = row["Room_Name"] as string;
                        string roomCode = row["Room_Code"] as string;
                        DateTime? startAgeDate = row["Start_Age_Date"] as DateTime?;
                        DateTime? endAgeDate = row["End_Age_Date"] as DateTime?;
                        int? activityId = row["Activity_ID"] as int?;

                        //Searches for Parent ActivityId
                        string activityStringId = activityId.ToString();
                        GroupType parentActivityArea = existingGroupTypes.Where( gt => gt.ForeignId == activityStringId ).FirstOrDefault();

                        if ( String.IsNullOrWhiteSpace( rlcName ) )
                        {
                            ReportProgress( 0, string.Format( "." ) );
                            rlcName = "Excavator Test";
                        }
                        var rlcGroup = new Group();
                        bool rlcIsActiveBool = (bool)rlcIsActive;

                        //Sets the Group values for RLC
                        rlcGroup.IsSystem = false;
                        rlcGroup.Name = rlcName.Trim();
                        rlcGroup.Order = 0;
                        //rlcGroup.Guid = new Guid();
                        rlcGroup.GroupTypeId = parentActivityArea.Id;
                        rlcGroup.IsActive = rlcIsActiveBool;
                        rlcGroup.Description = roomDescription;
                        rlcGroup.ForeignId = rlcStringId;
                        //rlcGroup.GroupLocations = new List<GroupLocation>();
                        //rlcGroup.GroupLocations.Add( CheckLocation( roomDescription ) );

                        var rlcAttributeValue = new AttributeValue();

                        //Sets the Attribute Values for RLC
                        //rlcAttributeValue.IsSystem = false;
                        //rlcAttributeValue.AttributeId = rlcAttributeId;
                        //rlcAttributeValue.Value = rlcStringId;
                        //rlcAttributeValue.ForeignId = rlcName.Trim();

                        //rlcAttributeValueList.Add(rlcAttributeValue);
                        newRLCGroupList.Add( rlcGroup );
                        completed++;

                        // Adds rlcGroup to newRLCGroup list
                        ReportProgress( 0, string.Format( "Parent Activity/Area: {1}  Group Added: {0}  IsActive: {2}.", rlcGroup.Name, parentActivityArea.Name, rlcGroup.IsActive ) );

                        if ( completed % percentage < 1 )
                        {
                            int percentComplete = completed / percentage;
                            ReportProgress( percentComplete, string.Format( "{0:N0} RLC/Groups imported ({1}% complete). ", completed, percentComplete ) );
                        }
                        else if ( completed % ReportingNumber < 1 )
                        {
                            var rockContext = new RockContext();
                            rockContext.WrapTransaction( () =>
                            {
                                rockContext.Configuration.AutoDetectChangesEnabled = false;
                                rockContext.AttributeValues.AddRange( rlcAttributeValueList );
                                rockContext.Groups.AddRange( newRLCGroupList );
                                rockContext.SaveChanges( DisableAudit );
                                newRLCGroupList.Clear();
                                rlcAttributeValueList.Clear();
                            } );

                            ReportPartialProgress();
                        }
                    }
                }
            }

            if ( newRLCGroupList.Any() )
            {
                var rockContext = new RockContext();
                rockContext.WrapTransaction( () =>
                {
                    rockContext.Configuration.AutoDetectChangesEnabled = false;
                    rockContext.AttributeValues.AddRange( rlcAttributeValueList );
                    rockContext.Groups.AddRange( newRLCGroupList );
                    rockContext.SaveChanges( DisableAudit );
                    newRLCGroupList.Clear();
                    rlcAttributeValueList.Clear();
                } );
            }
            ReportProgress( 100, string.Format( "Finished ministry and activity import: {0:N0} imported.", completed ) );
        }
        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlParentGroup 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 ddlParentGroup_SelectedIndexChanged( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            GroupTypeService groupTypeService = new GroupTypeService( rockContext );
            var groupTypeQry = groupTypeService.Queryable();

            // limit GroupType selection to what Block Attributes allow
            List<Guid> groupTypeGuids = GetAttributeValue( "GroupTypes" ).SplitDelimitedValues().Select( a => Guid.Parse( a ) ).ToList();
            if ( groupTypeGuids.Count > 0 )
            {
                groupTypeQry = groupTypeQry.Where( a => groupTypeGuids.Contains( a.Guid ) );
            }

            // next, limit GroupType to ChildGroupTypes that the ParentGroup allows
            int? parentGroupId = gpParentGroup.SelectedValueAsInt();
            if ( ( parentGroupId ?? 0 ) != 0 )
            {
                Group parentGroup = new GroupService( rockContext ).Queryable( "GroupType" ).Where( g => g.Id == parentGroupId.Value ).FirstOrDefault();
                List<int> allowedChildGroupTypeIds = parentGroup.GroupType.ChildGroupTypes.Select( a => a.Id ).ToList();
                groupTypeQry = groupTypeQry.Where( a => allowedChildGroupTypeIds.Contains( a.Id ) );
            }

            // limit to GroupTypes where ShowInNavigation=True depending on block setting
            if ( GetAttributeValue( "LimitToShowInNavigationGroupTypes" ).AsBoolean() )
            {
                groupTypeQry = groupTypeQry.Where( a => a.ShowInNavigation );
            }

            List<GroupType> groupTypes = groupTypeQry.OrderBy( a => a.Name ).ToList();
            if ( groupTypes.Count() > 1 )
            {
                // add a empty option so they are forced to choose
                groupTypes.Insert( 0, new GroupType { Id = 0, Name = string.Empty } );
            }

            // If the currently selected GroupType isn't an option anymore, set selected GroupType to null
            int? selectedGroupTypeId = ddlGroupType.SelectedValueAsInt();
            if ( ddlGroupType.SelectedValue != null )
            {
                if ( !groupTypes.Any( a => a.Id.Equals( selectedGroupTypeId ?? 0 ) ) )
                {
                    selectedGroupTypeId = null;
                }
            }

            ddlGroupType.DataSource = groupTypes;
            ddlGroupType.DataBind();

            if ( selectedGroupTypeId.HasValue )
            {
                ddlGroupType.SelectedValue = selectedGroupTypeId.ToString();
            }
            else
            {
                ddlGroupType.SelectedValue = null;
            }
        }
示例#6
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private void LoadDropDowns( ConnectionOpportunity connectionOpportunity )
        {
            cblCampus.Items.Clear();
            cblCampus.DataSource = CampusCache.All();
            cblCampus.DataBind();
            cblCampus.SetValues( connectionOpportunity.ConnectionOpportunityCampuses.Select( c => c.CampusId ).ToList() );
            // bind group types
            ddlGroupType.Items.Clear();

            using ( var rockContext = new RockContext() )
            {
                var groupTypeService = new Rock.Model.GroupTypeService( rockContext );

                // get all group types that have at least one role
                var groupTypes = groupTypeService.Queryable().Where( a => a.Roles.Any() ).OrderBy( a => a.Name ).ToList();

                foreach ( var g in groupTypes )
                {
                    ddlGroupType.Items.Add( new ListItem( g.Name, g.Id.ToString().ToUpper() ) );
                }
            }

            ddlGroupType.SetValue( connectionOpportunity.GroupTypeId.ToString() );
            LoadGroupRoles( ddlGroupType.SelectedValue.AsInteger() );
            ddlGroupRole.SetValue( connectionOpportunity.GroupMemberRoleId.ToString() );

            // bind group member status
            ddlGroupMemberStatus.BindToEnum<GroupMemberStatus>();
            if ( !String.IsNullOrWhiteSpace( connectionOpportunity.GroupMemberStatus.ToString() ) )
            {
                ddlGroupMemberStatus.SetValue( connectionOpportunity.GroupMemberStatus.ConvertToInt().ToString() );
            }
            else
            {
                ddlGroupMemberStatus.SetValue( GroupMemberStatus.Pending.ConvertToInt().ToString() );
            }
        }
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        public void LoadDropDowns()
        {
            clbCampuses.Items.Clear();
            var noCampusListItem = new ListItem();
            noCampusListItem.Text = "<span title='Include records that are not associated with a campus'>No Campus</span>";
            noCampusListItem.Value = "null";
            clbCampuses.Items.Add( noCampusListItem );
            foreach (var campus in CampusCache.All().OrderBy(a => a.Name))
            {
                var listItem = new ListItem();
                listItem.Text = campus.Name;
                listItem.Value = campus.Id.ToString();
                clbCampuses.Items.Add( listItem );
            }

            var groupTypeTemplateGuid = this.GetAttributeValue( "GroupTypeTemplate" ).AsGuidOrNull();
            if ( !groupTypeTemplateGuid.HasValue )
            {
                // show the CheckinType(GroupTypeTemplate) control if there isn't a block setting for it
                ddlAttendanceType.Visible = true;
                var groupTypeService = new GroupTypeService( _rockContext );
                Guid groupTypePurposeGuid = Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid();
                ddlAttendanceType.GroupTypes = groupTypeService.Queryable()
                        .Where( a => a.GroupTypePurposeValue.Guid == groupTypePurposeGuid )
                        .OrderBy( a => a.Order ).ThenBy( a => a.Name ).ToList();
            }
            else
            {
                // hide the CheckinType(GroupTypeTemplate) control if there is a block setting for it
                ddlAttendanceType.Visible = false;
            }
        }
        /// <summary>
        /// Creates the HTML controls required to configure this type of field
        /// </summary>
        /// <returns></returns>
        public override List<Control> ConfigurationControls()
        {
            var controls = base.ConfigurationControls();

            // build a drop down list of group types (the one that gets selected is
            // used to build a list of group location type defined values that the
            // group type allows) 
            var ddl = new RockDropDownList();
            controls.Add( ddl );
            ddl.AutoPostBack = true;
            ddl.SelectedIndexChanged += OnQualifierUpdated;
            ddl.Label = "Group Type";
            ddl.Help = "The Group Type to select location types from.";

            Rock.Model.GroupTypeService groupTypeService = new Model.GroupTypeService();
            foreach ( var groupType in groupTypeService.Queryable().OrderBy( g => g.Name ) )
            {
                ddl.Items.Add( new ListItem( groupType.Name, groupType.Guid.ToString() ) );
            }

            return controls;
        }
        /// <summary>
        /// Loads the groups.
        /// </summary>
        private void LoadDropDowns()
        {
            var groupEntityType = EntityTypeCache.Read( typeof( Group ) );
            var currentGroup = RockPage.GetCurrentContext( groupEntityType ) as Group;

            var groupIdString = Request.QueryString["groupId"];
            if ( groupIdString != null )
            {
                var groupId = groupIdString.AsInteger();

                if ( currentGroup == null || currentGroup.Id != groupId )
                {
                    currentGroup = SetGroupContext( groupId, false );
                }
            }

            var parts = ( GetAttributeValue( "GroupFilter" ) ?? string.Empty ).Split( '|' );
            Guid? groupTypeGuid = null;
            Guid? rootGroupGuid = null;

            if ( parts.Length >= 1 )
            {
                groupTypeGuid = parts[0].AsGuidOrNull();
                if ( parts.Length >= 2 )
                {
                    rootGroupGuid = parts[1].AsGuidOrNull();
                }
            }

            var rockContext = new RockContext();
            var groupService = new GroupService( rockContext );
            var groupTypeService = new GroupTypeService( rockContext );
            IQueryable<Group> qryGroups = null;

            // if rootGroup is set, use that as the filter.  Otherwise, use GroupType as the filter
            if ( rootGroupGuid.HasValue )
            {
                var rootGroup = groupService.Get( rootGroupGuid.Value );
                if ( rootGroup != null )
                {
                    qryGroups = groupService.GetAllDescendents( rootGroup.Id ).AsQueryable();
                }
            }
            else if ( groupTypeGuid.HasValue )
            {
                SetGroupTypeContext( groupTypeGuid );

                if ( GetAttributeValue( "IncludeGroupTypeChildren" ).AsBoolean() )
                {
                    var childGroupTypeGuids = groupTypeService.Queryable().Where( t => t.ParentGroupTypes.Select( p => p.Guid ).Contains( groupTypeGuid.Value ) )
                        .Select( t => t.Guid ).ToList();

                    qryGroups = groupService.Queryable().Where( a => childGroupTypeGuids.Contains( a.GroupType.Guid ) );
                }
                else
                {
                    qryGroups = groupService.Queryable().Where( a => a.GroupType.Guid == groupTypeGuid.Value );
                }
            }

            // no results
            if ( qryGroups == null )
            {
                nbSelectGroupTypeWarning.Visible = true;
                lCurrentSelection.Text = string.Empty;
                rptGroups.Visible = false;
            }
            else
            {
                nbSelectGroupTypeWarning.Visible = false;
                rptGroups.Visible = true;

                lCurrentSelection.Text = currentGroup != null ? currentGroup.ToString() : GetAttributeValue( "NoGroupText" );

                var groupList = qryGroups.OrderBy( a => a.Order )
                    .ThenBy( a => a.Name ).ToList()
                    .Select( a => new GroupItem() { Name = a.Name, Id = a.Id } )
                    .ToList();

                // check if the group can be unselected
                if ( !string.IsNullOrEmpty( GetAttributeValue( "ClearSelectionText" ) ) )
                {
                    var blankGroup = new GroupItem
                    {
                        Name = GetAttributeValue( "ClearSelectionText" ),
                        Id = Rock.Constants.All.Id
                    };

                    groupList.Insert( 0, blankGroup );
                }

                rptGroups.DataSource = groupList;
                rptGroups.DataBind();
            }
        }
        /// <summary>
        /// handles the connection opportunity group campuses_ show edit.
        /// </summary>
        /// <param name="connectionOpportunityGroupConfigsGuid">The connection opportunity group campus unique identifier.</param>
        protected void gConnectionOpportunityGroupConfigs_ShowEdit( Guid connectionOpportunityGroupConfigsGuid )
        {
            // bind group types
            ddlGroupType.Items.Clear();
            ddlGroupType.Items.Add( new ListItem() );

            using ( var rockContext = new RockContext() )
            {
                var groupTypeService = new Rock.Model.GroupTypeService( rockContext );

                // get all group types that have at least one role
                var groupTypes = groupTypeService.Queryable().Where( a => a.Roles.Any() ).OrderBy( a => a.Name ).ToList();

                foreach ( var g in groupTypes )
                {
                    ddlGroupType.Items.Add( new ListItem( g.Name, g.Id.ToString().ToUpper() ) );
                }
            }

            ddlGroupMemberStatus.BindToEnum<GroupMemberStatus>();

            var groupConfigStateObj = GroupConfigsState.FirstOrDefault( l => l.Guid.Equals( connectionOpportunityGroupConfigsGuid ) );
            if ( groupConfigStateObj != null )
            {
                hfGroupConfigGuid.Value = connectionOpportunityGroupConfigsGuid.ToString();

                ddlGroupType.SetValue( groupConfigStateObj.GroupTypeId );
                LoadGroupRoles( ddlGroupType.SelectedValue.AsInteger() );
                ddlGroupRole.SetValue( groupConfigStateObj.GroupMemberRoleId );

                ddlGroupMemberStatus.SetValue( groupConfigStateObj.GroupMemberStatus.ConvertToInt() );
                tglUseAllGroupsOfGroupType.Checked = groupConfigStateObj.UseAllGroupsOfType;
            }
            else
            {
                hfGroupConfigGuid.Value = string.Empty;
                LoadGroupRoles( null );
                ddlGroupMemberStatus.SetValue( GroupMemberStatus.Active.ConvertToInt() );
                tglUseAllGroupsOfGroupType.Checked = false;
            }

            ShowDialog( "GroupConfigDetails", true );
        }
        /// <summary>
        /// Gets the Attributes for a Group Member of a specific Group Type.
        /// </summary>
        /// <returns></returns>
        private List<EntityField> GetGroupMemberAttributes()
        {
            var entityAttributeFields = new Dictionary<string, EntityField>();
            var context = new RockContext();

            var attributeService = new AttributeService( context );
            var groupTypeService = new GroupTypeService( context );

            var groupMemberEntityTypeId = EntityTypeCache.GetId( typeof(Model.GroupMember) );

            var groupMemberAttributes = attributeService.Queryable()
                                                        .AsNoTracking()
                                                        .Where( a => a.EntityTypeId == groupMemberEntityTypeId )
                                                        .Join( groupTypeService.Queryable(), a => a.EntityTypeQualifierValue, gt => gt.Id.ToString(),
                                                               ( a, gt ) =>
                                                               new
                                                               {
                                                                   Attribute = a,
                                                                   AttributeKey = a.Key,
                                                                   FieldTypeName = a.FieldType.Name,
                                                                   a.FieldTypeId,
                                                                   AttributeName = a.Name,
                                                                   GroupTypeName = gt.Name
                                                               } )
                                                        .GroupBy( x => x.AttributeName )
                                                        .ToList();

            foreach (var attributesByName in groupMemberAttributes)
            {
                var attributeNameAndTypeGroups = attributesByName.GroupBy( x => x.FieldTypeId ).ToList();

                bool requiresTypeQualifier = ( attributeNameAndTypeGroups.Count > 1 );

                foreach (var attributeNameAndTypeGroup in attributeNameAndTypeGroups)
                {
                    foreach (var attribute in attributeNameAndTypeGroup)
                    {
                        string fieldKey;
                        string fieldName;

                        if (requiresTypeQualifier)
                        {
                            fieldKey = attribute.AttributeName + "_" + attribute.FieldTypeId;

                            fieldName = string.Format( "{0} [{1}]", attribute.AttributeName, attribute.FieldTypeName );
                        }
                        else
                        {
                            fieldName = attribute.AttributeName;
                            fieldKey = attribute.AttributeName;
                        }

                        if (entityAttributeFields.ContainsKey( fieldKey ))
                        {
                            continue;
                        }

                        var attributeCache = AttributeCache.Read( attribute.Attribute );

                        var entityField = EntityHelper.GetEntityFieldForAttribute( attributeCache );

                        entityField.Title = fieldName;
                        entityField.AttributeGuid = null;

                        entityAttributeFields.Add( fieldKey, entityField );
                    }
                }
            }

            int index = 0;
            var sortedFields = new List<EntityField>();
            foreach (var entityProperty in entityAttributeFields.Values.OrderBy( p => p.Title ).ThenBy( p => p.Name ))
            {
                entityProperty.Index = index;
                index++;
                sortedFields.Add( entityProperty );
            }

            return sortedFields;
        }
 private GroupType GetParentGroupType(GroupType groupType)
 {
     GroupTypeService groupTypeService = new GroupTypeService(_rockContext);
     return groupTypeService.Queryable()
                         .Include(t => t.ParentGroupTypes)
                         .AsNoTracking()
                         .Where(t => t.ChildGroupTypes.Select(p => p.Id).Contains(groupType.Id)).FirstOrDefault();
 }
        private GroupType GetRootGroupType(int groupId)
        {
            List<int> parentRecursionHistory = new List<int>();
            GroupTypeService groupTypeService = new GroupTypeService(_rockContext);
            var groupType = groupTypeService.Queryable().AsNoTracking().Include(t => t.ParentGroupTypes).Where(t => t.Groups.Select(g => g.Id).Contains(groupId)).FirstOrDefault();

            while (groupType != null && groupType.ParentGroupTypes.Count != 0)
            {
                if (parentRecursionHistory.Contains(groupType.Id))
                {
                    var exception = new Exception("Infinite Recursion detected in GetRootGroupType for groupId: " + groupId.ToString());
                    LogException(exception);
                    return null;
                }
                else
                {
                    var parentGroupType = GetParentGroupType(groupType);
                    if (parentGroupType != null && parentGroupType.Id == groupType.Id)
                    {
                        // the group type's parent is itself
                        return groupType;
                    }

                    groupType = parentGroupType;
                }

                parentRecursionHistory.Add(groupType.Id);
            }

            return groupType;
        }
        private void BuildHeirarchy(Guid parentGroupTypeGuid)
        {
            GroupTypeService groupTypeService = new GroupTypeService(_rockContext);

            var groupTypes = groupTypeService.Queryable("Groups, ChildGroupTypes").AsNoTracking()
                            .Where(t => t.ParentGroupTypes.Select(p => p.Guid).Contains(parentGroupTypeGuid) && t.Guid != parentGroupTypeGuid).ToList();

            foreach (var groupType in groupTypes)
            {
                if (groupType.GroupTypePurposeValueId == null || groupType.Groups.Count > 0)
                {
                    _content.Append("<ul>");
                    _content.Append(string.Format("<li><strong>{0}</strong></li>", groupType.Name));
                    if (groupType.ChildGroupTypes.Count > 0)
                    {
                        BuildHeirarchy(groupType.Guid);
                    }

                    _content.Append("<ul>");
                    foreach (var group in groupType.Groups)
                    {
                        if (!string.IsNullOrWhiteSpace(GetAttributeValue("GroupDetailPage")))
                        {
                            var groupPageParams = new Dictionary<string, string>();
                            if (Request["GroupTypeId"] != null)
                            {
                                groupPageParams.Add("GroupTypeId", Request["GroupTypeId"]);
                            }
                            groupPageParams.Add("GroupId", group.Id.ToString());
                            _content.Append(string.Format("<li><a href='{0}'>{1}</a></li>", LinkedPageUrl("GroupDetailPage", groupPageParams), group.Name));
                        }
                        else
                        {
                            _content.Append(string.Format("<li>{0}</li>", group.Name));
                        }
                    }
                    _content.Append("</ul>");

                    _content.Append("</ul>");
                }
                else
                {
                    BuildHeirarchy(groupType.Guid);
                }

            }
        }
示例#15
0
    /// <summary>
    /// Loads the drop downs.
    /// </summary>
    private void LoadDropDowns()
    {
        GroupTypeService groupTypeService = new GroupTypeService();
        var groupTypeQry = groupTypeService.Queryable();

        // limit GroupType selection to what Block Attributes allow
        List<int> groupTypeIds = AttributeValue( "GroupTypes" ).SplitDelimitedValues().Select( a => int.Parse( a ) ).ToList();
        if ( groupTypeIds.Count > 0 )
        {
            groupTypeQry = groupTypeQry.Where( a => groupTypeIds.Contains( a.Id ) );
        }

        List<GroupType> groupTypes = groupTypeQry.OrderBy( a => a.Name ).ToList();
        ddlGroupType.DataSource = groupTypes;
        ddlGroupType.DataBind();

        int currentGroupId = int.Parse( hfGroupId.Value );

        // TODO: Only include valid Parent choices (no circular references)
        GroupService groupService = new GroupService();
        List<Group> groups = groupService.Queryable().Where( g => g.Id != currentGroupId ).OrderBy( a => a.Name ).ToList();
        groups.Insert( 0, new Group { Id = None.Id, Name = None.Text } );
        ddlParentGroup.DataSource = groups;
        ddlParentGroup.DataBind();

        CampusService campusService = new CampusService();
        List<Campus> campuses = campusService.Queryable().OrderBy( a => a.Name ).ToList();
        campuses.Insert( 0, new Campus { Id = None.Id, Name = None.Text } );
        ddlCampus.DataSource = campuses;
        ddlCampus.DataBind();
    }
示例#16
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        public void LoadDropDowns()
        {
            cpCampuses.Campuses = CampusCache.All();

            var groupTypeTemplateGuid = this.GetAttributeValue( "GroupTypeTemplate" ).AsGuidOrNull();
            if ( !groupTypeTemplateGuid.HasValue )
            {
                // show the CheckinType(GroupTypeTemplate) control if there isn't a block setting for it
                ddlCheckinType.Visible = true;
                var groupTypeService = new GroupTypeService( _rockContext );
                Guid groupTypePurposeGuid = Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid();
                ddlCheckinType.GroupTypes = groupTypeService.Queryable()
                        .Where( a => a.GroupTypePurposeValue.Guid == groupTypePurposeGuid )
                        .OrderBy( a => a.Order ).ThenBy( a => a.Name ).ToList();
            }
            else
            {
                // hide the CheckinType(GroupTypeTemplate) control if there is a block setting for it
                ddlCheckinType.Visible = false;
            }
        }
示例#17
0
        /// <summary>
        /// Gets the available group types.
        /// </summary>
        /// <returns></returns>
        private List<int> GetAvailableGroupTypes()
        {
            var groupTypeIds = new List<int>();

            var groupTypeService = new GroupTypeService( new RockContext() );
            var qry = groupTypeService.Queryable().Where( t => t.ShowInGroupList );

            List<Guid> includeGroupTypeGuids = GetAttributeValue( "IncludeGroupTypes" ).SplitDelimitedValues().Select( a => Guid.Parse( a ) ).ToList();
            if ( includeGroupTypeGuids.Count > 0 )
            {
                _groupTypesCount = includeGroupTypeGuids.Count;
                qry = qry.Where( t => includeGroupTypeGuids.Contains( t.Guid ) );
            }

            List<Guid> excludeGroupTypeGuids = GetAttributeValue( "ExcludeGroupTypes" ).SplitDelimitedValues().Select( a => Guid.Parse( a ) ).ToList();
            if ( excludeGroupTypeGuids.Count > 0 )
            {
                qry = qry.Where( t => !excludeGroupTypeGuids.Contains( t.Guid ) );
            }

            foreach ( int groupTypeId in qry.Select( t => t.Id ) )
            {
                var groupType = GroupTypeCache.Read( groupTypeId );
                if ( groupType != null && groupType.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                {
                    groupTypeIds.Add( groupTypeId );
                }
            }

            // If there's only one group type, use it's 'group term' in the panel title.
            if ( groupTypeIds.Count == 1 )
            {
                var singleGroupType = GroupTypeCache.Read( groupTypeIds.FirstOrDefault() );
                lTitle.Text = string.Format( "{0}", singleGroupType.GroupTerm.Pluralize() );
                iIcon.AddCssClass( singleGroupType.IconCssClass );
            }
            else
            {
                iIcon.AddCssClass( "fa fa-users" );
            }

            groupTypeIds = qry.Select( t => t.Id ).ToList();

            return groupTypeIds;
        }
        /// <summary>
        /// Binds any needed data to the Grid Filter also using the user's stored
        /// preferences.
        /// </summary>
        private void BindFilter()
        {
            ddlGroupType.Items.Clear();
            ddlGroupType.Items.Add( Rock.Constants.All.ListItem );

            // populate the GroupType DropDownList only with GroupTypes with GroupTypePurpose of Checkin Template
            int groupTypePurposeCheckInTemplateId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE ) ).Id;

            var rockContext = new RockContext();

            GroupTypeService groupTypeService = new GroupTypeService( rockContext );
            var groupTypeList = groupTypeService.Queryable()
                .Where( a => a.GroupTypePurposeValueId == groupTypePurposeCheckInTemplateId )
                .ToList();
            foreach ( var groupType in groupTypeList )
            {
                ddlGroupType.Items.Add( new ListItem( groupType.Name, groupType.Id.ToString() ) );
            }

            ddlGroupType.SetValue( rFilter.GetUserPreference( "Group Type" ) );

            // hide the GroupType filter if this page has a groupTypeId parameter
            int? groupTypeIdPageParam = this.PageParameter( "groupTypeId" ).AsIntegerOrNull();
            if ( groupTypeIdPageParam.HasValue )
            {
                ddlGroupType.Visible = false;
            }

            var filterCategory = new CategoryService( rockContext ).Get( rFilter.GetUserPreference( "Category" ).AsInteger() );
            pCategory.SetValue( filterCategory );

            pkrParentLocation.SetValue( rFilter.GetUserPreference( "Parent Location" ).AsIntegerOrNull() );
        }
示例#19
0
        private void BindCheckinTypes( int? selectedValue )
        {
            ddlCheckinType.Items.Clear();

            if ( ddlKiosk.SelectedValue != None.IdValue )
            {
                using ( var rockContext = new RockContext() )
                {
                    var kioskCheckinTypes = new List<GroupType>();

                    var kioskGroupTypes = GetDeviceGroupTypes( ddlKiosk.SelectedValueAsInt() ?? 0, rockContext );
                    var kioskGroupTypeIds = kioskGroupTypes.Select( t => t.Id ).ToList();

                    var groupTypeService = new GroupTypeService( rockContext );

                    Guid templateTypeGuid = Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid();
                    ddlCheckinType.DataSource = groupTypeService
                        .Queryable().AsNoTracking()
                        .Where( t =>
                            t.GroupTypePurposeValue != null &&
                            t.GroupTypePurposeValue.Guid == templateTypeGuid )
                        .OrderBy( t => t.Name )
                        .Select( t => new
                        {
                            t.Name,
                            t.Id
                        } )
                        .ToList();
                    ddlCheckinType.DataBind();
                }

                if ( selectedValue.HasValue )
                {
                    ddlCheckinType.SetValue( selectedValue );
                }
                else
                {
                    if ( CurrentCheckinTypeId.HasValue )
                    {
                        ddlCheckinType.SetValue( CurrentCheckinTypeId );
                    }
                    else
                    {
                        var groupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_WEEKLY_SERVICE_CHECKIN_AREA.AsGuid() );
                        if ( groupType != null  )
                        {
                            ddlCheckinType.SetValue( groupType.Id );
                        }
                    }
                }
            }
        }
示例#20
0
        /// <summary>
        /// Determines whether [is inherited group type recursive] [the specified group type].
        /// </summary>
        /// <param name="groupType">Type of the group.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private bool IsInheritedGroupTypeRecursive( GroupType groupType, GroupTypeService groupTypeService, List<int> typesChecked = null )
        {
            // Track the groups that have been checked since group types can have themselves as a child
            typesChecked = typesChecked ?? new List<int>();
            if ( !typesChecked.Contains( groupType.Id ) )
            {
                typesChecked.Add( groupType.Id );

                if ( groupTypeService.Queryable().Any( a => a.InheritedGroupType.Guid == groupType.Guid ) )
                {
                    return true;
                }

                foreach ( var childGroupType in groupType.ChildGroupTypes.Where( t => !typesChecked.Contains( t.Id ) ) )
                {
                    if ( IsInheritedGroupTypeRecursive( childGroupType, groupTypeService, typesChecked ) )
                    {
                        return true;
                    }
                }
            }

            return false;
        }
        /// <summary>
        /// Gets the available group types.
        /// </summary>
        /// <returns></returns>
        private List<int> GetAvailableGroupTypes()
        {
            var groupTypeIds = new List<int>();

            var groupTypeService = new GroupTypeService( new RockContext() );
            var qry = groupTypeService.Queryable().Where( t => t.ShowInGroupList );

            List<Guid> includeGroupTypeGuids = GetAttributeValue( "IncludeGroupTypes" ).SplitDelimitedValues().Select( a => Guid.Parse( a ) ).ToList();
            if ( includeGroupTypeGuids.Count > 0 )
            {
                qry = qry.Where( t => includeGroupTypeGuids.Contains( t.Guid ) );
            }

            List<Guid> excludeGroupTypeGuids = GetAttributeValue( "ExcludeGroupTypes" ).SplitDelimitedValues().Select( a => Guid.Parse( a ) ).ToList();
            if ( excludeGroupTypeGuids.Count > 0 )
            {
                qry = qry.Where( t => !excludeGroupTypeGuids.Contains( t.Guid ) );
            }

            foreach ( int groupTypeId in qry.Select( t => t.Id ) )
            {
                var groupType = GroupTypeCache.Read( groupTypeId );
                if ( groupType != null && groupType.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                {
                    groupTypeIds.Add( groupTypeId );
                }
            }

            groupTypeIds = qry.Select( t => t.Id ).ToList();

            return groupTypeIds;
        }
        /// <summary>
        /// Gets the allowed group types.
        /// </summary>
        /// <param name="parentGroup">The parent group.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private IQueryable<GroupType> GetAllowedGroupTypes( Group parentGroup, RockContext rockContext )
        {
            rockContext = rockContext ?? new RockContext();

            GroupTypeService groupTypeService = new GroupTypeService( rockContext );

            var groupTypeQry = groupTypeService.Queryable();

            // limit GroupType selection to what Block Attributes allow
            List<Guid> groupTypeIncludeGuids = GetAttributeValue( "GroupTypes" ).SplitDelimitedValues().AsGuidList();
            List<Guid> groupTypeExcludeGuids = GetAttributeValue( "GroupTypesExclude" ).SplitDelimitedValues().AsGuidList();
            if ( groupTypeIncludeGuids.Any() )
            {
                groupTypeQry = groupTypeQry.Where( a => groupTypeIncludeGuids.Contains( a.Guid ) );
            }
            else if (groupTypeExcludeGuids.Any())
            {
                groupTypeQry = groupTypeQry.Where( a => !groupTypeExcludeGuids.Contains( a.Guid ) );
            }

            // next, limit GroupType to ChildGroupTypes that the ParentGroup allows
            if ( parentGroup != null )
            {
                List<int> allowedChildGroupTypeIds = parentGroup.GroupType.ChildGroupTypes.Select( a => a.Id ).ToList();
                groupTypeQry = groupTypeQry.Where( a => allowedChildGroupTypeIds.Contains( a.Id ) );
            }

            // limit to GroupTypes where ShowInNavigation=True depending on block setting
            if ( GetAttributeValue( "LimitToShowInNavigationGroupTypes" ).AsBoolean() )
            {
                groupTypeQry = groupTypeQry.Where( a => a.ShowInNavigation );
            }

            return groupTypeQry;
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        protected void BindGrid()
        {
            AddScheduleColumns();

            var rockContext = new RockContext();

            var groupLocationService = new GroupLocationService( rockContext );
            var groupTypeService = new GroupTypeService( rockContext );
            IEnumerable<GroupTypePath> groupPaths = new List<GroupTypePath>();
            var groupLocationQry = groupLocationService.Queryable();
            int groupTypeId;

            // if this page has a PageParam for groupTypeId use that to limit which groupTypeId to see. Otherwise, use the groupTypeId specified in the filter
            int? groupTypeIdPageParam = this.PageParameter( "groupTypeId" ).AsIntegerOrNull();
            if ( groupTypeIdPageParam.HasValue )
            {
                groupTypeId = groupTypeIdPageParam ?? Rock.Constants.All.Id;
            }
            else
            {
                groupTypeId = ddlGroupType.SelectedValueAsInt() ?? Rock.Constants.All.Id;
            }

            if ( groupTypeId != Rock.Constants.All.Id )
            {
                var descendantGroupTypeIds = groupTypeService.GetAllAssociatedDescendents( groupTypeId ).Select( a => a.Id );

                // filter to groups that either are of the GroupType or are of a GroupType that has the selected GroupType as a parent (ancestor)
                groupLocationQry = groupLocationQry.Where( a => a.Group.GroupType.Id == groupTypeId || descendantGroupTypeIds.Contains( a.Group.GroupTypeId ) );

                groupPaths = groupTypeService.GetAllAssociatedDescendentsPath( groupTypeId );
            }
            else
            {
                // if no specific GroupType is specified, show all GroupTypes with GroupTypePurpose of Checkin Template and their descendents (since this blocktype is specifically for Checkin)
                int groupTypePurposeCheckInTemplateId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE ) ).Id;
                List<int> descendantGroupTypeIds = new List<int>();
                foreach ( var templateGroupType in groupTypeService.Queryable().Where( a => a.GroupTypePurposeValueId == groupTypePurposeCheckInTemplateId ) )
                {
                    foreach ( var childGroupType in groupTypeService.GetChildGroupTypes( templateGroupType.Id ) )
                    {
                        descendantGroupTypeIds.Add( childGroupType.Id );
                        descendantGroupTypeIds.AddRange( groupTypeService.GetAllAssociatedDescendents( childGroupType.Id ).Select( a => a.Id ).ToList() );
                    }
                }

                groupLocationQry = groupLocationQry.Where( a => descendantGroupTypeIds.Contains( a.Group.GroupTypeId ) );
            }

            if ( gGroupLocationSchedule.SortProperty != null )
            {
                groupLocationQry = groupLocationQry.Sort( gGroupLocationSchedule.SortProperty );
            }
            else
            {
                groupLocationQry = groupLocationQry.OrderBy( a => a.Group.Name ).ThenBy( a => a.Location.Name );
            }

            var qryList = groupLocationQry.Select( a =>
                new
                {
                    GroupLocationId = a.Id,
                    GroupName = a.Group.Name,
                    LocationName = a.Location.Name,
                    ScheduleIdList = a.Schedules.Select( s => s.Id ),
                    a.LocationId,
                    GroupTypeId = a.Group.GroupTypeId
                } ).ToList();

            int parentLocationId = pkrParentLocation.SelectedValueAsInt() ?? Rock.Constants.All.Id;
            if ( parentLocationId != Rock.Constants.All.Id )
            {
                var descendantLocationIds = new LocationService( rockContext ).GetAllDescendents( parentLocationId ).Select( a => a.Id );
                qryList = qryList.Where( a => descendantLocationIds.Contains( a.LocationId ) ).ToList();
            }

            // put stuff in a datatable so we can dynamically have columns for each Schedule
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add( "GroupLocationId" );
            dataTable.Columns.Add( "GroupName" );
            dataTable.Columns.Add( "LocationName" );
            dataTable.Columns.Add( "Path" );
            foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() )
            {
                dataTable.Columns.Add( field.DataField, typeof( bool ) );
            }

            foreach ( var row in qryList )
            {
                DataRow dataRow = dataTable.NewRow();
                dataRow["GroupLocationId"] = row.GroupLocationId;
                dataRow["GroupName"] = row.GroupName;
                dataRow["LocationName"] = row.LocationName;
                dataRow["Path"] = groupPaths.Where( gt => gt.GroupTypeId == row.GroupTypeId ).Select( gt => gt.Path ).FirstOrDefault();
                foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() )
                {
                    int scheduleId = int.Parse( field.DataField.Replace( "scheduleField_", string.Empty ) );
                    dataRow[field.DataField] = row.ScheduleIdList.Any( a => a == scheduleId );
                }

                dataTable.Rows.Add( dataRow );
            }

            gGroupLocationSchedule.DataSource = dataTable;
            gGroupLocationSchedule.DataBind();
        }
示例#24
0
        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlParentGroup 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 ddlParentGroup_SelectedIndexChanged( object sender, EventArgs e )
        {
            GroupTypeService groupTypeService = new GroupTypeService();
            var groupTypeQry = groupTypeService.Queryable();

            // limit GroupType selection to what Block Attributes allow
            List<Guid> groupTypeGuids = GetAttributeValue( "GroupTypes" ).SplitDelimitedValues().Select( a => Guid.Parse( a ) ).ToList();
            if ( groupTypeGuids.Count > 0 )
            {
                groupTypeQry = groupTypeQry.Where( a => groupTypeGuids.Contains( a.Guid ) );
            }

            // next, limit GroupType to ChildGroupTypes that the ParentGroup allows
            int? parentGroupId = gpParentGroup.SelectedValueAsInt();
            if ( ( parentGroupId ?? 0 ) != 0 )
            {
                Group parentGroup = new GroupService().Get( parentGroupId.Value );
                List<int> allowedChildGroupTypeIds = parentGroup.GroupType.ChildGroupTypes.Select( a => a.Id ).ToList();
                groupTypeQry = groupTypeQry.Where( a => allowedChildGroupTypeIds.Contains( a.Id ) );
            }

            List<GroupType> groupTypes = groupTypeQry.OrderBy( a => a.Name ).ToList();
            if ( groupTypes.Count() > 1 )
            {
                // add a empty option so they are forced to choose
                groupTypes.Insert( 0, new GroupType { Id = 0, Name = string.Empty } );
            }

            // If the currently selected GroupType isn't an option anymore, set selected GroupType to null
            if ( ddlGroupType.SelectedValue != null )
            {
                int? selectedGroupTypeId = ddlGroupType.SelectedValueAsInt();
                if ( !groupTypes.Any( a => a.Id.Equals( selectedGroupTypeId ?? 0 ) ) )
                {
                    ddlGroupType.SelectedValue = null;
                }
            }

            ddlGroupType.DataSource = groupTypes;
            ddlGroupType.DataBind();
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            using ( var rockContext = new RockContext() )
            {
                GroupTypeService groupTypeService = new GroupTypeService( rockContext );
                SortProperty sortProperty = gGroupType.SortProperty;

                var qry = groupTypeService.Queryable();

                // limit to show only GroupTypes that have a group type purpose of Checkin Template
                int groupTypePurposeCheckInTemplateId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE ) ).Id;
                qry = qry.Where( a => a.GroupTypePurposeValueId == groupTypePurposeCheckInTemplateId );

                if ( sortProperty != null )
                {
                    gGroupType.DataSource = qry.Sort( sortProperty ).ToList();
                }
                else
                {
                    gGroupType.DataSource = qry.OrderBy( p => p.Name ).ToList();
                }

                gGroupType.DataBind();
            }
        }
示例#26
0
        /// <summary>
        /// Maps the activity ministry.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapActivityMinistry( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            var rockContext = new RockContext();

            // Add an Attribute for the unique F1 Ministry Id
            //int groupEntityTypeId = EntityTypeCache.Read("Rock.Model.Group").Id;
            //var ministryAttributeId = new AttributeService(lookupContext).Queryable().Where(a => a.EntityTypeId == groupEntityTypeId
            //    && a.Key == "F1MinistryId").Select(a => a.Id).FirstOrDefault();
            //var activityAttributeId = new AttributeService(lookupContext).Queryable().Where(a => a.EntityTypeId == groupEntityTypeId
            //    && a.Key == "F1ActivityId").Select(a => a.Id).FirstOrDefault();

            //if (ministryAttributeId == 0)
            //{
            //    var newMinistryAttribute = new Rock.Model.Attribute();
            //    newMinistryAttribute.Key = "F1MinistryId";
            //    newMinistryAttribute.Name = "F1 Ministry Id";
            //    newMinistryAttribute.FieldTypeId = IntegerFieldTypeId;
            //    newMinistryAttribute.EntityTypeId = groupEntityTypeId;
            //    newMinistryAttribute.EntityTypeQualifierValue = string.Empty;
            //    newMinistryAttribute.EntityTypeQualifierColumn = string.Empty;
            //    newMinistryAttribute.Description = "The FellowshipOne identifier for the ministry that was imported";
            //    newMinistryAttribute.DefaultValue = string.Empty;
            //    newMinistryAttribute.IsMultiValue = false;
            //    newMinistryAttribute.IsRequired = false;
            //    newMinistryAttribute.Order = 0;

            //    lookupContext.Attributes.Add(newMinistryAttribute);
            //    lookupContext.SaveChanges(DisableAudit);
            //    ministryAttributeId = newMinistryAttribute.Id;
            //}
            //if (activityAttributeId == 0)
            //{
            //    var newActivityAttribute = new Rock.Model.Attribute();
            //    newActivityAttribute.Key = "F1ActivityId";
            //    newActivityAttribute.Name = "F1 Activity Id";
            //    newActivityAttribute.FieldTypeId = IntegerFieldTypeId;
            //    newActivityAttribute.EntityTypeId = groupEntityTypeId;
            //    newActivityAttribute.EntityTypeQualifierValue = string.Empty;
            //    newActivityAttribute.EntityTypeQualifierColumn = string.Empty;
            //    newActivityAttribute.Description = "The FellowshipOne identifier for the activity that was imported";
            //    newActivityAttribute.DefaultValue = string.Empty;
            //    newActivityAttribute.IsMultiValue = false;
            //    newActivityAttribute.IsRequired = false;
            //    newActivityAttribute.Order = 0;

            //    lookupContext.Attributes.Add(newActivityAttribute);
            //    lookupContext.SaveChanges(DisableAudit);
            //    activityAttributeId = newActivityAttribute.Id;
            //}

            //// Get previously imported Ministries
            //List<AttributeValue> importedMinistriesAVList = new AttributeValueService(lookupContext).GetByAttributeId(ministryAttributeId).ToList();

            //// Get previously imported Activities
            //List<AttributeValue> importedActivitiesAVList = new AttributeValueService( lookupContext ).GetByAttributeId( activityAttributeId ).ToList();

            //int importedMinistriesCount = 0;
            //int importedActivitiesCount = 0;

            //if ( importedMinistriesAVList.Any() ) { importedMinistriesCount = importedMinistriesAVList.Count(); }
            //if ( importedActivitiesAVList.Any() ) { importedActivitiesCount = importedActivitiesAVList.Count(); }
            var orderMax = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Order != 0).ToList();
            int order = orderMax.Max(o => o.Order) + 1;

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;

            ReportProgress( 0, string.Format( "Verifying ministry import ({0:N0} found).", totalRows ) );
            //ReportProgress(0, string.Format("Previously Imported Ministries ({0:N0} found).", importedMinistriesCount));
            //ReportProgress(0, string.Format("Previously Imported Activities ({0:N0} found).", importedActivitiesCount));

            var newAreas = new List<GroupType>();
            var newCategories = new List<GroupType>();

            foreach ( var row in tableData )
            {
                int? ministryId = row["Ministry_ID"] as int?;
                string ministryName = row["Ministry_Name"] as string;
                string ministryIdString = Convert.ToString( ministryId );

                //GroupType importedMinistriesGTList = new GroupTypeService( lookupContext ).Queryable().Where( g => g.Name == ministryName && g.ForeignId == ( Convert.ToString( ministryId ) + 'm' ) ).FirstOrDefault();
                int? importedMinistry = new GroupTypeService( lookupContext ).Queryable().Where( a => a.ForeignId == ministryIdString ).Select( a => a.Id ).FirstOrDefault();
                //AttributeValue importedMinistry = new AttributeValueService(lookupContext).Queryable().Where(a => a.Value == Convert.ToString(ministryId) && a.ForeignId == ministryName).FirstOrDefault();
                //AttributeValue importedMinistry = importedMinistriesAVList.Where(av => av.Value == Convert.ToString(ministryId)).FirstOrDefault();
                // if (ministryId != null && !importedMinistries.ContainsKey(ministryId)) //Checks AttributeValue table to see if it has already been imported.
                //if ( ministryId != null && importedMinistriesAVList.Find( x => x.Value == Convert.ToString( ministryId ) ) == null ) //Checks AttributeValue table to see if it has already been imported.
                if ( ministryId != null && importedMinistry == 0 ) //Checks AttributeValue table to see if it has already been imported.
                {

                    bool? ministryIsActive = row["Ministry_Active"] as bool?;

                    if ( ministryName != null )
                    {

                        var ministryCategory = new GroupType();

                        var ministryAttribute = new AttributeValue();
                        var ministryAttributeList = new List<AttributeValue>();

                        //Creates the GroupType data
                        ministryCategory.IsSystem = false;
                        ministryCategory.Name = ministryName.Trim();
                        ministryCategory.GroupTerm = "Group";
                        ministryCategory.GroupMemberTerm = "Member";
                        ministryCategory.AllowMultipleLocations = false;
                        ministryCategory.ShowInGroupList = true;
                        ministryCategory.ShowInNavigation = false;
                        ministryCategory.TakesAttendance = false;
                        ministryCategory.AttendanceRule = 0;
                        ministryCategory.AttendancePrintTo = 0;
                        ministryCategory.Order = order;
                        ministryCategory.LocationSelectionMode = 0;
                        ministryCategory.Guid = Guid.NewGuid();
                        ministryCategory.ForeignId = ministryIdString; //F1 Ministry ID
                        ministryCategory.GroupTypePurposeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE ).Id; // ID = 142 in my db

                        //Creates the AttributeValue data for the Ministry
                        //ministryAttribute.IsSystem = false;
                        //ministryAttribute.AttributeId = ministryAttributeId;
                        //ministryAttribute.Value = ministryId.ToString();    //So the Value is the F1MinistryID
                        //ministryAttribute.Guid = Guid.NewGuid();
                        //ministryAttribute.ForeignId = ministryName.Trim();

                        newCategories.Add( ministryCategory );
                        //ministryAttributeList.Add(ministryAttribute);

                        //Saves it to the DB so that I can check for its ID in the table
                        if ( newCategories.Any() || ministryAttributeList.Any() )
                        {
                            //var rockContext = new RockContext();
                            if ( newCategories.Any() )
                            {
                                //var rockContext = new RockContext();
                                rockContext.WrapTransaction( () =>
                                {
                                    rockContext.Configuration.AutoDetectChangesEnabled = false;
                                    rockContext.GroupTypes.AddRange( newCategories );
                                    rockContext.SaveChanges( DisableAudit );
                                } );
                                newCategories.Clear();
                                order++;
                            }
                            //if ( ministryAttributeList.Any() )
                            //{
                            //    //var rockContext = new RockContext();
                            //    rockContext.WrapTransaction( () =>
                            //    {
                            //        rockContext.Configuration.AutoDetectChangesEnabled = false;
                            //        rockContext.AttributeValues.AddRange( ministryAttributeList );
                            //        rockContext.SaveChanges( DisableAudit );
                            //    } );
                            //    ministryAttributeList.Clear();
                            //}
                        }
                    }
                }

                //Checks AttributeValue table to see if it has already been imported.
                int? activityId = row["Activity_ID"] as int?;
                string activityName = row["Activity_Name"] as string;
                string activityIdString = Convert.ToString( activityId );
                ReportProgress( 0, string.Format( "Ministry ID {0}   Activity ID {1}.", ministryId, activityId ) );

                //if (activityId != null && !importedActivities.ContainsKey(activityId))
                int? importedActivity = new GroupTypeService( lookupContext ).Queryable().Where( a => a.ForeignId == activityIdString ).Select( a => a.Id ).FirstOrDefault();
                //AttributeValue importedActivity = new AttributeValueService( lookupContext ).Queryable().Where( a => a.Value == Convert.ToString( activityId ) && a.ForeignId == activityName ).FirstOrDefault();
                //AttributeValue importedActivity = importedActivitiesAVList.Where( av => av.Value == Convert.ToString( activityId ) ).FirstOrDefault();
                //if ( activityId != null && importedActivitiesAVList.Find(x => x.Value == Convert.ToString(activityId)) == null )
                if ( activityId != null && importedActivity == 0 )
                {

                    bool? activityIsActive = row["Activity_Active"] as bool?;

                    //Looking up the Ministry GroupType ID so it can be used as the ParentGroupTypeId for the Activity GroupType/Area
                    var gtService = new GroupTypeService( lookupContext );
                    int parentGroupTypeId;

                    string ministryID = ministryId.ToString();
                    parentGroupTypeId = gtService.Queryable().Where( gt => gt.ForeignId == ministryID ).FirstOrDefault().Id;

                    var parentGroupType = new GroupTypeService( rockContext ).Get( parentGroupTypeId );

                    var activityArea = new GroupType();
                    var activityAV = new AttributeValue();
                    var activityAVList = new List<AttributeValue>();

                    // create new GroupType for activity (will set this as child to Ministry/Category)
                    activityArea.IsSystem = false;
                    activityArea.Name = activityName.Trim();
                    activityArea.GroupTerm = "Group";
                    activityArea.GroupMemberTerm = "Member";

                    //Setup Group role Id
                    var memberRole = new GroupTypeRole();
                    memberRole.Name = "Member";
                    memberRole.Description = "Member of Group Type: " + activityName.Trim();

                    activityArea.Roles.Add( memberRole );
                    //activityArea.DefaultGroupRoleId = activityArea.Roles.ElementAt(0).Id;

                    activityArea.AllowMultipleLocations = true;
                    activityArea.ShowInGroupList = true;
                    activityArea.ShowInNavigation = false;
                    activityArea.TakesAttendance = true;
                    activityArea.AttendanceRule = 0;
                    activityArea.AttendancePrintTo = 0;
                    activityArea.Order = order;
                    activityArea.LocationSelectionMode = 0;
                    activityArea.Guid = Guid.NewGuid();
                    activityArea.ForeignId = activityIdString;  //F1 Activity ID

                    //Sets GroupTypeAssociation for the Categories and Areas
                    activityArea.ParentGroupTypes = new List<GroupType>();
                    activityArea.ParentGroupTypes.Add( parentGroupType );

                    //Create Activity AttributeValue Data
                    //activityAV.IsSystem = false;
                    //activityAV.Guid = Guid.NewGuid();
                    //activityAV.AttributeId = activityAttributeId;
                    //activityAV.Value = activityId.ToString();
                    //activityAV.ForeignId = activityName;

                    //activityAVList.Add(activityAV);
                    newAreas.Add( activityArea );
                    completed++;

                    if ( newAreas.Any() || activityAVList.Any() )
                    {
                        //var rockContext = new RockContext();
                        if ( newAreas.Any() )
                        {
                            rockContext.WrapTransaction( () =>
                            {
                                rockContext.Configuration.AutoDetectChangesEnabled = false;
                                rockContext.GroupTypes.AddRange( newAreas );
                                rockContext.SaveChanges( DisableAudit );
                            } );
                            newAreas.Clear();
                            order++;
                        }
                        //if ( activityAVList.Any() )
                        //{
                        //    //var rockContext = new RockContext();
                        //    rockContext.WrapTransaction( () =>
                        //    {
                        //        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        //        rockContext.AttributeValues.AddRange( activityAVList );
                        //        rockContext.SaveChanges( DisableAudit );
                        //    } );
                        //    activityAVList.Clear();
                        //}
                    }
                }
                if ( completed % percentage < 1 )
                {
                    int percentComplete = completed / percentage;
                    ReportProgress( percentComplete, string.Format( "{0:N0} ministries imported ({1}% complete). Categories: {2:N0} Areas: {3:N0}", completed, percentComplete, newCategories.Count, newAreas.Count ) );
                }
                else if ( completed % ReportingNumber < 1 )
                {
                    //var rockContext = new RockContext();
                    //rockContext.WrapTransaction(() =>
                    //{
                    //    rockContext.Configuration.AutoDetectChangesEnabled = false;
                    //    rockContext.GroupTypes.AddRange(newCategories);
                    //    rockContext.GroupTypes.AddRange(newAreas);
                    //    rockContext.SaveChanges(DisableAudit);
                    //});

                    ReportPartialProgress();
                }
            }
            //if (newAreas.Any())
            //{
            //    //var rockContext = new RockContext();
            //    rockContext.WrapTransaction(() =>
            //    {
            //        rockContext.Configuration.AutoDetectChangesEnabled = false;
            //        rockContext.GroupTypes.AddRange(newAreas);
            //        rockContext.SaveChanges(DisableAudit);
            //    });
            //}
            ReportProgress(100, string.Format("Finished ministry import: {0:N0} ministries imported. ", completed) );
            //ReportProgress( 0, string.Format( "Categories: {0}  Areas: {1}", importedMinistriesAVList.Count(), importedActivitiesAVList.Count() ) );
        }
        /// <summary>
        /// Handles the Add event of the gChildGroupTypes 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 gChildGroupTypes_Add( object sender, EventArgs e )
        {
            GroupTypeService groupTypeService = new GroupTypeService( new RockContext() );
            int currentGroupTypeId = int.Parse( hfGroupTypeId.Value );

            // populate dropdown with all grouptypes that aren't already childgroups
            var qry = from gt in groupTypeService.Queryable()
                      where !( from cgt in ChildGroupTypesDictionary.Keys
                               select cgt ).Contains( gt.Id )
                      select gt;

            List<GroupType> list = qry.ToList();
            if ( list.Count == 0 )
            {
                modalAlert.Show( "There are not any other group types that can be added", ModalAlertType.Warning );
            }
            else
            {
                ddlChildGroupType.DataSource = list;
                ddlChildGroupType.DataBind();
                ShowDialog( "ChildGroupTypes" );
            }
        }
示例#28
0
        /// <summary>
        /// Creates a Linq Expression that can be applied to an IQueryable to filter the result set.
        /// </summary>
        /// <param name="entityType">The type of entity in the result set.</param>
        /// <param name="serviceInstance">A service instance that can be queried to obtain the result set.</param>
        /// <param name="parameterExpression">The input parameter that will be injected into the filter expression.</param>
        /// <param name="selection">A formatted string representing the filter settings.</param>
        /// <returns>
        /// A Linq Expression that can be used to filter an IQueryable.
        /// </returns>
        /// <exception cref="System.Exception">Filter issue(s):  + errorMessages.AsDelimited( ;  )</exception>
        public override Expression GetExpression( Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection )
        {
            var settings = new FilterSettings( selection );

            var context = (RockContext)serviceInstance.Context;

            // Get the GroupType Data View that defines the set of candidates from which proximate GroupTypes can be selected.
            var dataView = DataComponentSettingsHelper.GetDataViewForFilterComponent( settings.DataViewGuid, context );

            // Evaluate the Data View that defines the candidate GroupTypes.
            var GroupTypeService = new GroupTypeService( context );

            var GroupTypeQuery = GroupTypeService.Queryable();

            if ( dataView != null )
            {
                GroupTypeQuery = DataComponentSettingsHelper.FilterByDataView( GroupTypeQuery, dataView, GroupTypeService );
            }

            // Get all of the Groups corresponding to the qualifying Group Types.
            var qry = new GroupService( context ).Queryable()
                                                  .Where( g => GroupTypeQuery.Any( gt => gt.Id == g.GroupTypeId ) );

            // Retrieve the Filter Expression.
            var extractedFilterExpression = FilterExpressionExtractor.Extract<Model.Group>( qry, parameterExpression, "g" );

            return extractedFilterExpression;
        }
示例#29
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        protected void BindGrid()
        {
            AddScheduleColumns();

            var rockContext = new RockContext();

            var groupLocationService = new GroupLocationService( rockContext );
            var groupTypeService = new GroupTypeService( rockContext );
            var groupService = new GroupService( rockContext );

            IEnumerable<GroupTypePath> groupPaths = new List<GroupTypePath>();
            var groupLocationQry = groupLocationService.Queryable();

            List<int> currentAndDescendantGroupTypeIds = new List<int>();
            var currentGroupTypeIds = this.CurrentGroupTypeIds.ToList();
            currentAndDescendantGroupTypeIds.AddRange( currentGroupTypeIds );
            foreach ( var templateGroupType in groupTypeService.Queryable().Where( a => currentGroupTypeIds.Contains( a.Id ) ) )
            {
                foreach ( var childGroupType in groupTypeService.GetChildGroupTypes( templateGroupType.Id ) )
                {
                    currentAndDescendantGroupTypeIds.Add( childGroupType.Id );
                    currentAndDescendantGroupTypeIds.AddRange( groupTypeService.GetAllAssociatedDescendents( childGroupType.Id ).Select( a => a.Id ).ToList() );
                }
            }

            groupLocationQry = groupLocationQry.Where( a => currentAndDescendantGroupTypeIds.Contains( a.Group.GroupTypeId ) );

            groupLocationQry = groupLocationQry.OrderBy( a => a.Group.Name ).ThenBy( a => a.Location.Name );

            List<int> currentDeviceLocationIdList = this.GetGroupTypesLocations( rockContext ).Select( a => a.Id ).Distinct().ToList();

            var qryList = groupLocationQry
                .Where( a => currentDeviceLocationIdList.Contains( a.LocationId ) )
                .Select( a =>
                new
                {
                    GroupLocationId = a.Id,
                    a.Location,
                    GroupId = a.GroupId,
                    GroupName = a.Group.Name,
                    ScheduleIdList = a.Schedules.Select( s => s.Id ),
                    GroupTypeId = a.Group.GroupTypeId
                } ).ToList();

            var locationService = new LocationService( rockContext );

            // put stuff in a datatable so we can dynamically have columns for each Schedule
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add( "GroupLocationId" );
            dataTable.Columns.Add( "GroupId" );
            dataTable.Columns.Add( "GroupName" );
            dataTable.Columns.Add( "GroupPath" );
            dataTable.Columns.Add( "LocationName" );
            dataTable.Columns.Add( "LocationPath" );
            foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() )
            {
                dataTable.Columns.Add( field.DataField, typeof( bool ) );
            }

            var locationPaths = new Dictionary<int, string>();

            foreach ( var row in qryList )
            {
                DataRow dataRow = dataTable.NewRow();
                dataRow["GroupLocationId"] = row.GroupLocationId;
                dataRow["GroupName"] = groupService.GroupAncestorPathName( row.GroupId );
                dataRow["GroupPath"] = groupPaths.Where( gt => gt.GroupTypeId == row.GroupTypeId ).Select( gt => gt.Path ).FirstOrDefault();
                dataRow["LocationName"] = row.Location.Name;

                if ( row.Location.ParentLocationId.HasValue )
                {
                    int locationId = row.Location.ParentLocationId.Value;

                    if ( !locationPaths.ContainsKey( locationId ) )
                    {
                        var locationNames = new List<string>();
                        var parentLocation = locationService.Get( locationId );
                        while ( parentLocation != null )
                        {
                            locationNames.Add( parentLocation.Name );
                            parentLocation = parentLocation.ParentLocation;
                        }

                        if ( locationNames.Any() )
                        {
                            locationNames.Reverse();
                            locationPaths.Add( locationId, locationNames.AsDelimited( " > " ) );
                        }
                        else
                        {
                            locationPaths.Add( locationId, string.Empty );
                        }
                    }

                    dataRow["LocationPath"] = locationPaths[locationId];
                }

                foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() )
                {
                    int scheduleId = int.Parse( field.DataField.Replace( "scheduleField_", string.Empty ) );
                    dataRow[field.DataField] = row.ScheduleIdList.Any( a => a == scheduleId );
                }

                dataTable.Rows.Add( dataRow );
            }

            gGroupLocationSchedule.EntityTypeId = EntityTypeCache.Read<GroupLocation>().Id;
            gGroupLocationSchedule.DataSource = dataTable;
            gGroupLocationSchedule.DataBind();
        }
示例#30
0
 /// <summary>
 /// The groups of a particular type that current person belongs to
 /// </summary>
 /// <returns></returns>
 protected IEnumerable<Group> PersonGroups(Guid groupTypeGuid)
 {
     var service = new GroupTypeService();
     int groupTypeId = service.Queryable().Where( g => g.Guid == groupTypeGuid ).Select( g => g.Id ).FirstOrDefault();
     return PersonGroups( groupTypeId );
 }