Beispiel #1
0
        /// <summary>
        /// Handles the Sorting event of the Grid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewSortEventArgs"/> instance containing the event data.</param>
        protected void Grid_Sorting( object sender, GridViewSortEventArgs e )
        {
            SortProperty sortProperty = this.SortProperty;
            if ( sortProperty != null && sortProperty.Property == e.SortExpression )
            {
                if ( sortProperty.Direction == SortDirection.Ascending )
                    sortProperty.Direction = SortDirection.Descending;
                else
                    sortProperty.Direction = SortDirection.Ascending;

                this.SortProperty = sortProperty;
            }
            else
                this.SortProperty = new SortProperty( e );

            OnGridRebind( e );
        }
Beispiel #2
0
        private void BindGrid()
        {
            var qry = new UserLoginService().Queryable()
                .Where( l => !_personId.HasValue || l.PersonId == _personId.Value );

            // username filter
            string usernameFilter =  gfSettings.GetUserPreference( "Username" );
            if (!string.IsNullOrWhiteSpace(usernameFilter))
            {
                qry = qry.Where( l => l.UserName.StartsWith( usernameFilter ) );
            }

            // provider filter
            Guid guid = Guid.Empty;
            if (Guid.TryParse(gfSettings.GetUserPreference( "Authentication Provider" ), out guid))
            {
                qry = qry.Where( l => l.EntityType.Guid.Equals( guid ) );
            }

            // created filter
            var drp = new DateRangePicker();
            drp.DelimitedValues = gfSettings.GetUserPreference( "Created" );
            if ( drp.LowerValue.HasValue )
            {
                qry = qry.Where( l => l.CreationDateTime >= drp.LowerValue.Value );
            }
            if ( drp.UpperValue.HasValue )
            {
                DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 );
                qry = qry.Where( l => l.CreationDateTime < upperDate );
            }

            // last login filter
            var drp2 = new DateRangePicker();
            drp2.DelimitedValues = gfSettings.GetUserPreference( "Last Login" );
            if ( drp2.LowerValue.HasValue )
            {
                qry = qry.Where( l => l.LastLoginDateTime >= drp2.LowerValue.Value );
            }
            if ( drp2.UpperValue.HasValue )
            {
                DateTime upperDate = drp2.UpperValue.Value.Date.AddDays( 1 );
                qry = qry.Where( l => l.LastLoginDateTime < upperDate );
            }

            // Is Confirmed filter
            bool isConfirmed = false;
            if (bool.TryParse(gfSettings.GetUserPreference( "Is Confirmed" ), out isConfirmed))
            {
                qry = qry.Where( l => l.IsConfirmed == isConfirmed || ( !isConfirmed && l.IsConfirmed == null ) );
            }

            // is locked out filter
            bool isLockedOut = false;
            if ( bool.TryParse( gfSettings.GetUserPreference( "Is Locked Out" ), out isLockedOut ) )
            {
                qry = qry.Where( l => l.IsLockedOut == isLockedOut || ( !isLockedOut && l.IsLockedOut == null ) );
            }

            // Sort
            SortProperty sortProperty = gUserLogins.SortProperty;
            if ( sortProperty == null )
            {
                sortProperty = new SortProperty( new GridViewSortEventArgs( "UserName", SortDirection.Ascending ) );
            }

            gUserLogins.DataSource = qry.Sort( sortProperty )
                .Select( l => new
                    {
                        Id = l.Id,
                        UserName = l.UserName,
                        PersonId = l.PersonId,
                        PersonName = l.Person.LastName + ", " + l.Person.NickName,
                        ProviderName = l.EntityType.FriendlyName,
                        CreationDateTime = l.CreationDateTime,
                        LastLoginDateTime = l.LastLoginDateTime,
                        IsConfirmed = l.IsConfirmed,
                        IsLockedOut = l.IsLockedOut
                    }
                ).ToList();
            gUserLogins.DataBind();
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            if ( CurrentPersonAlias != null )
            {
                var rockContext = new RockContext();

                int personAliasEntityTypeId = EntityTypeCache.Read( "Rock.Model.PersonAlias" ).Id;
                var personAliasIds = new FollowingService( new RockContext() ).Queryable()
                    .Where( f =>
                        f.EntityTypeId == personAliasEntityTypeId &&
                        f.PersonAliasId == CurrentPersonAlias.Id )
                    .Select( f => f.EntityId )
                    .Distinct()
                    .ToList();

                var qry = new PersonAliasService( rockContext ).Queryable()
                    .Where( p => personAliasIds.Contains( p.Id ) )
                    .Select( p => p.Person )
                    .Distinct();

                // Sort
                SortProperty sortProperty = gFollowings.SortProperty;
                if ( sortProperty == null )
                {
                    sortProperty = new SortProperty( new GridViewSortEventArgs( "LastName,NickName", SortDirection.Ascending ) );
                }

                Guid homePhoneGuid = Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid();
                Guid cellPhoneGuid = Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid();
                Guid adultGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();
                Guid marriedGuid = Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid();

                gFollowings.DataSource = qry.Sort( sortProperty )
                    .Select( p => new
                        {
                            p.Id,
                            p.LastName,
                            p.NickName,
                            p.BirthDate,
                            p.Email,
                            HomePhone = p.PhoneNumbers
                                .Where( n => n.NumberTypeValue.Guid.Equals(homePhoneGuid))
                                .Select( n => n.NumberFormatted)
                                .FirstOrDefault(),
                            CellPhone = p.PhoneNumbers
                                .Where( n => n.NumberTypeValue.Guid.Equals( cellPhoneGuid ) )
                                .Select( n => n.NumberFormatted )
                                .FirstOrDefault(),
                            SpouseName = p.Members
                                .Where( m =>
                                    p.MaritalStatusValue.Guid.Equals(marriedGuid) &&
                                    m.GroupRole.Guid.Equals(adultGuid))
                                .SelectMany( m => m.Group.Members)
                                .Where( m =>
                                    m.PersonId != p.Id &&
                                    m.GroupRole.Guid.Equals(adultGuid) &&
                                    m.Person.MaritalStatusValue.Guid.Equals(marriedGuid) )
                                .Select( s => s.Person.NickName + " " + s.Person.LastName)
                                .FirstOrDefault()
                        } ).ToList();

                gFollowings.DataBind();
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            // Find all the Group Types
            var groupTypeIds = GetAvailableGroupTypes();

            if ( ( GetAttributeValue( "DisplayFilter" ) ?? "false" ).AsBoolean() )
            {
                int? groupTypeFilter = gfSettings.GetUserPreference( "Group Type" ).AsInteger( false );
                if ( groupTypeFilter.HasValue )
                {
                    groupTypeIds = groupTypeIds.Where( g => g == groupTypeFilter.Value ).ToList();
                }
            }

            var rockContext = new RockContext();

            SortProperty sortProperty = gGroups.SortProperty;
            if ( sortProperty == null )
            {
                sortProperty = new SortProperty( new GridViewSortEventArgs( "GroupTypeOrder, GroupTypeName, GroupOrder, Name", SortDirection.Ascending ) );
            }

            bool onlySecurityGroups = GetAttributeValue( "LimittoSecurityRoleGroups" ).AsBoolean();
            bool showDescriptionColumn = GetAttributeValue( "DisplayDescriptionColumn" ).AsBoolean();
            bool showActiveStatusColumn = GetAttributeValue( "DisplayActiveStatusColumn" ).AsBoolean();
            bool showSystemColumn = GetAttributeValue( "DisplaySystemColumn" ).AsBoolean();

            if ( !showDescriptionColumn )
            {
                gGroups.TooltipField = "Description";
            }

            Dictionary<string, BoundField> boundFields = gGroups.Columns.OfType<BoundField>().ToDictionary( a => a.DataField );
            boundFields["GroupTypeName"].Visible = GetAttributeValue( "DisplayGroupTypeColumn" ).AsBoolean();
            boundFields["Description"].Visible = showDescriptionColumn;

            Dictionary<string, BoolField> boolFields = gGroups.Columns.OfType<BoolField>().ToDictionary( a => a.DataField );
            boolFields["IsActive"].Visible = showActiveStatusColumn;
            boolFields["IsSystem"].Visible = showSystemColumn;

            // Person context will exist if used on a person detail page
            var personContext = ContextEntity<Person>();
            if ( personContext != null )
            {
                boundFields["GroupRole"].Visible = true;
                boundFields["DateAdded"].Visible = true;
                boundFields["MemberCount"].Visible = false;

                gGroups.Actions.ShowAdd = false;
                gGroups.IsDeleteEnabled = false;
                gGroups.Columns.OfType<DeleteField>().ToList().ForEach( f => f.Visible = false );

                var qry = new GroupMemberService( rockContext ).Queryable()
                    .Where( m =>
                        m.PersonId == personContext.Id &&
                        groupTypeIds.Contains( m.Group.GroupTypeId ) &&
                        ( !onlySecurityGroups || m.Group.IsSecurityRole ) );

                // Filter by active/inactive
                if ( ddlActiveFilter.SelectedIndex > -1 )
                {
                    if ( ddlActiveFilter.SelectedValue == "inactive" )
                    {
                        qry = qry.Where( a => a.Group.IsActive == false );
                    }
                    else if ( ddlActiveFilter.SelectedValue == "active" )
                    {
                        qry = qry.Where( a => a.Group.IsActive == true );
                    }
                }

                gGroups.DataSource = qry
                    .Select( m => new
                        {
                            Id = m.Group.Id,
                            Name = m.Group.Name,
                            GroupTypeName = m.Group.GroupType.Name,
                            GroupOrder = m.Group.Order,
                            GroupTypeOrder = m.Group.GroupType.Order,
                            Description = m.Group.Description,
                            IsSystem = m.Group.IsSystem,
                            GroupRole = m.GroupRole.Name,
                            DateAdded = m.CreatedDateTime,
                            IsActive = m.Group.IsActive,
                            MemberCount = 0
                        } )
                    .Sort( sortProperty )
                    .ToList();
            }
            else
            {
                bool canEdit = IsUserAuthorized( Authorization.EDIT );
                gGroups.Actions.ShowAdd = canEdit;
                gGroups.IsDeleteEnabled = canEdit;

                boundFields["GroupRole"].Visible = false;
                boundFields["DateAdded"].Visible = false;
                boundFields["MemberCount"].Visible = true;

                var qry = new GroupService( rockContext ).Queryable()
                    .Where( g =>
                        groupTypeIds.Contains( g.GroupTypeId ) &&
                        ( !onlySecurityGroups || g.IsSecurityRole ) );

                // Filter by active/inactive
                if ( ddlActiveFilter.SelectedIndex > -1 )
                {
                    if ( ddlActiveFilter.SelectedValue == "inactive" )
                    {
                        qry = qry.Where( a => a.IsActive == false );
                    }
                    else if ( ddlActiveFilter.SelectedValue == "active" )
                    {
                        qry = qry.Where( a => a.IsActive == true );
                    }
                }

                gGroups.DataSource = qry.Select( g => new
                        {
                            Id = g.Id,
                            Name = g.Name,
                            GroupTypeName = g.GroupType.Name,
                            GroupOrder = g.Order,
                            GroupTypeOrder = g.GroupType.Order,
                            Description = g.Description,
                            IsSystem = g.IsSystem,
                            IsActive = g.IsActive,
                            GroupRole = string.Empty,
                            DateAdded = DateTime.MinValue,
                            MemberCount = g.Members.Count()
                        } )
                    .Sort( sortProperty )
                    .ToList();
            }

            gGroups.DataBind();
        }
Beispiel #5
0
        /// <summary>
        /// Job that will sync groups.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute( IJobExecutionContext context )
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            bool requirePasswordReset = dataMap.GetBoolean( "RequirePasswordReset" );

            int groupsSynced = 0;
            int groupsChanged = 0;

            try
            {
                // get groups set to sync
                GroupService groupService = new GroupService( new RockContext() );
                var groupIdsThatSync = groupService.Queryable().Where( g => g.SyncDataViewId != null ).Select( a => a.Id ).ToList();

                foreach ( var syncGroupId in groupIdsThatSync )
                {
                    bool hasGroupChanged = false;

                    // use a fresh rockContext per group so that ChangeTracker doesn't get bogged down
                    using ( var rockContext = new RockContext() )
                    {
                        var syncGroup = new GroupService( rockContext ).Get( syncGroupId );
                        GroupMemberService groupMemberService = new GroupMemberService( rockContext );

                        // increase the timeout just in case the dataview source is slow
                        rockContext.Database.CommandTimeout = 180;

                        var syncSource = new DataViewService( rockContext ).Get( syncGroup.SyncDataViewId.Value );

                        // ensure this is a person dataview
                        bool isPersonDataSet = syncSource.EntityTypeId == EntityTypeCache.Read( typeof( Rock.Model.Person ) ).Id;

                        if ( isPersonDataSet )
                        {
                            SortProperty sortById = new SortProperty();
                            sortById.Property = "Id";
                            sortById.Direction = System.Web.UI.WebControls.SortDirection.Ascending;
                            List<string> errorMessages = new List<string>();

                            var personService = new PersonService( rockContext );
                            var parameterExpression = personService.ParameterExpression;
                            var whereExpression = syncSource.GetExpression( personService, parameterExpression, out errorMessages );
                            var sourceItems = personService.Get( parameterExpression, whereExpression ).Select( q => q.Id ).ToList();
                            var targetItems = groupMemberService.Queryable().Where( gm => gm.GroupId == syncGroup.Id ).ToList();

                            // delete items from the target not in the source
                            foreach ( var targetItem in targetItems.Where( t => !sourceItems.Contains( t.PersonId ) ) )
                            {
                                // made a clone of the person as it will be detached when the group member is deleted. Also
                                // saving the delete before the email is sent in case an exception occurs so the user doesn't
                                // get an email everytime the agent runs.
                                Person recipient = (Person)targetItem.Person.Clone();
                                groupMemberService.Delete( targetItem );

                                rockContext.SaveChanges();

                                hasGroupChanged = true;

                                if ( syncGroup.ExitSystemEmailId.HasValue )
                                {
                                    SendExitEmail( syncGroup.ExitSystemEmailId.Value, recipient, syncGroup );
                                }
                            }

                            // add items not in target but in the source
                            foreach ( var sourceItem in sourceItems.Where( s => !targetItems.Select( t => t.PersonId ).Contains( s ) ) )
                            {
                                // add source to target
                                var newGroupMember = new GroupMember { Id = 0 };
                                newGroupMember.PersonId = sourceItem;
                                newGroupMember.Group = syncGroup;
                                newGroupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                newGroupMember.GroupRoleId = syncGroup.GroupType.DefaultGroupRoleId ?? syncGroup.GroupType.Roles.FirstOrDefault().Id;
                                groupMemberService.Add( newGroupMember );

                                hasGroupChanged = true;

                                if ( syncGroup.WelcomeSystemEmailId.HasValue )
                                {
                                    SendWelcomeEmail( syncGroup.WelcomeSystemEmailId.Value, sourceItem, syncGroup, syncGroup.AddUserAccountsDuringSync ?? false, requirePasswordReset );
                                }
                            }

                            if ( hasGroupChanged )
                            {
                                groupsChanged++;
                            }

                            groupsSynced++;

                            rockContext.SaveChanges();

                            if ( hasGroupChanged && ( syncGroup.IsSecurityRole || syncGroup.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) )
                            {
                                Rock.Security.Role.Flush( syncGroup.Id );
                            }
                        }
                    }
                }

                var resultMessage = string.Empty;
                if ( groupsSynced == 0 )
                {
                    resultMessage = "No groups to sync";
                }
                else if ( groupsSynced == 1 )
                {
                    resultMessage = "1 group was sync'ed";
                }
                else
                {
                    resultMessage = string.Format( "{0} groups were sync'ed", groupsSynced );
                }

                resultMessage += string.Format( " and {0} groups where changed", groupsChanged );

                context.Result = resultMessage;
            }
            catch ( System.Exception ex )
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException( ex, context2 );
                throw;
            }
        }
