using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using HRM.BO; using Microsoft.Data.SqlClient; namespace HRM.DA { /// /// One column of a virtual grid. Field is the name the screen uses. In a list grid it is a property /// of the business object; in a SQL grid it is the alias of Sql, the expression the column selects, /// sorts and searches by (null = filled in code, not sorted or searched by SQL). /// internal sealed class VirtualGridColumn { public string Field { get; set; } public string Title { get; set; } public int Width { get; set; } = 130; public EnumVirtualGridColumnType Type { get; set; } = EnumVirtualGridColumnType.Text; public string Sql { get; set; } public bool Sortable { get; set; } = true; public bool Searchable { get; set; } = true; } /// /// The rows a grid is built on: a "FROM ... WHERE ..." clause plus its parameters. /// Filter values must only ever reach SQL through . /// internal sealed class VirtualGridSource { public string FromWhere { get; set; } public List Parameters { get; } = new List(); /// Human-readable filter summary, printed at the top of the Excel file. public string FilterDescription { get; set; } } /// /// Extra search conditions a definition adds for values that are worked out in code (e.g. department /// tier names): each becomes one more OR branch of the search. Only code-produced SQL goes here. /// internal sealed class VirtualGridSearchExtras { internal List Predicates { get; } = new List(); /// Adds "sqlExpression IN (v1, v2, …)" — the values are integers, so they are safe to splice. public void AddIntIn(string sqlExpression, IEnumerable values) { List list = (values ?? Enumerable.Empty()).Distinct().ToList(); if (list.Count > 0) Predicates.Add(sqlExpression + " IN (" + string.Join(",", list.Select(v => v.ToString(CultureInfo.InvariantCulture))) + ")"); } } /// /// Typed, validated access to . Every problem is an /// ArgumentException with a message fit to show the user (the controller returns it as 400). /// internal sealed class VirtualGridFilters { private readonly Dictionary _values; public VirtualGridFilters(Dictionary values) { _values = new Dictionary(values ?? new Dictionary(), StringComparer.OrdinalIgnoreCase); } public string GetString(string name) { string value; return _values.TryGetValue(name, out value) && !string.IsNullOrWhiteSpace(value) ? value.Trim() : null; } /// A "yyyy-MM-dd" date. is the name the user sees ("From Date"). public DateTime? GetDate(string name, string label, bool required) { string text = GetString(name); if (text == null) { if (required) throw new ArgumentException("Please select " + label + "."); return null; } DateTime value; if (!DateTime.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out value)) throw new ArgumentException("Please select a valid " + label + "."); return value; } public int? GetInt(string name, string label, bool required) { string text = GetString(name); if (text == null) { if (required) throw new ArgumentException("Please select " + label + "."); return null; } int value; if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) throw new ArgumentException("Please select a valid " + label + "."); return value; } } /// /// Base class of every virtual grid: what the grid is called, its columns and its limits. /// A grid derives from one of the two kinds below, never from this class directly: /// /// - VirtualGridListDefinition<T> (the usual choice): LoadData calls an ordinary service method /// that returns a List of business objects, exactly as screens always get their data. The common /// service keeps that list in memory and pages, sorts, searches and exports it on the server. /// - VirtualGridSqlDefinition (for very large lists): the grid gives a FROM/WHERE and SQL Server /// does the paging, so only one window of rows is ever read. /// /// A new instance is created for every call, so a definition may keep per-call state. /// internal abstract class VirtualGridDefinition { private static readonly Regex Identifier = new Regex("^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.Compiled); /// The key the screen sends (e.g. "discontinue-employee"). public abstract string Key { get; } public abstract string Title { get; } public virtual string DefaultSortField => null; // null = first sortable column public virtual string DefaultSortDir => "asc"; /// Self-service (ESS) logins are refused unless a grid opts in. public virtual bool AllowSelfServiceUsers => false; public virtual int MaxPageSize => 500; /// Largest Excel export allowed; past it the user is asked to narrow the filters. public virtual int ExportRowLimit => 200000; public virtual string ExcelFileName => Regex.Replace(Title, "[^A-Za-z0-9]+", "") + ".xlsx"; /// The grid's columns, in display order. May depend on configuration (e.g. department tier names). public abstract List GetColumns(VirtualGridContext context); /// Whether the user can sort by this column. internal virtual bool CanSort(VirtualGridColumn column) => column.Sortable; /// Whether the search box looks in this column. internal virtual bool CanSearch(VirtualGridColumn column) => column.Searchable; internal static bool IsIdentifier(string name) => name != null && Identifier.IsMatch(name); } /// /// A grid filled from an ordinary service method that returns a list of business objects, the way /// screens have always loaded their data: /// /// protected override List<LeaveEntry> LoadData(VirtualGridFilters filters, VirtualGridContext context) /// => new LeaveEntryService().Get(...); /// /// Each column's Field is the name of a property of T (camelCase, matched case-insensitively); /// Sql is not used. /// /// The list is loaded on Preview and kept in server memory for a few minutes, so scrolling, sorting /// and searching do not call the service again. Suits lists up to tens of thousands of rows; for /// larger ones use VirtualGridSqlDefinition. /// internal abstract class VirtualGridListDefinition : VirtualGridDefinition, IVirtualGridListSource where T : class { /// Reads/validates the filters and returns the rows, usually with one call to an existing service. protected abstract List LoadData(VirtualGridFilters filters, VirtualGridContext context); /// Human-readable filter summary, printed at the top of the Excel file. Optional. public virtual string DescribeFilters(VirtualGridFilters filters) => null; /// Calls LoadData and turns each object into a row holding just the grid's columns. List> IVirtualGridListSource.LoadRows( VirtualGridFilters filters, VirtualGridContext context, List columns) { var properties = new List>(); foreach (VirtualGridColumn c in columns) { PropertyInfo property = FindProperty(c.Field); if (property == null || !property.CanRead) throw new InvalidOperationException("Virtual grid '" + Key + "': " + typeof(T).Name + " has no readable property for column '" + c.Field + "'."); properties.Add(new KeyValuePair(c.Field, property)); } List items = LoadData(filters, context) ?? new List(); var rows = new List>(items.Count); foreach (T item in items) { if (item == null) continue; var row = new Dictionary(properties.Count, StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair p in properties) row[p.Key] = p.Value.GetValue(item); rows.Add(row); } return rows; } /// /// The public property named (case-insensitive). When a class hides a base /// property with "new" (e.g. EmployeeDetailInfo.Status over the base Status), the most derived one — /// the one the business object itself shows — wins. /// private static PropertyInfo FindProperty(string field) { PropertyInfo best = null; int bestDepth = int.MaxValue; foreach (PropertyInfo p in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (!string.Equals(p.Name, field, StringComparison.OrdinalIgnoreCase) || p.GetIndexParameters().Length > 0) continue; int depth = 0; for (Type t = typeof(T); t != null && t != p.DeclaringType; t = t.BaseType) depth++; if (depth < bestDepth) { best = p; bestDepth = depth; } } return best; } } /// Non-generic view of a list grid, used by VirtualGridService. internal interface IVirtualGridListSource { List> LoadRows(VirtualGridFilters filters, VirtualGridContext context, List columns); string DescribeFilters(VirtualGridFilters filters); } /// /// A grid whose paging, sorting and searching run in SQL Server: for very large lists, where loading /// every row (even once) is too slow. Each column's Sql is the expression it selects, sorts and searches /// by; a column with Sql = null is filled in OnRowsLoaded. /// internal abstract class VirtualGridSqlDefinition : VirtualGridDefinition { /// A unique, stable SQL expression (usually the primary key) used as the last sort key so pages never overlap. public abstract string TieBreakerSql { get; } /// /// Extra values selected for OnRowsLoaded only, as "sqlExpression AS _alias". /// Aliases must start with '_'; they are removed from the rows before they leave the server. /// public virtual IEnumerable HiddenSelect => Enumerable.Empty(); /// Reads/validates the filters and returns the FROM/WHERE the grid is built on. public abstract VirtualGridSource BuildSource(VirtualGridFilters filters, VirtualGridContext context); /// Adds OR-conditions for code-computed values matching the search text. Optional. public virtual void AddSearchExtras(string term, VirtualGridSearchExtras extras, VirtualGridContext context) { } /// Fills code-computed columns (and reformats values) on one loaded window of rows. Optional. public virtual void OnRowsLoaded(List> rows, VirtualGridContext context) { } internal override bool CanSort(VirtualGridColumn column) => column.Sortable && !string.IsNullOrEmpty(column.Sql); internal override bool CanSearch(VirtualGridColumn column) => column.Searchable && !string.IsNullOrEmpty(column.Sql); } }