Skip to content

Instantly share code, notes, and snippets.

@tawman
Created February 10, 2012 17:43
Show Gist options
  • Save tawman/1791186 to your computer and use it in GitHub Desktop.
Save tawman/1791186 to your computer and use it in GitHub Desktop.
DynamicReportSource Null Object Reference Fix
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DoddleReport;
namespace Hasc.Web.Helpers
{
public static class DynamicReportSourceExtensions
{
public static IReportSource ToReportSource(this IEnumerable<dynamic> source)
{
return new DynamicReportSource(source);
}
}
/// <summary>
/// Generate a Report for a collection of dynamic ExpandoObjects
/// </summary>
public class DynamicReportSource : IReportSource
{
private readonly IEnumerable<dynamic> _source;
public DynamicReportSource(IEnumerable<dynamic> source)
{
_source = source;
}
public ReportFieldCollection GetFields()
{
var fields = new ReportFieldCollection();
var item = _source.FirstOrDefault();
if (item == null)
return fields;
foreach (var t in item)
{
fields.Add(t.Key, (t.Value ?? new object()).GetType());
}
return fields;
}
public IEnumerable GetItems()
{
return _source;
}
public object GetFieldValue(object dataItem, string fieldName)
{
if (dataItem == null)
return string.Empty;
var di = (IDictionary<string, object>)dataItem;
return di[fieldName];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment