using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace Umbraco.Core
{
///
/// Static and extension methods for the DataTable object
///
public static class DataTableExtensions
{
///
/// Creates a DataTable with the specified alias and columns and uses a callback to populate the headers.
///
///
///
///
///
///
/// This has been migrated from the Node class and uses proper locking now. It is now used by the Node class and the
/// DynamicPublishedContent extensions for legacy reasons.
///
public static DataTable GenerateDataTable(
string tableAlias,
Func>> getHeaders,
Func>, IEnumerable>>>> rowData)
{
var dt = new DataTable(tableAlias);
//get all row data
var tableData = rowData().ToArray();
//get all headers
var propertyHeaders = GetPropertyHeaders(tableAlias, getHeaders);
foreach(var h in propertyHeaders)
{
dt.Columns.Add(new DataColumn(h.Value));
}
//add row data
foreach(var r in tableData)
{
dt.PopulateRow(
propertyHeaders,
r.Item1,
r.Item2);
}
return dt;
}
///
/// Helper method to return this ugly object
///
///
///
/// This is for legacy code, I didn't want to go creating custom classes for these
///
public static List>, IEnumerable>>> CreateTableData()
{
return new List>, IEnumerable>>>();
}
///
/// Helper method to deal with these ugly objects
///
///
///
///
///
/// This is for legacy code, I didn't want to go creating custom classes for these
///
public static void AddRowData(
List>, IEnumerable>>> rowData,
IEnumerable> standardVals,
IEnumerable> userVals)
{
rowData.Add(new System.Tuple>, IEnumerable>>(
standardVals,
userVals
));
}
private static IDictionary GetPropertyHeaders(string alias, Func>> getHeaders)
{
var headers = getHeaders(alias);
var def = headers.ToDictionary(pt => pt.Key, pt => pt.Value);
return def;
}
private static void PopulateRow(
this DataTable dt,
IDictionary aliasesToNames,
IEnumerable> standardVals,
IEnumerable> userPropertyVals)
{
var dr = dt.NewRow();
foreach (var r in standardVals)
{
dr[r.Key] = r.Value;
}
foreach (var p in userPropertyVals.Where(p => p.Value != null))
{
dr[aliasesToNames[p.Key]] = p.Value;
}
dt.Rows.Add(dr);
}
}
}