Beispiel #6
0
        /// <summary>
        /// Job that will sync groups.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute( IJobExecutionContext context )
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            try
            {
                // get groups set to sync
                RockContext rockContext = new RockContext();
                GroupService groupService = new GroupService( rockContext );
                var groupsThatSync = groupService.Queryable().Where( g => g.SyncDataViewId != null ).ToList();

                foreach ( var syncGroup in groupsThatSync )
                {
                    GroupMemberService groupMemberService = new GroupMemberService( rockContext );

                    var syncSource = new DataViewService( rockContext ).Get( syncGroup.SyncDataViewId.Value );

                    // ensure this is a person dataview
                    bool isPersonDataSet = syncSource.EntityTypeId == EntityTypeCache.Read( typeof( Rock.Model.Person ) ).Id;

                    if ( isPersonDataSet )
                    {
                        SortProperty sortById = new SortProperty();
                        sortById.Property = "Id";
                        sortById.Direction = System.Web.UI.WebControls.SortDirection.Ascending;
                        List<string> errorMessages = new List<string>();

                        var sourceItems = syncSource.GetQuery( sortById, 180, out errorMessages ).Select( q => q.Id ).ToList();
                        var targetItems = groupMemberService.Queryable("Person").Where( gm => gm.GroupId == syncGroup.Id ).ToList();

                        // delete items from the target not in the source
                        foreach ( var targetItem in targetItems.Where( t => !sourceItems.Contains( t.PersonId ) ) )
                        {
                            // made a clone of the person as it will be detached when the group member is deleted. Also
                            // saving the delete before the email is sent in case an exception occurs so the user doesn't
                            // get an email everytime the agent runs.
                            Person recipient = (Person)targetItem.Person.Clone();
                            groupMemberService.Delete( targetItem );

                            rockContext.SaveChanges();

                            if ( syncGroup.ExitSystemEmailId.HasValue )
                            {
                                SendExitEmail( syncGroup.ExitSystemEmailId.Value, recipient, syncGroup );
                            }
                        }

                        // add items not in target but in the source
                        foreach ( var sourceItem in sourceItems.Where( s => !targetItems.Select( t => t.PersonId ).Contains( s ) ) )
                        {
                            // add source to target
                            var newGroupMember = new GroupMember { Id = 0 };
                            newGroupMember.PersonId = sourceItem;
                            newGroupMember.Group = syncGroup;
                            newGroupMember.GroupMemberStatus = GroupMemberStatus.Active;
                            newGroupMember.GroupRoleId = syncGroup.GroupType.DefaultGroupRoleId ?? syncGroup.GroupType.Roles.FirstOrDefault().Id;
                            groupMemberService.Add( newGroupMember );

                            if ( syncGroup.WelcomeSystemEmailId.HasValue )
                            {
                                SendWelcomeEmail( syncGroup.WelcomeSystemEmailId.Value, sourceItem, syncGroup, syncGroup.AddUserAccountsDuringSync ?? false );
                            }
                        }

                        rockContext.SaveChanges();
                    }
                }
            }
            catch ( System.Exception ex )
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException( ex, context2 );
                throw ex;
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            // Find all the Group Types
            var groupTypeIds = GetAvailableGroupTypes();

            if ( GetAttributeValue( "DisplayFilter" ).AsBooleanOrNull() ?? false )
            {
                int? groupTypeFilter = gfSettings.GetUserPreference( "Group Type" ).AsIntegerOrNull();
                if ( groupTypeFilter.HasValue )
                {
                    groupTypeIds = groupTypeIds.Where( g => g == groupTypeFilter.Value ).ToList();
                }
            }

            var rockContext = new RockContext();

            SortProperty sortProperty = gGroups.SortProperty;
            if ( sortProperty == null )
            {
                sortProperty = new SortProperty( new GridViewSortEventArgs( "GroupTypeOrder, GroupTypeName, GroupOrder, Name", SortDirection.Ascending ) );
            }

            bool onlySecurityGroups = GetAttributeValue( "LimittoSecurityRoleGroups" ).AsBoolean();

            var qryGroups = new GroupService( rockContext ).Queryable().Where( g => groupTypeIds.Contains( g.GroupTypeId ) && ( !onlySecurityGroups || g.IsSecurityRole ) );

            string limitToActiveStatus = GetAttributeValue( "LimittoActiveStatus" );

            if ( limitToActiveStatus == "all" && gfSettings.Visible )
            {
                // Filter by active/inactive unless the block settings restrict it
                if ( ddlActiveFilter.SelectedIndex > -1 )
                {
                    if ( ddlActiveFilter.SelectedValue == "inactive" )
                    {
                        qryGroups = qryGroups.Where( a => a.IsActive == false );
                    }
                    else if ( ddlActiveFilter.SelectedValue == "active" )
                    {
                        qryGroups = qryGroups.Where( a => a.IsActive == true );
                    }
                }
            }
            else if ( limitToActiveStatus != "all")
            {
                // filter by the block settinf for Active Status
                if ( limitToActiveStatus == "inactive")
                {
                    qryGroups = qryGroups.Where( a => a.IsActive == false );
                }
                else if ( limitToActiveStatus == "active" )
                {
                    qryGroups = qryGroups.Where( a => a.IsActive == true );
                }
            }

            // Person context will exist if used on a person detail page
            int personEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id;
            if ( ContextTypesRequired.Any( e => e.Id == personEntityTypeId ) )
            {
                var personContext = ContextEntity<Person>();
                if ( personContext != null )
                {
                    // limit to Groups that the person is a member of
                    var qry = new GroupMemberService( rockContext ).Queryable( true )
                        .Where( m => m.PersonId == personContext.Id )
                        .Join( qryGroups, gm => gm.GroupId, g => g.Id, ( gm, g ) => new { Group = g, GroupMember = gm } );

                    gGroups.DataSource = qry
                        .Select( m => new
                            {
                                Id = m.Group.Id,
                                Name = m.Group.Name,
                                GroupTypeName = m.Group.GroupType.Name,
                                GroupOrder = m.Group.Order,
                                GroupTypeOrder = m.Group.GroupType.Order,
                                Description = m.Group.Description,
                                IsSystem = m.Group.IsSystem,
                                GroupRole = m.GroupMember.GroupRole.Name,
                                DateAdded = m.GroupMember.CreatedDateTime,
                                IsActive = m.Group.IsActive,
                                MemberCount = 0
                            } )
                        .Sort( sortProperty )
                        .ToList();
                }
            }
            else
            {
                var roleGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() );
                int roleGroupTypeId = roleGroupType != null ? roleGroupType.Id : 0;
                bool useRolePrefix = onlySecurityGroups || groupTypeIds.Contains( roleGroupTypeId );

                gGroups.DataSource = qryGroups.Select( g => new
                        {
                            Id = g.Id,
                            Name = (( useRolePrefix && g.GroupType.Id != roleGroupTypeId ) ? "GROUP - " : "" ) + g.Name,
                            GroupTypeName = g.GroupType.Name,
                            GroupOrder = g.Order,
                            GroupTypeOrder = g.GroupType.Order,
                            Description = g.Description,
                            IsSystem = g.IsSystem,
                            IsActive = g.IsActive,
                            GroupRole = string.Empty,
                            DateAdded = DateTime.MinValue,
                            MemberCount = g.Members.Count()
                        } )
                    .Sort( sortProperty )
                    .ToList();
            }

            gGroups.DataBind();

            // hide the group type column if there's only one type; must come after DataBind()
            if ( _groupTypesCount == 1 )
            {
                this.gGroups.Columns[1].Visible = false;
            }
        }
        private List<ContentChannelItem> GetContent( List<string> errorMessages )
        {
            var items = GetCacheItem( CONTENT_CACHE_KEY ) as List<ContentChannelItem>;
            bool queryParameterFiltering = GetAttributeValue( "QueryParameterFiltering" ).AsBoolean( false );

            if ( items == null || ( queryParameterFiltering && Request.QueryString.Count > 0 ) )
            {
                Guid? channelGuid = GetAttributeValue( "Channel" ).AsGuidOrNull();
                if ( channelGuid.HasValue )
                {
                    var rockContext = new RockContext();
                    var service = new ContentChannelItemService( rockContext );
                    var itemType = typeof( Rock.Model.ContentChannelItem );
                    
                    ParameterExpression paramExpression = service.ParameterExpression;

                    var contentChannel = new ContentChannelService( rockContext ).Get( channelGuid.Value );
                    if ( contentChannel != null )
                    {
                        var entityFields = HackEntityFields( contentChannel, rockContext );

                        if ( items == null )
                        {
                            items = new List<ContentChannelItem>();

                            var qry = service.Queryable( "ContentChannel,ContentChannelType" );

                            int? itemId = PageParameter( "Item" ).AsIntegerOrNull();
                            if ( queryParameterFiltering && itemId.HasValue )
                            {
                                qry = qry.Where( i => i.Id == itemId.Value );
                            }
                            else
                            {
                                qry = qry.Where( i => i.ContentChannelId == contentChannel.Id );

                                if ( contentChannel.RequiresApproval )
                                {
                                    // Check for the configured status and limit query to those
                                    var statuses = new List<ContentChannelItemStatus>();

                                    foreach ( string statusVal in ( GetAttributeValue( "Status" ) ?? "2" ).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ) )
                                    {
                                        var status = statusVal.ConvertToEnumOrNull<ContentChannelItemStatus>();
                                        if ( status != null )
                                        {
                                            statuses.Add( status.Value );
                                        }
                                    }
                                    if ( statuses.Any() )
                                    {
                                        qry = qry.Where( i => statuses.Contains( i.Status ) );
                                    }
                                }

                                int? dataFilterId = GetAttributeValue( "FilterId" ).AsIntegerOrNull();
                                if ( dataFilterId.HasValue )
                                {
                                    var dataFilterService = new DataViewFilterService( rockContext );
                                    var dataFilter = dataFilterService.Queryable( "ChildFilters" ).FirstOrDefault( a => a.Id == dataFilterId.Value );
                                    Expression whereExpression = dataFilter != null ? dataFilter.GetExpression( itemType, service, paramExpression, errorMessages ) : null;

                                    qry = qry.Where( paramExpression, whereExpression, null );
                                }
                            }

                            // All filtering has been added, now run query and load attributes
                            foreach ( var item in qry.ToList() )
                            {
                                item.LoadAttributes( rockContext );
                                items.Add( item );
                            }

                            // Order the items
                            SortProperty sortProperty = null;

                            string orderBy = GetAttributeValue( "Order" );
                            if ( !string.IsNullOrWhiteSpace( orderBy ) )
                            {
                                var fieldDirection = new List<string>();
                                foreach ( var itemPair in orderBy.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ).Select( a => a.Split( '^' ) ) )
                                {
                                    if ( itemPair.Length == 2 && !string.IsNullOrWhiteSpace( itemPair[0] ) )
                                    {
                                        var sortDirection = SortDirection.Ascending;
                                        if ( !string.IsNullOrWhiteSpace( itemPair[1] ) )
                                        {
                                            sortDirection = itemPair[1].ConvertToEnum<SortDirection>( SortDirection.Ascending );
                                        }
                                        fieldDirection.Add( itemPair[0] + ( sortDirection == SortDirection.Descending ? " desc" : "" ) );
                                    }
                                }

                                sortProperty = new SortProperty();
                                sortProperty.Direction = SortDirection.Ascending;
                                sortProperty.Property = fieldDirection.AsDelimited( "," );

                                string[] columns = sortProperty.Property.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );

                                var itemQry = items.AsQueryable();
                                IOrderedQueryable<ContentChannelItem> orderedQry = null;

                                for ( int columnIndex = 0; columnIndex < columns.Length; columnIndex++ )
                                {
                                    string column = columns[columnIndex].Trim();

                                    var direction = sortProperty.Direction;
                                    if ( column.ToLower().EndsWith( " desc" ) )
                                    {
                                        column = column.Left( column.Length - 5 );
                                        direction = sortProperty.Direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
                                    }

                                    try
                                    {
                                        if ( column.StartsWith( "Attribute:" ) )
                                        {
                                            string attributeKey = column.Substring( 10 );

                                            if ( direction == SortDirection.Ascending )
                                            {
                                                orderedQry = ( columnIndex == 0 ) ?
                                                    itemQry.OrderBy( i => i.AttributeValues.Where( v => v.Key == attributeKey ).FirstOrDefault().Value.SortValue ) :
                                                    orderedQry.ThenBy( i => i.AttributeValues.Where( v => v.Key == attributeKey ).FirstOrDefault().Value.SortValue );
                                            }
                                            else
                                            {
                                                orderedQry = ( columnIndex == 0 ) ?
                                                    itemQry.OrderByDescending( i => i.AttributeValues.Where( v => v.Key == attributeKey ).FirstOrDefault().Value.SortValue ) :
                                                    orderedQry.ThenByDescending( i => i.AttributeValues.Where( v => v.Key == attributeKey ).FirstOrDefault().Value.SortValue );
                                            }
                                        }
                                        else
                                        {
                                            if ( direction == SortDirection.Ascending )
                                            {
                                                orderedQry = ( columnIndex == 0 ) ? itemQry.OrderBy( column ) : orderedQry.ThenBy( column );
                                            }
                                            else
                                            {
                                                orderedQry = ( columnIndex == 0 ) ? itemQry.OrderByDescending( column ) : orderedQry.ThenByDescending( column );
                                            }
                                        }
                                    }
                                    catch { }

                                }

                                try
                                {
                                    if ( orderedQry != null )
                                    {
                                        items = orderedQry.ToList();
                                    }
                                }
                                catch { }

                            }

                            int? cacheDuration = GetAttributeValue( "CacheDuration" ).AsInteger();
                            if ( cacheDuration > 0 )
                            {
                                var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds( cacheDuration.Value ) };
                                AddCacheItem( CONTENT_CACHE_KEY, items, cacheItemPolicy );
                            }
                        }


                        // If items could be filtered by querystring values, check for filters
                        if ( queryParameterFiltering )
                        {
                            var pageParameters = PageParameters();
                            if ( pageParameters.Count > 0 )
                            {
                                var propertyFilter = new Rock.Reporting.DataFilter.PropertyFilter();

                                var itemQry = items.AsQueryable();
                                foreach ( string key in PageParameters().Select( p => p.Key ).ToList() )
                                {
                                    var selection = new List<string>();
                                    selection.Add( key );

                                    var entityField = entityFields.FirstOrDefault( f => f.Name.Equals( key, StringComparison.OrdinalIgnoreCase ) );
                                    if ( entityField != null )
                                    {
                                        string value = PageParameter( key );
                                        switch ( entityField.FieldType.Guid.ToString().ToUpper() )
                                        {
                                            case Rock.SystemGuid.FieldType.DAY_OF_WEEK:
                                            case Rock.SystemGuid.FieldType.SINGLE_SELECT:
                                                {
                                                    selection.Add( value );
                                                }
                                                break;
                                            case Rock.SystemGuid.FieldType.MULTI_SELECT:
                                                {
                                                    selection.Add( ComparisonType.Contains.ConvertToInt().ToString() );
                                                    selection.Add( value );
                                                }
                                                break;
                                            default:
                                                {
                                                    selection.Add( ComparisonType.EqualTo.ConvertToInt().ToString() );
                                                    selection.Add( value );
                                                }
                                                break;
                                        }

                                        itemQry = itemQry.Where( paramExpression, propertyFilter.GetExpression( itemType, service, paramExpression, Newtonsoft.Json.JsonConvert.SerializeObject( selection ) ) );
                                    }
                                }

                                items = itemQry.ToList();

                            }
                        }
                    }
                }
            }

            return items;

        }
        protected void doStuff()
        {
            int personFilter = ppGroupMember.PersonId ?? -1;
            int checkinGroupFilter = int.TryParse(rddlCheckinGroup.SelectedValue, out checkinGroupFilter) ? checkinGroupFilter : -1;
            SortProperty attendanceSort = rgAttendanceList.SortProperty;

            var attendance = attendServ.Queryable();
            if (checkinGroupFilter != -1)
            {
                attendance = attendance.Where(x => x.GroupId == checkinGroupFilter);
            }
            if (personFilter != -1)
            {
                attendance = attendance.Where(x => x.PersonAlias.PersonId == personFilter);
            }
            if (dateRange.LowerValue != null && dateRange.UpperValue != null)
            {
                attendance = attendance.Where(x => x.StartDateTime > dateRange.LowerValue && x.StartDateTime < dateRange.UpperValue);
            }

            var attendanceData = attendance.Select(x => new AttendanceData { Id = x.Id, CheckinDate = x.StartDateTime, CheckinGroupName = x.Group.Name, PersonName = x.PersonAlias.Person.NickName + " " + x.PersonAlias.Person.LastName, DidAttend = x.DidAttend, DidNotOccur = x.DidNotOccur });

            if (attendanceSort != null)
            {
                attendanceData = attendanceData.Sort(attendanceSort);
            }
            else
            {
                SortProperty prop = new SortProperty();
                prop.Direction = SortDirection.Descending;
                prop.Property = "CheckinDate";
                attendanceData = attendanceData.Sort(prop);
            }

            rgAttendanceList.DataSource = attendanceData.ToList();
            rgAttendanceList.DataKeyNames = new string[] { "Id" };
            rgAttendanceList.DataBind();
        }
        /// <summary>
        /// Shows the preview.
        /// </summary>
        /// <param name="entityTypeId">The entity type id.</param>
        /// <param name="filter">The filter.</param>
        private void BindGrid( Report report )
        {
            if ( report != null )
            {
                var errors = new List<string>();

                if ( !report.EntityTypeId.HasValue )
                {
                    gReport.Visible = false;
                    return;
                }

                var rockContext = new RockContext();

                if ( !report.IsAuthorized( Authorization.VIEW, this.CurrentPerson ) )
                {
                    gReport.Visible = false;
                    return;
                }

                Type entityType = EntityTypeCache.Read( report.EntityTypeId.Value, rockContext ).GetEntityType();

                bool isPersonDataSet = report.EntityTypeId == EntityTypeCache.Read( typeof( Rock.Model.Person ), true, rockContext ).Id;

                if ( isPersonDataSet )
                {
                    gReport.PersonIdField = "Id";
                    gReport.DataKeyNames = new string[] { "Id" };
                }
                else
                {
                    gReport.PersonIdField = null;
                }

                if ( report.EntityTypeId.HasValue )
                {
                    gReport.RowItemText = EntityTypeCache.Read( report.EntityTypeId.Value, rockContext ).FriendlyName;
                }

                List<EntityField> entityFields = Rock.Reporting.EntityHelper.GetEntityFields( entityType );

                var selectedEntityFields = new Dictionary<int, EntityField>();
                var selectedAttributes = new Dictionary<int, AttributeCache>();
                var selectedComponents = new Dictionary<int, ReportField>();

                // if there is a selectField, keep it to preserve which items are checked
                var selectField = gReport.Columns.OfType<SelectField>().FirstOrDefault();
                gReport.Columns.Clear();
                int columnIndex = 0;

                if ( !string.IsNullOrWhiteSpace( gReport.PersonIdField ) )
                {
                    // if we already had a selectField, use it (to preserve checkbox state)
                    gReport.Columns.Add( selectField ?? new SelectField() );
                    columnIndex++;
                }

                var reportFieldSortExpressions = new Dictionary<Guid, string>();

                foreach ( var reportField in report.ReportFields.OrderBy( a => a.ColumnOrder ) )
                {
                    columnIndex++;
                    if ( reportField.ReportFieldType == ReportFieldType.Property )
                    {
                        var entityField = entityFields.FirstOrDefault( a => a.Name == reportField.Selection );
                        if ( entityField != null )
                        {
                            selectedEntityFields.Add( columnIndex, entityField );

                            BoundField boundField;
                            if ( entityField.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DEFINED_VALUE.AsGuid() ) )
                            {
                                boundField = new DefinedValueField();
                            }
                            else
                            {
                                boundField = Grid.GetGridField( entityField.PropertyType );
                            }

                            boundField.DataField = string.Format( "Entity_{0}_{1}", entityField.Name, columnIndex );
                            boundField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? entityField.Title : reportField.ColumnHeaderText;
                            boundField.SortExpression = boundField.DataField;
                            reportFieldSortExpressions.AddOrReplace( reportField.Guid, boundField.SortExpression );
                            boundField.Visible = reportField.ShowInGrid;
                            gReport.Columns.Add( boundField );
                        }
                    }
                    else if ( reportField.ReportFieldType == ReportFieldType.Attribute )
                    {
                        Guid? attributeGuid = reportField.Selection.AsGuidOrNull();
                        if ( attributeGuid.HasValue )
                        {
                            var attribute = AttributeCache.Read( attributeGuid.Value, rockContext );
                            if ( attribute != null )
                            {
                                selectedAttributes.Add( columnIndex, attribute );

                                BoundField boundField;

                                if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.BOOLEAN.AsGuid() ) )
                                {
                                    boundField = new BoolField();
                                }
                                else
                                {
                                    boundField = new BoundField();
                                }

                                boundField.DataField = string.Format( "Attribute_{0}_{1}", attribute.Id, columnIndex );
                                boundField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? attribute.Name : reportField.ColumnHeaderText;
                                boundField.SortExpression = boundField.DataField;
                                reportFieldSortExpressions.AddOrReplace( reportField.Guid, boundField.SortExpression );

                                if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.INTEGER.AsGuid() ) ||
                                    attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE.AsGuid() ) ||
                                    attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.FILTER_DATE.AsGuid() ) )
                                {
                                    boundField.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
                                    boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                                }

                                boundField.Visible = reportField.ShowInGrid;

                                // NOTE:  Additional formatting for attributes is done in the gReport_RowDataBound event
                                gReport.Columns.Add( boundField );
                            }
                        }
                    }
                    else if ( reportField.ReportFieldType == ReportFieldType.DataSelectComponent )
                    {
                        selectedComponents.Add( columnIndex, reportField );

                        DataSelectComponent selectComponent = DataSelectContainer.GetComponent( reportField.DataSelectComponentEntityType.Name );
                        if ( selectComponent != null )
                        {
                            DataControlField columnField = selectComponent.GetGridField( entityType, reportField.Selection );

                            if ( columnField is BoundField )
                            {
                                ( columnField as BoundField ).DataField = string.Format( "Data_{0}_{1}", selectComponent.ColumnPropertyName, columnIndex );
                                columnField.SortExpression = ( columnField as BoundField ).DataField;
                            }

                            columnField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? selectComponent.ColumnHeaderText : reportField.ColumnHeaderText;
                            if ( columnField.SortExpression != null )
                            {
                                reportFieldSortExpressions.AddOrReplace( reportField.Guid, columnField.SortExpression );
                            }

                            columnField.Visible = reportField.ShowInGrid;
                            gReport.Columns.Add( columnField );
                        }
                    }
                }

                // if no fields are specified, show the default fields (Previewable/All) for the EntityType
                var dataColumns = gReport.Columns.OfType<object>().Where( a => a.GetType() != typeof( SelectField ) );
                if ( dataColumns.Count() == 0 )
                {
                    // show either the Previewable Columns or all (if there are no previewable columns)
                    bool showAllColumns = !entityFields.Any( a => a.FieldKind == FieldKind.Property && a.IsPreviewable );
                    foreach ( var entityField in entityFields.Where( a => a.FieldKind == FieldKind.Property ) )
                    {
                        columnIndex++;
                        selectedEntityFields.Add( columnIndex, entityField );

                        BoundField boundField;
                        if ( entityField.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DEFINED_VALUE.AsGuid() ) )
                        {
                            boundField = new DefinedValueField();
                        }
                        else
                        {
                            boundField = Grid.GetGridField( entityField.PropertyType );
                        }

                        boundField.DataField = string.Format( "Entity_{0}_{1}", entityField.Name, columnIndex );
                        boundField.HeaderText = entityField.Name;
                        boundField.SortExpression = boundField.DataField;
                        boundField.Visible = showAllColumns || entityField.IsPreviewable;
                        gReport.Columns.Add( boundField );
                    }
                }

                try
                {
                    gReport.Visible = true;
                    gReport.ExportFilename = report.Name;
                    SortProperty sortProperty = gReport.SortProperty;
                    if ( sortProperty == null )
                    {
                        var reportSort = new SortProperty();
                        var sortColumns = new Dictionary<string, SortDirection>();
                        foreach ( var reportField in report.ReportFields.Where( a => a.SortOrder.HasValue ).OrderBy( a => a.SortOrder.Value ) )
                        {
                            if ( reportFieldSortExpressions.ContainsKey( reportField.Guid ) )
                            {
                                var sortField = reportFieldSortExpressions[reportField.Guid];
                                if ( !string.IsNullOrWhiteSpace( sortField ) )
                                {
                                    sortColumns.Add( sortField, reportField.SortDirection );
                                }
                            }
                        }

                        if ( sortColumns.Any() )
                        {
                            reportSort.Property = sortColumns.Select( a => a.Key + ( a.Value == SortDirection.Descending ? " desc" : string.Empty ) ).ToList().AsDelimited( "," );
                            sortProperty = reportSort;
                        }
                    }

                    gReport.DataSource = report.GetDataSource( entityType, selectedEntityFields, selectedAttributes, selectedComponents, sortProperty, GetAttributeValue( "DatabaseTimeout" ).AsIntegerOrNull() ?? 180, out errors );
                    gReport.DataBind();
                }
                catch ( Exception ex )
                {
                    Exception exception = ex;
                    this.LogException( ex );
                    while ( exception != null )
                    {
                        if ( exception is System.Data.SqlClient.SqlException )
                        {
                            // if there was a SQL Server Timeout, have the warning be a friendly message about that.
                            if ( ( exception as System.Data.SqlClient.SqlException ).Number == -2 )
                            {
                                nbEditModeMessage.NotificationBoxType = NotificationBoxType.Warning;
                                nbEditModeMessage.Text = "This report did not complete in a timely manner. You can try again or adjust the timeout setting of this block.";
                                return;
                            }
                            else
                            {
                                errors.Add( exception.Message );
                                exception = exception.InnerException;
                            }
                        }
                        else
                        {
                            errors.Add( exception.Message );
                            exception = exception.InnerException;
                        }
                    }
                }

                if ( errors.Any() )
                {
                    nbEditModeMessage.NotificationBoxType = NotificationBoxType.Warning;
                    nbEditModeMessage.Text = "INFO: There was a problem with one or more of the report's data components...<br/><br/> " + errors.AsDelimited( "<br/>" );
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            // Find all the Group Types
            var groupTypeIds = GetAvailableGroupTypes();

            if ( ( GetAttributeValue( "DisplayFilter" ) ?? "false" ).AsBoolean() )
            {
                int groupTypeFilter = int.MinValue;
                if ( int.TryParse( gfSettings.GetUserPreference( "Group Type" ), out groupTypeFilter ) )
                {
                    groupTypeIds = groupTypeIds.Where( g => g == groupTypeFilter ).ToList();
                }
            }

            using ( new UnitOfWorkScope() )
            {
                SortProperty sortProperty = gGroups.SortProperty;
                if ( sortProperty == null )
                {
                    sortProperty = new SortProperty( new GridViewSortEventArgs( "GroupTypeOrder, GroupTypeName, GroupOrder, Name", SortDirection.Ascending ) );
                }
                bool onlySecurityGroups =  GetAttributeValue( "LimittoSecurityRoleGroups" ).FromTrueFalse();
                bool showDescriptionColumn = GetAttributeValue( "DisplayDescriptionColumn" ).FromTrueFalse();
                if ( !showDescriptionColumn )
                {
                    gGroups.TooltipField = "Description";
                }
                Dictionary<string, BoundField> boundFields = gGroups.Columns.OfType<BoundField>().ToDictionary( a => a.DataField );
                boundFields["GroupTypeName"].Visible = GetAttributeValue( "DisplayGroupTypeColumn" ).FromTrueFalse();
                boundFields["Description"].Visible = showDescriptionColumn;

                // Person context will exist if used on a person detail page
                var personContext = ContextEntity<Person>();
                if ( personContext != null )
                {
                    boundFields["GroupRole"].Visible = true;
                    boundFields["DateAdded"].Visible = true;
                    boundFields["MemberCount"].Visible = false;

                    gGroups.Actions.ShowAdd = false;
                    gGroups.IsDeleteEnabled = false;
                    gGroups.Columns.OfType<DeleteField>().ToList().ForEach( f => f.Visible = false);

                    int groupMemberEntityTypeId = EntityTypeCache.Read(typeof(GroupMember)).Id;
                    var audits = new AuditService().Queryable()
                        .Where( a => 
                            a.EntityTypeId == groupMemberEntityTypeId &&
                            a.AuditType == AuditType.Add);

                    gGroups.DataSource = new GroupMemberService().Queryable()
                        .Where( m => 
                            m.PersonId == personContext.Id &&
                            groupTypeIds.Contains(m.Group.GroupTypeId) &&
                            (!onlySecurityGroups || m.Group.IsSecurityRole) )
                        .Select( m => new 
                            {
                                Id = m.Group.Id,
                                Name = m.Group.Name,
                                GroupTypeName = m.Group.GroupType.Name,
                                GroupOrder = m.Group.Order,
                                GroupTypeOrder = m.Group.GroupType.Order,
                                Description = m.Group.Description,
                                IsSystem = m.Group.IsSystem,
                                GroupRole = m.GroupRole.Name,
                                DateAdded = audits.Where( a => a.EntityId == m.Id).Select(a => a.DateTime).FirstOrDefault(),
                                MemberCount = 0
                            })
                        .Sort(sortProperty)
                        .ToList();
                }
                else
                {
                    bool canEdit = IsUserAuthorized( "Edit" );
                    gGroups.Actions.ShowAdd = canEdit;
                    gGroups.IsDeleteEnabled = canEdit;

                    boundFields["GroupRole"].Visible = false;
                    boundFields["DateAdded"].Visible = false;
                    boundFields["MemberCount"].Visible = true;

                    gGroups.DataSource = new GroupService().Queryable()
                        .Where( g => 
                            groupTypeIds.Contains(g.GroupTypeId) &&
                            (!onlySecurityGroups || g.IsSecurityRole) )
                        .Select( g => new 
                            {
                                Id = g.Id,
                                Name = g.Name,
                                GroupTypeName = g.GroupType.Name,
                                GroupOrder = g.Order,
                                GroupTypeOrder = g.GroupType.Order,
                                Description = g.Description,
                                IsSystem = g.IsSystem,
                                GroupRole = "",
                                DateAdded = DateTime.MinValue,
                                MemberCount = g.Members.Count()
                            })
                        .Sort(sortProperty)
                        .ToList();
                }

                gGroups.DataBind();
            }
        }
