// Copyright (c) Umbraco. // See LICENSE for more details. using System.Data; namespace Umbraco.Extensions; /// /// 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 Tuple>, IEnumerable>>[] tableData = rowData().ToArray(); // get all headers IDictionary propertyHeaders = GetPropertyHeaders(tableAlias, getHeaders); foreach (KeyValuePair h in propertyHeaders) { dt.Columns.Add(new DataColumn(h.Value)); } // add row data foreach (Tuple>, IEnumerable>> 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() => 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 Tuple>, IEnumerable>>( standardVals, userVals)); private static IDictionary GetPropertyHeaders( string alias, Func>> getHeaders) { IEnumerable> 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) { DataRow dr = dt.NewRow(); foreach (KeyValuePair r in standardVals) { dr[r.Key] = r.Value; } foreach (KeyValuePair p in userPropertyVals.Where(p => p.Value != null)) { dr[aliasesToNames[p.Key]] = p.Value; } dt.Rows.Add(dr); } }