using System; using System.Threading; namespace HRM.BO { /// /// How a long-running piece of work (salary process, bulk upload, ...) tells the outside world how far it got. /// /// It lives in HRM.BO on purpose: HRM.DA services take it as a plain parameter and never know who listens. /// HRM.UI implements it (background job runner + SignalR), so HRM.DA keeps no reference to ASP.NET or SignalR. /// Every member is safe to call as often as you like - the implementation throttles what it actually sends. /// A null IJobProgress means "nobody is listening": callers must check for null (or use TryReport below). /// public interface IJobProgress { /// Set when the application is shutting down or the job was cancelled. Work may check it between steps. CancellationToken CancellationToken { get; } /// /// Reports where the work is. /// /// 0 - 100 of the whole job. Values out of range are clamped; it never goes backwards. /// Short name of the current stage, e.g. "Calculating Income Tax". Null keeps the previous one. /// Optional extra line, e.g. an employee name. Null clears it. /// Optional items done in the current stage (shown as current / total). /// Optional items in the current stage. void Report(double percent, string stage = null, string detail = null, int? current = null, int? total = null); } public static class JobProgressExtensions { /// /// Null-safe AND exception-safe Report. Business code (salary process, uploads, ...) must report through this: /// progress only watches the work, so a fault in reporting must never be able to stop or change the work. /// public static void TryReport(this IJobProgress progress, double percent, string stage = null, string detail = null, int? current = null, int? total = null) { if (progress == null) return; try { progress.Report(percent, stage, detail, current, total); } catch { // progress is best-effort; the work goes on regardless } } } /// /// Maps a sub-task's own 0 - 100 onto a slice [from, to] of an outer job's bar. Lets a service report its /// own progress (e.g. the salary save, 0 - 100) without knowing which part of the whole job it is. /// public sealed class JobProgressScope : IJobProgress { private readonly IJobProgress _outer; private readonly double _from; private readonly double _to; public JobProgressScope(IJobProgress outer, double from, double to) { _outer = outer; _from = Math.Max(0, Math.Min(100, from)); _to = Math.Max(_from, Math.Min(100, to)); } public CancellationToken CancellationToken => _outer != null ? _outer.CancellationToken : CancellationToken.None; public void Report(double percent, string stage = null, string detail = null, int? current = null, int? total = null) { if (_outer == null) return; double p = Math.Max(0, Math.Min(100, percent)); _outer.Report(_from + (_to - _from) * p / 100.0, stage, detail, current, total); } } }