Given the following class:
public class PayrollReport
{
[UiGridColumn(Name = "fullName",Visible = false,Width = "90")]
public string FullName { get; set; }
[UiGridColumn(Name = "weekStart", CellFilter = "date")]
public DateTime WeekStart { get; set; }
}
And this custom attribute
[AttributeUsage(AttributeTargets.All)]
public class UiGridColumn : Attribute
{
public string CellFilter { get; set; }
public string DisplayName { get; set; }
public string Name { get; set; }
public bool Visible { get; set; }
public string Width { get; set; }
}
I want to create a List<UiGridColumn> for each field with only the provided values (I don't want a null for the skipped properties).
Is it possible to create a List<UiGridColumn> where each List item has only the provided values? (I fear this isn't possible, but thought I would ask) If so, how?
If not, my second preference would be a string array like this:
[{"name":"fullName","visible":false,"width":"90"},{"name":"weekStart","cellFilter":"date"}]
I would prefer to not loop through each property and attribute and argument to manually build the desired JSON string, but I haven't been able to find an easy way to do it otherwise.
public List<Object> GetUiGridColumnDef(string className)
{
Assembly assembly = typeof(DynamicReportService).Assembly;
var type = assembly.GetType(className);
var properties = type.GetProperties();
var columnDefs = new List<object>();
foreach (var property in properties)
{
var column = new Dictionary<string, Object>();
var attributes = property.CustomAttributes;
foreach (var attribute in attributes)
{
if (attribute.AttributeType.Name != typeof(UiGridColumn).Name || attribute.NamedArguments == null)
continue;
foreach (var argument in attribute.NamedArguments)
{
column.Add(argument.MemberName, argument.TypedValue.Value);
}
}
columnDefs.Add(column);
}
return columnDefs;
}
Is there a better way to do this?