diff --git a/HRM.BO/VirtualGrid/VirtualGrid.cs b/HRM.BO/VirtualGrid/VirtualGrid.cs
deleted file mode 100644
index d423bc5..0000000
--- a/HRM.BO/VirtualGrid/VirtualGrid.cs
+++ /dev/null
@@ -1,110 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace HRM.BO
-{
- ///
- /// Common virtual-scrolling grid ("virtual grid") contracts.
- ///
- /// Every large list screen shares ONE BO / DA / Service / Controller: a screen is just a registered
- /// grid definition (HRM.DA/Service/VirtualGrid/Definitions) identified by .
- /// The server pages, sorts, searches and exports; the browser only ever holds one window of rows.
- /// See HRM.DA/Service/VirtualGrid/README.md for how to add a grid.
- ///
- public enum EnumVirtualGridColumnType
- {
- Text = 1,
- Number = 2,
- Money = 3,
- Date = 4,
- DateTime = 5
- }
-
- /// A column as the screen sees it (from the layout endpoint).
- public class VirtualGridColumnInfo
- {
- public string Field { get; set; }
- public string Title { get; set; }
- public int Width { get; set; }
- public EnumVirtualGridColumnType Type { get; set; }
- public bool Sortable { get; set; }
- }
-
- /// Everything the screen needs to draw an empty grid before any data is requested.
- public class VirtualGridLayout
- {
- public string GridKey { get; set; }
- public string Title { get; set; }
- public string DefaultSortField { get; set; }
- public string DefaultSortDir { get; set; }
- public int MaxPageSize { get; set; }
- public List Columns { get; set; } = new List();
- }
-
- /// One window request: which grid, its filters, and the grid's skip/take, sort and search.
- public class VirtualGridRequest
- {
- public string GridKey { get; set; }
-
- ///
- /// Screen-specific filters (e.g. fromDate / toDate as "yyyy-MM-dd"). Each grid definition reads and
- /// validates the ones it needs; values are never spliced into SQL.
- ///
- public Dictionary Filters { get; set; } = new Dictionary();
-
- public int Skip { get; set; }
- public int Take { get; set; } = 100;
- public string Search { get; set; }
- public string SortField { get; set; }
- public string SortDir { get; set; }
-
- ///
- /// True on Preview: reload the data instead of using the copy kept in server memory (list grids).
- /// Scrolling, sorting and searching send false and are answered from that copy.
- ///
- public bool Refresh { get; set; }
- }
-
- /// Excel export: the same request plus the grid's visible columns, in order.
- public class VirtualGridExportRequest : VirtualGridRequest
- {
- /// Fields of the columns to export, in grid order. Empty = every column of the grid.
- public List Fields { get; set; } = new List();
- }
-
- public class VirtualGridPage
- {
- /// Rows matching the filters and the search.
- public int Total { get; set; }
-
- /// Rows matching the filters alone (equals Total when there is no search).
- public int TotalWithoutSearch { get; set; }
-
- /// One row per entry, keyed by column field. Values are raw (dates, numbers); the screen formats them.
- public List> Data { get; set; } = new List>();
- }
-
- /// A generated file (Excel export).
- public class VirtualGridFile
- {
- public string FileName { get; set; }
- public string ContentType { get; set; }
- public byte[] Content { get; set; }
- }
-
- /// The signed-in user, as the grid definitions need it for scoping (payroll type) and access.
- public class VirtualGridContext
- {
- public int UserID { get; set; }
- public int? EmployeeID { get; set; }
- public int? PayrollTypeID { get; set; }
- public EnumUserType UserType { get; set; }
- }
-
- public interface IVirtualGridService
- {
- VirtualGridLayout GetLayout(string gridKey, VirtualGridContext context);
- VirtualGridPage GetPage(VirtualGridRequest request, VirtualGridContext context);
- VirtualGridFile ExportExcel(VirtualGridExportRequest request, VirtualGridContext context);
- }
-}
diff --git a/HRM.BO/VirtualPaging/VirtualPaging.cs b/HRM.BO/VirtualPaging/VirtualPaging.cs
new file mode 100644
index 0000000..85e9cbf
--- /dev/null
+++ b/HRM.BO/VirtualPaging/VirtualPaging.cs
@@ -0,0 +1,74 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+
+namespace HRM.BO
+{
+ ///
+ /// What <app-virtual-grid> sends to a page endpoint: the page's own filters plus the grid's
+ /// scroll position, search text and sort. The same class is used by every page, so no page needs a
+ /// request class of its own. See HRM.DA/Service/VirtualPaging/README.md.
+ ///
+ public class VirtualPageRequest
+ {
+ /// The page's filters, e.g. { fromDate: "2025-01-01", toDate: "2025-12-31" }. Read them with GetDate / GetInt / GetString.
+ public Dictionary Filters { get; set; } = new Dictionary();
+
+ /// The grid's columns (property names). Only these are sent back and searched.
+ public List Fields { get; set; } = new List();
+
+ public int Skip { get; set; }
+
+ /// Rows wanted. 0 = all rows (used by Export to Excel).
+ public int Take { get; set; } = 100;
+
+ public string Search { get; set; }
+ public string SortField { get; set; }
+
+ /// "asc" or "desc".
+ public string SortDir { get; set; }
+
+ /// True on Preview: load the data again. False on scroll/sort/search/export: use the kept copy.
+ public bool Refresh { get; set; }
+
+ /// A filter as text, or null when it was not sent.
+ public string GetString(string name)
+ {
+ string value;
+ if (Filters != null && Filters.TryGetValue(name, out value) && !string.IsNullOrWhiteSpace(value))
+ return value.Trim();
+ return null;
+ }
+
+ /// A "yyyy-MM-dd" filter. Throws a message fit for the user when it is missing or invalid.
+ public DateTime GetDate(string name, string label = null)
+ {
+ DateTime value;
+ if (!DateTime.TryParseExact(GetString(name), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
+ throw new ArgumentException("Please select a valid " + (label ?? name) + ".");
+ return value;
+ }
+
+ /// A whole-number filter. Throws a message fit for the user when it is missing or invalid.
+ public int GetInt(string name, string label = null)
+ {
+ int value;
+ if (!int.TryParse(GetString(name), NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
+ throw new ArgumentException("Please select a valid " + (label ?? name) + ".");
+ return value;
+ }
+ }
+
+ /// One window of rows for the grid.
+ public class VirtualPageResult
+ {
+ /// Rows matching the search (all rows when there is no search).
+ public int Total { get; set; }
+
+ /// All rows, ignoring the search.
+ public int TotalWithoutSearch { get; set; }
+
+ /// The rows of this window, holding only the requested fields.
+ public List> Data { get; set; } = new List>();
+ }
+}
diff --git a/HRM.DA/DA/VirtualGrid/VirtualGridDA.cs b/HRM.DA/DA/VirtualGrid/VirtualGridDA.cs
deleted file mode 100644
index 24fd9fb..0000000
--- a/HRM.DA/DA/VirtualGrid/VirtualGridDA.cs
+++ /dev/null
@@ -1,110 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Linq;
-using Ease.Core.DataAccess;
-using Ease.Core.DataAccess.SQL;
-using HRM.BO;
-using Microsoft.Data.SqlClient;
-
-namespace HRM.DA
-{
- ///
- /// Everything VirtualGridDA needs to build a grid's SQL. Built by VirtualGridService from a grid
- /// definition; all SQL fragments in it are code-produced (definition expressions, whitelisted sort,
- /// integer lists), and all user values are parameters.
- ///
- internal sealed class VirtualGridQuery
- {
- /// "sqlExpression AS [alias]" entries.
- public List Select { get; } = new List();
-
- public VirtualGridSource Source { get; set; }
-
- /// Columns searched with LIKE, with the type that decides how each is rendered as text.
- public List> SearchColumns { get; } =
- new List>();
-
- /// Extra OR-branches of the search (code-produced, e.g. "e.DEPARTMENTID IN (1,2)").
- public List SearchPredicates { get; } = new List();
-
- /// The escaped LIKE pattern ("%text%"), or null for no search.
- public string SearchPattern { get; set; }
-
- /// Whitelisted sort expression including ASC/DESC.
- public string OrderBy { get; set; }
-
- public string TieBreaker { get; set; }
- }
-
- ///
- /// The one data-access class behind every virtual grid: a COUNT and an OFFSET/FETCH window (or every
- /// row, for Excel) over the grid's source, with search and sort done by SQL Server.
- ///
- internal static class VirtualGridDA
- {
- internal static int Count(TransactionContext tc, VirtualGridQuery query, bool withSearch)
- {
- string sql = "SELECT COUNT(*) " + query.Source.FromWhere + SearchClause(query, withSearch);
- object value = tc.ExecuteScalar(CommandType.Text, sql, Parameters(query, withSearch, null, null));
- return value == null || value == DBNull.Value ? 0 : Convert.ToInt32(value);
- }
-
- /// One window of rows; with null, every row (Excel export).
- internal static IDataReader GetRows(TransactionContext tc, VirtualGridQuery query, int skip, int? take)
- {
- string sql = "SELECT " + string.Join(", ", query.Select) + " "
- + query.Source.FromWhere + SearchClause(query, true)
- + " ORDER BY " + query.OrderBy + ", " + query.TieBreaker + " ASC";
- if (take.HasValue)
- sql += " OFFSET @__Skip ROWS FETCH NEXT @__Take ROWS ONLY";
- return tc.ExecuteReader(CommandType.Text, sql, Parameters(query, true, skip, take));
- }
-
- /// A column as the screen displays it, so the user can search what they see.
- private static string AsDisplayText(string sql, EnumVirtualGridColumnType type)
- {
- switch (type)
- {
- case EnumVirtualGridColumnType.Date:
- return "CONVERT(varchar(11), " + sql + ", 106)"; // 13 Feb 2025
- case EnumVirtualGridColumnType.DateTime:
- return "(CONVERT(varchar(11), " + sql + ", 106) + ' ' + CONVERT(varchar(5), " + sql + ", 108))";
- case EnumVirtualGridColumnType.Money:
- return "CONVERT(varchar(30), CAST(" + sql + " AS money), 1)"; // 1,234.56
- case EnumVirtualGridColumnType.Number:
- return "CONVERT(varchar(40), " + sql + ")";
- default:
- return sql;
- }
- }
-
- private static string SearchClause(VirtualGridQuery query, bool withSearch)
- {
- if (!withSearch || string.IsNullOrEmpty(query.SearchPattern))
- return string.Empty;
-
- List parts = query.SearchColumns
- .Select(c => AsDisplayText(c.Key, c.Value) + @" LIKE @__Search ESCAPE '\'")
- .Concat(query.SearchPredicates)
- .ToList();
- return parts.Count == 0 ? " AND 1 = 0" : " AND (" + string.Join(" OR ", parts) + ")";
- }
-
- private static IDataParameter[] Parameters(VirtualGridQuery query, bool withSearch, int? skip, int? take)
- {
- // Clones: a SqlParameter cannot belong to two commands, and one query runs several.
- var list = query.Source.Parameters
- .Select(p => (SqlParameter)((ICloneable)p).Clone())
- .ToList();
- if (withSearch && !string.IsNullOrEmpty(query.SearchPattern))
- list.Add(SqlHelperExtension.CreateInParam("@__Search", SqlDbType.NVarChar, query.SearchPattern, 400));
- if (take.HasValue)
- {
- list.Add(SqlHelperExtension.CreateInParam("@__Skip", SqlDbType.Int, skip ?? 0));
- list.Add(SqlHelperExtension.CreateInParam("@__Take", SqlDbType.Int, take.Value));
- }
- return list.ToArray();
- }
- }
-}
diff --git a/HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs b/HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs
deleted file mode 100644
index c65bc77..0000000
--- a/HRM.DA/Service/VirtualGrid/Definitions/DiscontinueEmployeeVirtualGrid.cs
+++ /dev/null
@@ -1,103 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using HRM.BO;
-using HRM.BO.Report;
-
-namespace HRM.DA
-{
- ///
- /// Discontinue Employee Details (Manage Employee › Report, /reports/discontinue-employee-details):
- /// employees discontinued inside a date range, with the same columns as Employee Details plus the
- /// Discontinue Date.
- ///
- /// The data comes the usual way — EmployeeService.GetDiscontinuedEmployeeDetails returns a
- /// List<DiscontinueEmployeeDetailInfo> (query in EmployeeDA) — and the common virtual grid pages it.
- /// Filters: fromDate, toDate ("yyyy-MM-dd", both required). Scoped to the user's payroll type.
- ///
- internal sealed class DiscontinueEmployeeVirtualGrid : VirtualGridListDefinition
- {
- public const string GridKey = "discontinue-employee";
-
- public override string Key => GridKey;
- public override string Title => "Discontinue Employee Details";
- public override string DefaultSortField => "employeeNo";
- public override string ExcelFileName => "DiscontinueEmployeeDetails.xlsx";
-
- /// Each Field is a property of DiscontinueEmployeeDetailInfo.
- public override List GetColumns(VirtualGridContext context)
- {
- var columns = new List
- {
- new VirtualGridColumn { Field = "employeeNo", Title = "Employee No", Width = 110 },
- new VirtualGridColumn { Field = "name", Title = "Employee Name", Width = 220 },
- new VirtualGridColumn { Field = "gender", Title = "Gender", Width = 100 },
- new VirtualGridColumn { Field = "birthDate", Title = "Birth Date", Width = 120, Type = EnumVirtualGridColumnType.Date },
- new VirtualGridColumn { Field = "joiningDate", Title = "Joining Date", Width = 120, Type = EnumVirtualGridColumnType.Date },
- new VirtualGridColumn { Field = "discontinueDate", Title = "Discontinue Date", Width = 140, Type = EnumVirtualGridColumnType.Date },
- new VirtualGridColumn { Field = "mobileNo", Title = "Mobile No", Width = 130 },
- new VirtualGridColumn { Field = "emailAddress", Title = "Email Address", Width = 200 },
- new VirtualGridColumn { Field = "designation", Title = "Designation", Width = 160 },
- new VirtualGridColumn { Field = "grade", Title = "Grade", Width = 120 },
- new VirtualGridColumn { Field = "category", Title = "Category", Width = 120 },
- new VirtualGridColumn { Field = "status", Title = "Status", Width = 120 },
- };
-
- // Department tier headings come from the Logic configuration, as in Employee Details.
- string[] tierFields = { "deptireOne", "deptireTwo", "deptireThree", "deptireFour", "deptireFive" };
- List configs = new SystemConfigarationService()
- .GetAllChildrenByParentNode(EnumConfigurationType.Logic, "department") ?? new List();
- int tier = 0;
- foreach (SystemConfigaration c in configs)
- {
- if (!string.Equals(c.Node, "text", StringComparison.OrdinalIgnoreCase))
- continue;
- if (tier < tierFields.Length)
- columns.Add(new VirtualGridColumn { Field = tierFields[tier], Title = c.Value, Width = 150 });
- tier++;
- }
-
- columns.AddRange(new[]
- {
- new VirtualGridColumn { Field = "location", Title = "Location", Width = 130 },
- new VirtualGridColumn { Field = "religion", Title = "Religion", Width = 110 },
- new VirtualGridColumn { Field = "maritalStatus", Title = "Marital Status", Width = 120 },
- new VirtualGridColumn { Field = "dateOfConfirmation", Title = "Confirmation", Width = 120, Type = EnumVirtualGridColumnType.Date },
- new VirtualGridColumn { Field = "basicSalary", Title = "Basic Salary", Width = 120, Type = EnumVirtualGridColumnType.Money },
- new VirtualGridColumn { Field = "grossSalary", Title = "Gross Salary", Width = 120, Type = EnumVirtualGridColumnType.Money },
- new VirtualGridColumn { Field = "passportNo", Title = "Passport No", Width = 120 },
- new VirtualGridColumn { Field = "bloodGroup", Title = "Blood Group", Width = 110 },
- new VirtualGridColumn { Field = "lineManagerNo", Title = "LineManager No", Width = 130 },
- new VirtualGridColumn { Field = "lineManagerName", Title = "LineManager Name", Width = 180 },
- new VirtualGridColumn { Field = "lineManagerEmail", Title = "LineManager Email", Width = 200 },
- new VirtualGridColumn { Field = "empStatus", Title = "Employee Status", Width = 130 },
- new VirtualGridColumn { Field = "bank", Title = "Bank", Width = 150 },
- new VirtualGridColumn { Field = "branch", Title = "Branch", Width = 150 },
- new VirtualGridColumn { Field = "accountNo", Title = "Account No", Width = 150 },
- new VirtualGridColumn { Field = "nationalId", Title = "National ID/NID", Width = 150 },
- new VirtualGridColumn { Field = "tinNo", Title = "TIN", Width = 120 },
- });
- return columns;
- }
-
- protected override List LoadData(VirtualGridFilters filters, VirtualGridContext context)
- {
- DateTime fromDate = filters.GetDate("fromDate", "From Date", true).Value;
- DateTime toDate = filters.GetDate("toDate", "To Date", true).Value;
- if (fromDate > toDate)
- throw new ArgumentException("From Date cannot be after To Date.");
- if (!context.PayrollTypeID.HasValue)
- throw new ArgumentException("No payroll type is selected for your login.");
-
- return new EmployeeService().GetDiscontinuedEmployeeDetails(fromDate, toDate, context.PayrollTypeID.Value);
- }
-
- public override string DescribeFilters(VirtualGridFilters filters)
- {
- DateTime? fromDate = filters.GetDate("fromDate", "From Date", false);
- DateTime? toDate = filters.GetDate("toDate", "To Date", false);
- return "Discontinued from " + fromDate?.ToString("dd MMM yyyy", CultureInfo.InvariantCulture)
- + " to " + toDate?.ToString("dd MMM yyyy", CultureInfo.InvariantCulture);
- }
- }
-}
diff --git a/HRM.DA/Service/VirtualGrid/README.md b/HRM.DA/Service/VirtualGrid/README.md
deleted file mode 100644
index 0ad94e6..0000000
--- a/HRM.DA/Service/VirtualGrid/README.md
+++ /dev/null
@@ -1,88 +0,0 @@
-# Virtual grid — common virtual-scrolling grid for large lists
-
-One common controller, service and Angular component serve every virtual-scrolling list. The data
-still comes **the usual way**: a service method returns a `List` (query in the module's DA). A grid
-only says *which* service method to call and *which* columns to show.
-
-| Layer | File | Role |
-|---|---|---|
-| BO | `HRM.BO/VirtualGrid/VirtualGrid.cs` | Request/page/layout DTOs, `EnumVirtualGridColumnType`, `IVirtualGridService` |
-| Service | `HRM.DA/Service/VirtualGrid/VirtualGridService.cs` | Access check, keeps the loaded list in memory, search/sort/page, Excel |
-| Grids | `HRM.DA/Service/VirtualGrid/Definitions/*.cs` | **One small class per grid**: columns + which service to call |
-| Registry | `HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs` | Key → grid. Unlisted keys cannot be queried |
-| Controller | `HRM.UI/Controllers/CommonInterface/VirtualGridController.cs` | `GET api/virtualGrid/layout/{key}`, `POST page`, `POST export-excel` |
-| Angular | `custom-components/virtual-grid/` (`VirtualGridModule`, ``) | Virtual scrolling, search box, sort, total, Excel button |
-
-## How it works
-
-1. Screen opens → the component asks for the grid's columns (`layout`).
-2. **Preview** → `grid.load(filters)` → `page` with `refresh: true` → the grid's `LoadData` calls the
- service (e.g. `EmployeeService.GetDiscontinuedEmployeeDetails`) → the whole `List` is kept in
- server memory (per user + filters, 10 min sliding / 30 min max) → the first 100 rows go back.
-3. **Scroll / sort / search** → `page` with `refresh: false` → answered from the kept list: search,
- sort, `Skip/Take` 100. The service is not called again.
-4. **Export to Excel** → every matching row of the kept list, same order, as `.xlsx`.
-
-The browser only ever holds ~100 rows, however long the list is.
-
-## Adding a grid (existing screen with a service that already returns a list)
-
-1. **Grid class** — `Definitions/VirtualGrid.cs`:
- ```csharp
- internal sealed class LeaveHistoryVirtualGrid : VirtualGridListDefinition
- {
- public const string GridKey = "leave-history";
- public override string Key => GridKey;
- public override string Title => "Leave History";
-
- public override List GetColumns(VirtualGridContext context) => new List
- {
- // Field = a property of LeaveEntry (camelCase)
- new VirtualGridColumn { Field = "employeeNo", Title = "Employee No", Width = 110 },
- new VirtualGridColumn { Field = "fromDate", Title = "From", Width = 120, Type = EnumVirtualGridColumnType.Date },
- new VirtualGridColumn { Field = "amount", Title = "Amount", Width = 120, Type = EnumVirtualGridColumnType.Money },
- };
-
- protected override List LoadData(VirtualGridFilters filters, VirtualGridContext context)
- {
- DateTime from = filters.GetDate("fromDate", "From Date", true).Value; // user-facing errors
- DateTime to = filters.GetDate("toDate", "To Date", true).Value;
- return new LeaveEntryService().Get(from, to, context.PayrollTypeID.Value); // the existing service
- }
- }
- ```
-2. **Registry** — `{ LeaveHistoryVirtualGrid.GridKey, () => new LeaveHistoryVirtualGrid() }`.
-3. **Screen** — import `VirtualGridModule`, then:
- ```html
-
- ```
- ```ts
- this.grid.load({ fromDate: '2025-01-01', toDate: '2025-12-31' }); // filters as strings
- ```
-
-No new controller, Angular service or model. For a brand-new screen, write its query in the module's
-DA and a service method returning `List` (as always), then steps 1–3.
-
-Worked example: `Definitions/DiscontinueEmployeeVirtualGrid.cs` →
-`EmployeeService.GetDiscontinuedEmployeeDetails` → `EmployeeDA.GetDiscontinuedEmployeeDetails`.
-
-## Column types
-
-`Text` (default), `Number`, `Money` (`1,234.56`), `Date` (`dd MMM yyyy`), `DateTime` (`dd MMM yyyy HH:mm`).
-The screen shows values in that format and the search box searches that same text, so users find what
-they see. Set `Sortable = false` / `Searchable = false` on a column to turn either off.
-
-## Very large lists: `VirtualGridSqlDefinition` (advanced)
-
-A list grid loads the whole list once per Preview — fine up to tens of thousands of rows. When even
-that is too slow, derive from `VirtualGridSqlDefinition` instead: give each column a `Sql` expression
-and a `BuildSource` returning `FROM … WHERE …` with parameters, and SQL Server pages each request
-(`OFFSET/FETCH`, `HRM.DA/DA/VirtualGrid/VirtualGridDA.cs`). User values reach SQL only as parameters;
-spliced text is code-produced only.
-
-## Rules
-
-- A service a grid calls must not run one query per row; load lookups once (see `GetDiscontinuedEmployeeDetails`).
-- Self-service (ESS) logins are refused unless the grid sets `AllowSelfServiceUsers`. Authorization in
- this app is menu-driven, so add any further check a grid needs in `LoadData`.
-- The kept list is per user, payroll type, grid and filter values; Preview always reloads it.
diff --git a/HRM.DA/Service/VirtualGrid/VirtualGridDefinition.cs b/HRM.DA/Service/VirtualGrid/VirtualGridDefinition.cs
deleted file mode 100644
index 02f8de1..0000000
--- a/HRM.DA/Service/VirtualGrid/VirtualGridDefinition.cs
+++ /dev/null
@@ -1,271 +0,0 @@
-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);
- }
-}
diff --git a/HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs b/HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs
deleted file mode 100644
index e1357d4..0000000
--- a/HRM.DA/Service/VirtualGrid/VirtualGridRegistry.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace HRM.DA
-{
- ///
- /// Every virtual grid the application serves, by key. Adding a grid = one definition class in
- /// Definitions/ and one line here. A key that is not listed here cannot be queried.
- ///
- internal static class VirtualGridRegistry
- {
- private static readonly Dictionary> Grids =
- new Dictionary>(StringComparer.OrdinalIgnoreCase)
- {
- { DiscontinueEmployeeVirtualGrid.GridKey, () => new DiscontinueEmployeeVirtualGrid() },
- };
-
- /// A fresh definition instance for one call. Throws ArgumentException for an unknown key.
- internal static VirtualGridDefinition Create(string gridKey)
- {
- Func factory;
- if (string.IsNullOrWhiteSpace(gridKey) || !Grids.TryGetValue(gridKey.Trim(), out factory))
- throw new ArgumentException("Unknown grid: " + gridKey);
- return factory();
- }
- }
-}
diff --git a/HRM.DA/Service/VirtualGrid/VirtualGridService.cs b/HRM.DA/Service/VirtualGrid/VirtualGridService.cs
deleted file mode 100644
index a5a3863..0000000
--- a/HRM.DA/Service/VirtualGrid/VirtualGridService.cs
+++ /dev/null
@@ -1,591 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Text;
-using ClosedXML.Excel;
-using Ease.Core.DataAccess;
-using Ease.Core.Model;
-using Ease.Core.Utility;
-using HRM.BO;
-using Microsoft.Extensions.Caching.Memory;
-
-namespace HRM.DA
-{
- ///
- /// The one service behind every virtual-scrolling grid (api/virtualGrid). It looks the grid up in
- /// and serves it in one of two ways:
- ///
- /// - List grid (): the grid's existing service returns a
- /// List of business objects; that list is kept in server memory for a few minutes and every scroll,
- /// sort, search and Excel export is answered from it.
- /// - SQL grid (): SQL Server counts, sorts, searches and returns
- /// one OFFSET/FETCH window per request (VirtualGridDA).
- ///
- /// Shared work for both: access check, column validation, paging limits, sort whitelist, the Excel file.
- ///
- public class VirtualGridService : ServiceTemplate, IVirtualGridService
- {
- private const int ExportCommandTimeoutSeconds = 600;
- private const int MaxSearchLength = 200;
- private const string ExcelContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
-
- // List grids: loaded lists, per user + grid + filters. Size = rows, so at most ~1,000,000 rows are
- // held in total; the least recently used lists are dropped first.
- private static readonly MemoryCache ListCache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 1000000 });
- private static readonly TimeSpan ListCacheSliding = TimeSpan.FromMinutes(10);
- private static readonly TimeSpan ListCacheAbsolute = TimeSpan.FromMinutes(30);
-
- #region Public API
-
- public VirtualGridLayout GetLayout(string gridKey, VirtualGridContext context)
- {
- VirtualGridDefinition grid = Open(gridKey, context);
- List columns = GetValidatedColumns(grid, context);
- VirtualGridColumn defaultSort = DefaultSortColumn(grid, columns);
-
- var layout = new VirtualGridLayout
- {
- GridKey = grid.Key,
- Title = grid.Title,
- DefaultSortField = defaultSort?.Field,
- DefaultSortDir = NormalizeDir(grid.DefaultSortDir),
- MaxPageSize = grid.MaxPageSize,
- };
- layout.Columns.AddRange(columns.Select(c => new VirtualGridColumnInfo
- {
- Field = c.Field,
- Title = c.Title,
- Width = c.Width,
- Type = c.Type,
- Sortable = grid.CanSort(c),
- }));
- return layout;
- }
-
- public VirtualGridPage GetPage(VirtualGridRequest request, VirtualGridContext context)
- {
- if (request == null)
- throw new ArgumentException("Invalid request.");
- VirtualGridDefinition grid = Open(request.GridKey, context);
- List columns = GetValidatedColumns(grid, context);
- int skip = Math.Max(0, request.Skip);
- int take = Math.Min(Math.Max(1, request.Take), grid.MaxPageSize);
-
- var listSource = grid as IVirtualGridListSource;
- if (listSource != null)
- {
- CachedList list = GetList(grid, listSource, columns, request, context);
- List matches = Search(list, request.Search);
- List ordered = Sort(grid, columns, list, matches, request);
- return new VirtualGridPage
- {
- Total = ordered.Count,
- TotalWithoutSearch = list.Rows.Count,
- Data = ordered.Skip(skip).Take(take).Select(i => list.Rows[i]).ToList(),
- };
- }
-
- var sqlGrid = (VirtualGridSqlDefinition)grid;
- VirtualGridQuery query = BuildQuery(sqlGrid, columns, request, context);
- var page = new VirtualGridPage();
- TransactionContext tc = null;
- try
- {
- tc = TransactionContext.Begin();
- page.Total = VirtualGridDA.Count(tc, query, true);
- page.TotalWithoutSearch = query.SearchPattern == null ? page.Total : VirtualGridDA.Count(tc, query, false);
- if (page.Total > skip)
- page.Data = ReadRows(VirtualGridDA.GetRows(tc, query, skip, take));
- tc.End();
- }
- catch (Exception e)
- {
- #region Handle Exception
- if (tc != null)
- tc.HandleError();
- ExceptionLog.Write(e);
- throw new ServiceException(e.Message, e);
- #endregion
- }
-
- // After the transaction: definitions may call other services that open their own.
- FinishRows(sqlGrid, page.Data, context);
- return page;
- }
-
- public VirtualGridFile ExportExcel(VirtualGridExportRequest request, VirtualGridContext context)
- {
- if (request == null)
- throw new ArgumentException("Invalid request.");
- VirtualGridDefinition grid = Open(request.GridKey, context);
- List columns = GetValidatedColumns(grid, context);
- List exportColumns = ResolveExportColumns(columns, request.Fields);
-
- List> rows;
- string filterDescription;
-
- var listSource = grid as IVirtualGridListSource;
- if (listSource != null)
- {
- CachedList list = GetList(grid, listSource, columns, request, context);
- List ordered = Sort(grid, columns, list, Search(list, request.Search), request);
- CheckExportLimit(grid, ordered.Count);
- rows = ordered.Select(i => list.Rows[i]).ToList();
- filterDescription = listSource.DescribeFilters(new VirtualGridFilters(request.Filters));
- }
- else
- {
- var sqlGrid = (VirtualGridSqlDefinition)grid;
- VirtualGridQuery query = BuildQuery(sqlGrid, columns, request, context);
- TransactionContext tc = null;
- try
- {
- tc = TransactionContext.Begin();
- tc.CommandTimeOut = ExportCommandTimeoutSeconds;
- CheckExportLimit(grid, VirtualGridDA.Count(tc, query, true));
- rows = ReadRows(VirtualGridDA.GetRows(tc, query, 0, null));
- tc.End();
- }
- catch (ArgumentException)
- {
- if (tc != null)
- tc.HandleError();
- throw;
- }
- catch (Exception e)
- {
- #region Handle Exception
- if (tc != null)
- tc.HandleError();
- ExceptionLog.Write(e);
- throw new ServiceException(e.Message, e);
- #endregion
- }
- FinishRows(sqlGrid, rows, context);
- filterDescription = query.Source.FilterDescription;
- }
-
- return new VirtualGridFile
- {
- FileName = grid.ExcelFileName,
- ContentType = ExcelContentType,
- Content = BuildWorkbook(grid, exportColumns, rows, filterDescription, request.Search),
- };
- }
-
- #endregion
-
- #region Shared helpers
-
- /// Finds the grid and checks the user may use it. Unknown key → ArgumentException.
- private static VirtualGridDefinition Open(string gridKey, VirtualGridContext context)
- {
- if (context == null)
- throw new UnauthorizedAccessException("Not signed in.");
- VirtualGridDefinition grid = VirtualGridRegistry.Create(gridKey);
- if (!(grid is IVirtualGridListSource) && !(grid is VirtualGridSqlDefinition))
- throw new InvalidOperationException("Virtual grid '" + grid.Key
- + "' must derive from VirtualGridListDefinition or VirtualGridSqlDefinition.");
- if (context.UserType == EnumUserType.Employee && !grid.AllowSelfServiceUsers)
- throw new UnauthorizedAccessException("You do not have access to " + grid.Title + ".");
- return grid;
- }
-
- /// The definition's columns, checked so a bad definition fails loudly.
- private static List GetValidatedColumns(VirtualGridDefinition grid, VirtualGridContext context)
- {
- List columns = grid.GetColumns(context) ?? new List();
- var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
- foreach (VirtualGridColumn c in columns)
- {
- if (!VirtualGridDefinition.IsIdentifier(c.Field) || c.Field.StartsWith("_") || !seen.Add(c.Field))
- throw new InvalidOperationException("Virtual grid '" + grid.Key + "' has an invalid or duplicate column field: " + c.Field);
- }
- if (columns.Count == 0)
- throw new InvalidOperationException("Virtual grid '" + grid.Key + "' has no columns.");
- return columns;
- }
-
- private static VirtualGridColumn DefaultSortColumn(VirtualGridDefinition grid, List columns)
- {
- VirtualGridColumn byName = columns.FirstOrDefault(c => grid.CanSort(c)
- && string.Equals(c.Field, grid.DefaultSortField, StringComparison.OrdinalIgnoreCase));
- return byName ?? columns.FirstOrDefault(c => grid.CanSort(c));
- }
-
- /// The column to sort by and its direction: a sortable column the user picked, else the grid's default.
- private static VirtualGridColumn ResolveSort(VirtualGridDefinition grid, List columns,
- VirtualGridRequest request, out bool descending)
- {
- VirtualGridColumn picked = columns.FirstOrDefault(c => grid.CanSort(c)
- && string.Equals(c.Field, request.SortField, StringComparison.OrdinalIgnoreCase));
- descending = NormalizeDir(picked != null ? request.SortDir : grid.DefaultSortDir) == "desc";
- return picked ?? DefaultSortColumn(grid, columns);
- }
-
- private static string NormalizeDir(string dir) =>
- string.Equals(dir, "desc", StringComparison.OrdinalIgnoreCase) ? "desc" : "asc";
-
- private static string CleanSearch(string search)
- {
- string term = (search ?? string.Empty).Trim();
- return term.Length > MaxSearchLength ? term.Substring(0, MaxSearchLength) : term;
- }
-
- private static void CheckExportLimit(VirtualGridDefinition grid, int total)
- {
- if (total > grid.ExportRowLimit)
- throw new ArgumentException("There are " + total.ToString("N0", CultureInfo.InvariantCulture)
- + " rows; Excel export is limited to " + grid.ExportRowLimit.ToString("N0", CultureInfo.InvariantCulture)
- + ". Please narrow the filters or the search.");
- }
-
- ///
- /// A value as the screen shows it (dates "dd MMM yyyy", money "1,234.56"), so the search box finds
- /// what the user sees. Mirrors the formatting in <app-virtual-grid>.
- ///
- private static string DisplayText(object value, EnumVirtualGridColumnType type)
- {
- if (value == null)
- return string.Empty;
- switch (type)
- {
- case EnumVirtualGridColumnType.Date:
- if (value is DateTime d) return d.ToString("dd MMM yyyy", CultureInfo.InvariantCulture);
- break;
- case EnumVirtualGridColumnType.DateTime:
- if (value is DateTime dt) return dt.ToString("dd MMM yyyy HH:mm", CultureInfo.InvariantCulture);
- break;
- case EnumVirtualGridColumnType.Money:
- if (value is IConvertible && !(value is string))
- return Convert.ToDecimal(value, CultureInfo.InvariantCulture).ToString("N2", CultureInfo.InvariantCulture);
- break;
- }
- return Convert.ToString(value, CultureInfo.InvariantCulture);
- }
-
- #endregion
-
- #region List grids (existing service + in-memory paging)
-
- /// A loaded list plus, per row, the text the search box looks in.
- private sealed class CachedList
- {
- public List> Rows;
- public List SearchText;
- }
-
- ///
- /// The grid's list for this user and these filters: from the cache, or — on Preview (Refresh) or
- /// when the cache has expired — freshly from the grid's service.
- ///
- private static CachedList GetList(VirtualGridDefinition grid, IVirtualGridListSource source,
- List columns, VirtualGridRequest request, VirtualGridContext context)
- {
- string key = CacheKey(grid, columns, request, context);
- CachedList list;
- if (!request.Refresh && ListCache.TryGetValue(key, out list))
- return list;
-
- List> rows = source.LoadRows(new VirtualGridFilters(request.Filters), context, columns);
-
- List searchable = columns.Where(c => grid.CanSearch(c)).ToList();
- var searchText = new List(rows.Count);
- var sb = new StringBuilder();
- foreach (Dictionary row in rows)
- {
- sb.Clear();
- foreach (VirtualGridColumn c in searchable)
- {
- object value;
- row.TryGetValue(c.Field, out value);
- sb.Append(DisplayText(value, c.Type)).Append('\u0001'); // separator: no match across two columns
- }
- searchText.Add(sb.ToString());
- }
-
- list = new CachedList { Rows = rows, SearchText = searchText };
- ListCache.Set(key, list, new MemoryCacheEntryOptions
- {
- Size = Math.Max(1, rows.Count),
- SlidingExpiration = ListCacheSliding,
- AbsoluteExpirationRelativeToNow = ListCacheAbsolute,
- });
- return list;
- }
-
- /// One list per user, payroll type, grid and filter values (and column set, in case configuration changes).
- private static string CacheKey(VirtualGridDefinition grid, List columns,
- VirtualGridRequest request, VirtualGridContext context)
- {
- var sb = new StringBuilder();
- sb.Append(grid.Key.ToLowerInvariant())
- .Append('|').Append(context.UserID)
- .Append('|').Append(context.PayrollTypeID)
- .Append('|').Append((int)context.UserType)
- .Append('|').Append(string.Join(",", columns.Select(c => c.Field)));
- foreach (KeyValuePair f in (request.Filters ?? new Dictionary())
- .OrderBy(f => f.Key, StringComparer.OrdinalIgnoreCase))
- sb.Append('|').Append(f.Key.ToLowerInvariant()).Append('=').Append(f.Value);
- return sb.ToString();
- }
-
- /// Indexes of the rows whose shown text contains the search (case-insensitive); all rows when there is none.
- private static List Search(CachedList list, string search)
- {
- string term = CleanSearch(search);
- var result = new List(term.Length == 0 ? list.Rows.Count : 64);
- for (int i = 0; i < list.Rows.Count; i++)
- {
- if (term.Length == 0 || list.SearchText[i].IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0)
- result.Add(i);
- }
- return result;
- }
-
- /// Sorts row indexes by the chosen column (stable, so equal values keep the service's order).
- private static List Sort(VirtualGridDefinition grid, List columns, CachedList list,
- List indexes, VirtualGridRequest request)
- {
- bool descending;
- VirtualGridColumn sortColumn = ResolveSort(grid, columns, request, out descending);
- if (sortColumn == null)
- return indexes;
-
- string field = sortColumn.Field;
- Func keyOf = i =>
- {
- object value;
- list.Rows[i].TryGetValue(field, out value);
- return value;
- };
- return (descending
- ? indexes.OrderByDescending(keyOf, ValueComparer.Instance)
- : indexes.OrderBy(keyOf, ValueComparer.Instance))
- .ToList();
- }
-
- /// Compares cell values: empty first, numbers as numbers, dates as dates, text case-insensitively.
- private sealed class ValueComparer : IComparer