Inheritance: RockBoundField
Example #1
0
 /// <summary>
 /// Handles the OnFormatDataValue event of the CallbackField control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="CallbackField.CallbackEventArgs"/> instance containing the event data.</param>
 /// <exception cref="System.NotImplementedException"></exception>
 protected void FormatGridDataValue( object sender, CallbackField.CallbackEventArgs e )
 {
     var fakePerson = new Rock.Model.Person();
     fakePerson.GraduationYear = e.DataValue as int?;
     e.FormattedValue = fakePerson.GradeFormatted;
 }
        /// <summary>
        /// Adds the attribute columns.
        /// </summary>
        private void AddDynamicControls()
        {
            // Clear the filter controls
            phAttributeFilters.Controls.Clear();

            // Remove attribute columns
            foreach ( var column in gWorkflows.Columns.OfType<AttributeField>().ToList() )
            {
                gWorkflows.Columns.Remove( column );
            }

            if ( AvailableAttributes != null )
            {
                foreach ( var attribute in AvailableAttributes )
                {
                    var control = attribute.FieldType.Field.FilterControl( attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false, Rock.Reporting.FilterMode.SimpleFilter );
                    if ( control is IRockControl )
                    {
                        var rockControl = (IRockControl)control;
                        rockControl.Label = attribute.Name;
                        rockControl.Help = attribute.Description;
                        phAttributeFilters.Controls.Add( control );
                    }
                    else
                    {
                        var wrapper = new RockControlWrapper();
                        wrapper.ID = control.ID + "_wrapper";
                        wrapper.Label = attribute.Name;
                        wrapper.Controls.Add( control );
                        phAttributeFilters.Controls.Add( wrapper );
                    }

                    string savedValue = gfWorkflows.GetUserPreference( MakeKeyUniqueToType( attribute.Key ) );
                    if ( !string.IsNullOrWhiteSpace( savedValue ) )
                    {
                        try
                        {
                            var values = JsonConvert.DeserializeObject<List<string>>( savedValue );
                            attribute.FieldType.Field.SetFilterValues( control, attribute.QualifierValues, values );
                        }
                        catch { }
                    }

                    string dataFieldExpression = attribute.Key;
                    bool columnExists = gWorkflows.Columns.OfType<AttributeField>().FirstOrDefault( a => a.DataField.Equals( dataFieldExpression ) ) != null;
                    if ( !columnExists )
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField = dataFieldExpression;
                        boundField.HeaderText = attribute.Name;
                        boundField.SortExpression = string.Empty;
                        boundField.Condensed = false;

                        var attributeCache = Rock.Web.Cache.AttributeCache.Read( attribute.Id );
                        if ( attributeCache != null )
                        {
                            boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                        }

                        gWorkflows.Columns.Add( boundField );
                    }
                }
            }

            var dateField = new DateTimeField();
            gWorkflows.Columns.Add( dateField );
            dateField.DataField = "CreatedDateTime";
            dateField.SortExpression = "CreatedDateTime";
            dateField.HeaderText = "Created";
            dateField.FormatAsElapsedTime = true;

            var statusField = new BoundField();
            gWorkflows.Columns.Add( statusField );
            statusField.DataField = "Status";
            statusField.SortExpression = "Status";
            statusField.HeaderText = "Status";
            statusField.DataFormatString = "<span class='label label-info'>{0}</span>";
            statusField.HtmlEncode = false;

            var stateField = new CallbackField();
            gWorkflows.Columns.Add( stateField );
            stateField.DataField = "IsCompleted";
            stateField.SortExpression = "CompletedDateTime";
            stateField.HeaderText = "State";
            stateField.HtmlEncode = false;
            stateField.OnFormatDataValue += ( sender, e ) =>
            {
                if ( (bool)e.DataValue )
                {
                    e.FormattedValue = "<span class='label label-default'>Completed</span>";
                }
                else
                {
                    e.FormattedValue = "<span class='label label-success'>Active</span>";
                }
            };

            if ( _canView )
            {
                var manageField = new LinkButtonField();
                gWorkflows.Columns.Add( manageField );
                manageField.CssClass = "btn btn-default btn-sm fa fa-file-text-o";
                manageField.Click += gWorkflows_Manage;
            }

            if ( _canEdit )
            {
                var deleteField = new DeleteField();
                gWorkflows.Columns.Add( deleteField );
                deleteField.Click += gWorkflows_Delete;
            }
        }
Example #3
0
        /// <summary>
        /// Gets the grid field.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override System.Web.UI.WebControls.DataControlField GetGridField( Type entityType, string selection )
        {
            var result = new CallbackField();
            result.OnFormatDataValue += FormatGridDataValue;

            return result;
        }
        /// <summary>
        /// Gets the grid field.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override System.Web.UI.WebControls.DataControlField GetGridField( Type entityType, string selection )
        {
            var callbackField = new CallbackField();
            string basePersonUrl = System.Web.VirtualPathUtility.ToAbsolute( "~/Person/" );
            string baseGroupMemberUrl = System.Web.VirtualPathUtility.ToAbsolute( "~/GroupMember/" );
            var selectionParts = selection.Split( '|' );
            ShowAsLinkType showAsLinkType = selectionParts.Length > 0 ? selectionParts[0].ConvertToEnum<ShowAsLinkType>( ShowAsLinkType.NameOnly ) : ShowAsLinkType.NameOnly;
            callbackField.OnFormatDataValue += ( sender, e ) =>
            {
                var groupMemberList = e.DataValue as IEnumerable<MemberInfo>;
                if ( groupMemberList != null )
                {
                    var formattedList = new List<string>();
                    foreach ( var groupMember in groupMemberList )
                    {
                        var formattedPersonFullName = Rock.Model.Person.FormatFullName( groupMember.NickName, groupMember.LastName, groupMember.SuffixValueId );
                        string formattedValue;
                        if ( showAsLinkType == ShowAsLinkType.PersonLink )
                        {
                            formattedValue = "<a href='" + basePersonUrl + groupMember.PersonId.ToString() + "'>" + formattedPersonFullName + "</a>";
                        }
                        else if ( showAsLinkType == ShowAsLinkType.GroupMemberLink )
                        {
                            formattedValue = "<a href='" + baseGroupMemberUrl + groupMember.GroupMemberId.ToString() + "'>" + formattedPersonFullName + "</a>";
                        }
                        else
                        {
                            formattedValue = formattedPersonFullName;
                        }

                        formattedList.Add( formattedValue );
                    }

                    e.FormattedValue = formattedList.AsDelimited( ", " );
                }
                else
                {
                    e.FormattedValue = string.Empty;
                }
            };

            return callbackField;
        }
Example #5
0
        /// <summary>
        /// Gets the grid field.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override System.Web.UI.WebControls.DataControlField GetGridField( Type entityType, string selection )
        {
            var callbackField = new CallbackField();
            var selectionParts = selection.Split( '|' );
            bool includeGender = selectionParts.Length > 0 && selectionParts[0].AsBoolean();
            bool includeAge = selectionParts.Length > 1 && selectionParts[1].AsBoolean();
            callbackField.OnFormatDataValue += ( sender, e ) =>
            {
                var personList = e.DataValue as IEnumerable<KidInfo>;
                if ( personList != null )
                {
                    var formattedList = new List<string>();
                    foreach ( var person in personList )
                    {
                        var formattedPerson = Rock.Model.Person.FormatFullName( person.NickName, person.LastName, person.SuffixValueId );
                        var formattedGenderAge = string.Empty;

                        if ( includeGender && person.Gender != Gender.Unknown )
                        {
                            // return F for Female, M for Male
                            if ( person.Gender == Gender.Female )
                            {
                                formattedGenderAge += "F";
                            }
                            else if ( person.Gender == Gender.Male )
                            {
                                formattedGenderAge += "M";
                            }
                        }

                        int? age = Rock.Model.Person.GetAge( person.BirthDate );

                        if ( includeAge && age.HasValue )
                        {
                            formattedGenderAge += " " + age.Value.ToString();
                        }

                        if ( !string.IsNullOrWhiteSpace( formattedGenderAge ) )
                        {
                            formattedPerson += " (" + formattedGenderAge.Trim() + ")";
                        }

                        formattedList.Add( formattedPerson );
                    }

                    e.FormattedValue = formattedList.AsDelimited( ", " );
                }
                else
                {
                    e.FormattedValue = string.Empty;
                }
            };

            return callbackField;
        }
Example #6
0
 /// <summary>
 /// Handles the OnFormatDataValue event of the gActionsPath control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="CallbackField.CallbackEventArgs"/> instance containing the event data.</param>
 protected void gActionsPath_OnFormatDataValue( object sender, CallbackField.CallbackEventArgs e )
 {
     e.FormattedValue = e.DataValue.ToString();
     if ( e.FormattedValue.EndsWith( "?key={key}" ) )
     {
         e.FormattedValue = e.FormattedValue.Replace( "?key={key}", "(id)" );
     }
 }
Example #7
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;

                                // 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 );
                                var customSortExpression = selectComponent.SortProperties( reportField.Selection );
                                if ( customSortExpression != null )
                                {
                                    if ( customSortExpression == string.Empty )
                                    {
                                        // disable sorting if customSortExpression set to string.empty
                                        columnField.SortExpression = string.Empty;
                                    }
                                    else
                                    {
                                        columnField.SortExpression = customSortExpression.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;
                                }
                            }

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

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

                    dynamic qry = report.GetQueryable( entityType, selectedEntityFields, selectedAttributes, selectedComponents, sortProperty, databaseTimeoutSeconds ?? 180, out errors );
                    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/>" );
                }
            }
        }