Created
February 10, 2012 17:43
-
-
Save tawman/1791186 to your computer and use it in GitHub Desktop.
DynamicReportSource Null Object Reference Fix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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