Beispiel #12
0
        /// <summary>
        /// Shows the preview.
        /// </summary>
        /// <param name="report">The report.</param>
        /// <param name="gReport">The g report.</param>
        /// <param name="currentPerson">The current person.</param>
        /// <param name="databaseTimeoutSeconds">The database timeout seconds.</param>
        /// <param name="errorMessage">The error message.</param>
        public static void BindGrid( Report report, Grid gReport, Person currentPerson, int? databaseTimeoutSeconds, out string errorMessage )
        {
            errorMessage = null;
            if ( report != null )
            {
                var errors = new List<string>();

                if ( !report.EntityTypeId.HasValue )
                {
                    gReport.Visible = false;
                    return;
                }

                var rockContext = new RockContext();

                if ( !report.IsAuthorized( Authorization.VIEW, currentPerson ) )
                {
                    gReport.Visible = false;
                    return;
                }

                Type entityType = EntityTypeCache.Read( report.EntityTypeId.Value, rockContext ).GetEntityType();
                if ( entityType == null )
                {
                    errorMessage = string.Format( "Unable to determine entityType for {0}", report.EntityType );
                    return;
                }

                gReport.EntityTypeId = report.EntityTypeId;

                bool isPersonDataSet = report.EntityTypeId == EntityTypeCache.Read( typeof( Rock.Model.Person ), true, rockContext ).Id;

                if ( isPersonDataSet )
                {
                    gReport.PersonIdField = "Id";
                    gReport.DataKeyNames = new string[] { "Id" };
                }
                else
                {
                    gReport.PersonIdField = null;
                }

                if ( report.EntityTypeId.HasValue )
                {
                    gReport.RowItemText = EntityTypeCache.Read( report.EntityTypeId.Value, rockContext ).FriendlyName;
                }

                List<EntityField> entityFields = Rock.Reporting.EntityHelper.GetEntityFields( entityType, true, false );

                var selectedEntityFields = new Dictionary<int, EntityField>();
                var selectedAttributes = new Dictionary<int, AttributeCache>();
                var selectedComponents = new Dictionary<int, ReportField>();

                // if there is a selectField, keep it to preserve which items are checked
                var selectField = gReport.Columns.OfType<SelectField>().FirstOrDefault();
                gReport.Columns.Clear();
                int columnIndex = 0;

                if ( !string.IsNullOrWhiteSpace( gReport.PersonIdField ) )
                {
                    // if we already had a selectField, use it (to preserve checkbox state)
                    gReport.Columns.Add( selectField ?? new SelectField() );
                    columnIndex++;
                }

                var reportFieldSortExpressions = new Dictionary<Guid, string>();

                foreach ( var reportField in report.ReportFields.OrderBy( a => a.ColumnOrder ) )
                {
                    columnIndex++;
                    if ( reportField.ReportFieldType == ReportFieldType.Property )
                    {
                        var entityField = entityFields.FirstOrDefault( a => a.Name == reportField.Selection );
                        if ( entityField != null )
                        {
                            selectedEntityFields.Add( columnIndex, entityField );

                            BoundField boundField = entityField.GetBoundFieldType();
                            boundField.DataField = string.Format( "Entity_{0}_{1}", entityField.Name, columnIndex );
                            boundField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? entityField.Title : reportField.ColumnHeaderText;
                            boundField.SortExpression = boundField.DataField;
                            reportFieldSortExpressions.AddOrReplace( reportField.Guid, boundField.SortExpression );
                            boundField.Visible = reportField.ShowInGrid;
                            gReport.Columns.Add( boundField );
                        }
                    }
                    else if ( reportField.ReportFieldType == ReportFieldType.Attribute )
                    {
                        Guid? attributeGuid = reportField.Selection.AsGuidOrNull();
                        if ( attributeGuid.HasValue )
                        {
                            var attribute = AttributeCache.Read( attributeGuid.Value, rockContext );
                            if ( attribute != null )
                            {
                                selectedAttributes.Add( columnIndex, attribute );

                                BoundField boundField;

                                if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.BOOLEAN.AsGuid() ) )
                                {
                                    boundField = new BoolField();
                                }
                                else if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DEFINED_VALUE.AsGuid() ) )
                                {
                                    boundField = new DefinedValueField();
                                }
                                else
                                {
                                    boundField = new CallbackField();
                                    boundField.HtmlEncode = false;
                                    ( boundField as CallbackField ).OnFormatDataValue += (sender, e) => {
                                        string resultHtml = null;
                                        if (e.DataValue != null)
                                        {
                                            bool condensed = true;
                                            resultHtml = attribute.FieldType.Field.FormatValueAsHtml( gReport, e.DataValue.ToString(), attribute.QualifierValues, condensed );

                                        }

                                        e.FormattedValue = resultHtml ?? string.Empty;
                                    };
                                }

                                boundField.DataField = string.Format( "Attribute_{0}_{1}", attribute.Id, columnIndex );
                                boundField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? attribute.Name : reportField.ColumnHeaderText;
                                boundField.SortExpression = boundField.DataField;
                                reportFieldSortExpressions.AddOrReplace( reportField.Guid, boundField.SortExpression );

                                if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.INTEGER.AsGuid() ) ||
                                    attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE.AsGuid() ) ||
                                    attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.FILTER_DATE.AsGuid() ) )
                                {
                                    boundField.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
                                    boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                                }

                                boundField.Visible = reportField.ShowInGrid;

                                gReport.Columns.Add( boundField );
                            }
                        }
                    }
                    else if ( reportField.ReportFieldType == ReportFieldType.DataSelectComponent )
                    {
                        selectedComponents.Add( columnIndex, reportField );

                        DataSelectComponent selectComponent = DataSelectContainer.GetComponent( reportField.DataSelectComponentEntityType.Name );
                        if ( selectComponent != null )
                        {
                            try
                            {
                                DataControlField columnField = selectComponent.GetGridField( entityType, reportField.Selection ?? string.Empty );

                                if ( columnField is BoundField )
                                {
                                    ( columnField as BoundField ).DataField = string.Format( "Data_{0}_{1}", selectComponent.ColumnPropertyName, columnIndex );
                                    var customSortProperties = selectComponent.SortProperties( reportField.Selection ?? string.Empty );
                                    bool sortReversed = selectComponent.SortReversed( reportField.Selection ?? string.Empty );
                                    if ( customSortProperties != null )
                                    {
                                        if ( customSortProperties == string.Empty )
                                        {
                                            // disable sorting if customSortExpression set to string.empty
                                            columnField.SortExpression = string.Empty;
                                        }
                                        else
                                        {
                                            columnField.SortExpression = customSortProperties.Split( ',' ).Select( a => string.Format( "Sort_{0}_{1}", a, columnIndex ) ).ToList().AsDelimited( "," );
                                        }
                                    }
                                    else
                                    {
                                        // use default sorting if customSortExpression was null
                                        columnField.SortExpression = ( columnField as BoundField ).DataField;
                                    }

                                    if ( sortReversed == true && !string.IsNullOrWhiteSpace( columnField.SortExpression ) )
                                    {
                                        columnField.SortExpression = columnField.SortExpression + " DESC";
                                    }
                                }

                                columnField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? selectComponent.ColumnHeaderText : reportField.ColumnHeaderText;
                                if ( !string.IsNullOrEmpty( columnField.SortExpression ) )
                                {
                                    reportFieldSortExpressions.AddOrReplace( reportField.Guid, columnField.SortExpression );
                                }

                                columnField.Visible = reportField.ShowInGrid;
                                gReport.Columns.Add( columnField );
                            }
                            catch ( Exception ex )
                            {
                                ExceptionLogService.LogException( ex, HttpContext.Current );
                                errors.Add( string.Format( "{0} - {1}", selectComponent, ex.Message ) );
                            }
                        }
                    }
                }

                // if no fields are specified, show the default fields (Previewable/All) for the EntityType
                var dataColumns = gReport.Columns.OfType<object>().Where( a => a.GetType() != typeof( SelectField ) );
                if ( dataColumns.Count() == 0 )
                {
                    // show either the Previewable Columns or all (if there are no previewable columns)
                    bool showAllColumns = !entityFields.Any( a => a.FieldKind == FieldKind.Property && a.IsPreviewable );
                    foreach ( var entityField in entityFields.Where( a => a.FieldKind == FieldKind.Property ) )
                    {
                        columnIndex++;
                        selectedEntityFields.Add( columnIndex, entityField );

                        BoundField boundField = entityField.GetBoundFieldType();

                        boundField.DataField = string.Format( "Entity_{0}_{1}", entityField.Name, columnIndex );
                        boundField.HeaderText = entityField.Name;
                        boundField.SortExpression = boundField.DataField;
                        boundField.Visible = showAllColumns || entityField.IsPreviewable;
                        gReport.Columns.Add( boundField );
                    }
                }

                try
                {
                    gReport.Visible = true;
                    gReport.ExportFilename = report.Name;
                    SortProperty sortProperty = gReport.SortProperty;
                    if ( sortProperty == null )
                    {
                        var reportSort = new SortProperty();
                        var sortColumns = new Dictionary<string, SortDirection>();
                        foreach ( var reportField in report.ReportFields.Where( a => a.SortOrder.HasValue ).OrderBy( a => a.SortOrder.Value ) )
                        {
                            if ( reportFieldSortExpressions.ContainsKey( reportField.Guid ) )
                            {
                                var sortField = reportFieldSortExpressions[reportField.Guid];
                                if ( !string.IsNullOrWhiteSpace( sortField ) )
                                {
                                    sortColumns.Add( sortField, reportField.SortDirection );
                                }
                            }
                        }

                        if ( sortColumns.Any() )
                        {
                            reportSort.Property = sortColumns.Select( a => a.Key + ( a.Value == SortDirection.Descending ? " desc" : string.Empty ) ).ToList().AsDelimited( "," );
                            sortProperty = reportSort;
                        }
                    }

                    var qryErrors = new List<string>();
                    dynamic qry = report.GetQueryable( entityType, selectedEntityFields, selectedAttributes, selectedComponents, sortProperty, databaseTimeoutSeconds ?? 180, out qryErrors );
                    errors.AddRange( qryErrors );
                    gReport.SetLinqDataSource( qry );
                    gReport.DataBind();
                }
                catch ( Exception ex )
                {
                    Exception exception = ex;
                    ExceptionLogService.LogException( ex, HttpContext.Current );
                    while ( exception != null )
                    {
                        if ( exception is System.Data.SqlClient.SqlException )
                        {
                            // if there was a SQL Server Timeout, have the warning be a friendly message about that.
                            if ( ( exception as System.Data.SqlClient.SqlException ).Number == -2 )
                            {
                                errorMessage = "This report did not complete in a timely manner. You can try again or adjust the timeout setting of this block.";
                                return;
                            }
                            else
                            {
                                errors.Add( exception.Message );
                                exception = exception.InnerException;
                            }
                        }
                        else
                        {
                            errors.Add( exception.Message );
                            exception = exception.InnerException;
                        }
                    }
                }

                if ( errors.Any() )
                {
                    errorMessage = "WARNING: There was a problem with one or more of the report's data components...<br/><br/> " + errors.AsDelimited( "<br/>" );
                }
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var personAliasEntityType = EntityTypeCache.Read( "Rock.Model.PersonAlias" );
            if ( personAliasEntityType != null && CurrentPersonAlias != null )
            {
                var rockContext = new RockContext();

                // PersonAlias query for joining the followed entity id to
                var personAliasQry = new PersonAliasService( rockContext ).Queryable();

                // Get all the people that the current person currently follows
                var followedPersonIds = new FollowingService( rockContext ).Queryable()
                    .Where( f =>
                        f.EntityTypeId == personAliasEntityType.Id &&
                        f.PersonAliasId == CurrentPersonAlias.Id )
                    .Join( personAliasQry, s => s.EntityId, p => p.Id, ( s, p ) => p.PersonId )
                    .Distinct();

                // Get all the person suggestions for the current person that they are not already following
                var qry = new FollowingSuggestedService( rockContext )
                    .Queryable("SuggestionType")
                    .Where( s =>
                        s.SuggestionType != null &&
                        s.EntityTypeId == personAliasEntityType.Id &&
                        s.PersonAliasId == CurrentPersonAlias.Id )
                    .Join( personAliasQry, s => s.EntityId, p => p.Id, ( s, p ) => new { s, p } )
                    .Where( j => !followedPersonIds.Contains( j.p.PersonId ) )
                    .Select( j => new
                    {
                        j.s.Id,
                        j.s.LastPromotedDateTime,
                        j.s.StatusChangedDateTime,
                        j.s.SuggestionType.ReasonNote,
                        j.s.Status,
                        Person = j.p.Person,
                        LastName = j.p.Person.LastName,
                        NickName = j.p.Person.NickName
                    } );

                // Sort the result
                SortProperty sortProperty = gSuggestions.SortProperty;
                if ( sortProperty == null )
                {
                    sortProperty = new SortProperty( new GridViewSortEventArgs( "LastName,NickName", SortDirection.Ascending ) );
                }

                // Bind grid to the query
                gSuggestions.DataSource = qry.Sort( sortProperty )
                    .Select( s => new
                    {
                        s.Id,
                        s.LastPromotedDateTime,
                        s.StatusChangedDateTime,
                        s.ReasonNote,
                        s.Status,
                        StatusLabel = s.Status == FollowingSuggestedStatus.Ignored ?
                            "<span class='label label-warning'>Ignored</span>" :
                            "<span class='label label-success'>Suggested</span>",
                        s.Person,
                        s.LastName,
                        s.NickName
                    } )
                    .ToList();

                gSuggestions.DataBind();
            }
        }