Skip to content

Report Templates ​

Templates are the heart of GrydReports. They define the structure, metadata, and supported formats for each report type using a code-first approach.

IReportTemplate<TData> ​

Every template implements IReportTemplate<TData>. A listed format can be generated only when a matching renderer is registered. The shipped renderer packages provide PDF, Excel, and CSV; Html is an enum value without a shipped renderer.

csharp
public interface IReportTemplate<in TData>
{
    string TemplateId { get; }                              // Unique identifier
    string DisplayName { get; }                             // Human-readable name
    string? Description { get; }                            // Optional description
    IReadOnlyList<ReportFormat> SupportedFormats { get; }   // Must match registered renderers
    IReadOnlyList<ReportParameterDefinition> Parameters { get; }  // Input params
    PageSettings PageSettings { get; }                      // Page layout (default A4)
    ReportMetadata GetMetadata(TData data);                 // Dynamic metadata
}

Basic Template ​

csharp
public class MonthlyBillingTemplate : IReportTemplate<BillingData>
{
    public string TemplateId => "monthly-billing";
    public string DisplayName => "Monthly Billing Report";
    public string? Description => "Customer billing summary by month";

    public IReadOnlyList<ReportFormat> SupportedFormats =>
        [ReportFormat.Pdf, ReportFormat.Excel, ReportFormat.Csv];

    public IReadOnlyList<ReportParameterDefinition> Parameters =>
    [
        new("month", "Month", "int", required: true),
        new("year", "Year", "int", required: true),
        new("customerId", "Customer ID", "guid", required: false)
    ];

    public ReportMetadata GetMetadata(BillingData data) => new()
    {
        Title = $"Billing - {data.MonthName} {data.Year}",
        Author = "Finance Department",
        Subject = "Monthly Billing Summary",
        Keywords = "billing, finance, monthly"
    };
}

Parameters ​

Define typed input parameters with validation and defaults:

csharp
public IReadOnlyList<ReportParameterDefinition> Parameters =>
[
    // Required string parameter
    new("customerId", "Customer", "guid", required: true),

    // Optional with default
    new("format", "Output Format", "string", required: false,
        defaultValue: "detailed"),

    // With allowed values (dropdown in UIs)
    new("status", "Status Filter", "string", required: false,
        allowedValues: ["active", "inactive", "all"],
        defaultValue: "active"),

    // Date range
    new("fromDate", "Start Date", "datetime", required: true),
    new("toDate", "End Date", "datetime", required: true),

    // Numeric parameter
    new("minAmount", "Minimum Amount", "decimal", required: false,
        defaultValue: 0m,
        description: "Filter transactions above this amount")
];

Parameter definitions stored with report definitions preserve the parameter name, display label, CLR value type, required flag, default, ordered allowed values, and description. Defaults and allowed values are written and read using the declared CLR type, so values such as decimals, dates, GUIDs, and enums keep their types. A missing or null allowed-values list remains distinct from an empty list.

Stored type names are resolved only against assemblies already loaded by the host. New assembly- qualified identities require the matching assembly identity and version to be loaded when stored definitions are reloaded. Legacy full-name type identities remain readable only when they resolve unambiguously in loaded assemblies. Unknown or ambiguous types and malformed parameter values fail explicitly; the reader does not replace invalid metadata with an empty parameter list. A value type must round-trip through System.Text.Json as its declared type; untyped object values are not persisted. The stored metadata is a snapshot of the definition. HTTP metadata currently comes from templates registered in the live process.

The Reports Infrastructure persistence tests use the real Reports migrations and a PostgreSQL Testcontainer. Run them with:

sh
dotnet test tests/Modules/Reports/GrydReports.Infrastructure.Tests/GrydReports.Infrastructure.Tests.csproj \
  --collect:"Code Coverage" \
  --settings coverage.runsettings

Docker must be available for this project in the Reports test shard.

Page Settings ​

Control page layout for renderers that support it:

csharp
public PageSettings PageSettings => new()
{
    Size = PageSize.A4,
    Orientation = PageOrientation.Landscape,
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 25,
    MarginRight = 25
};

Data Sources ​

Standard Data Source ​

For queries that return a complete dataset:

csharp
public class BillingDataSource : IReportDataSource<BillingData, BillingParameters>
{
    private readonly IBillingRepository _billing;

    public BillingDataSource(IBillingRepository billing) => _billing = billing;

    public async Task<BillingData> FetchDataAsync(
        BillingParameters parameters, CancellationToken ct)
    {
        var invoices = await _billing.GetByPeriodAsync(
            parameters.Year, parameters.Month, ct);

        return new BillingData
        {
            Year = parameters.Year,
            MonthName = new DateTime(parameters.Year, parameters.Month, 1).ToString("MMMM"),
            Invoices = invoices,
            TotalAmount = invoices.Sum(i => i.Total)
        };
    }

    // Optional: validate parameters before execution
    public async Task<Result> ValidateParametersAsync(
        BillingParameters parameters, CancellationToken ct)
    {
        if (parameters.Month < 1 || parameters.Month > 12)
            return Result.Failure("Month must be between 1 and 12");

        if (parameters.Year < 2020 || parameters.Year > DateTime.UtcNow.Year)
            return Result.Failure("Year is out of range");

        return Result.Success();
    }
}

Streaming data source extension point ​

IStreamingReportDataSource<TRecord, TParams> (StreamDataAsync and GetEstimatedCountAsync) is consumed by the streaming export only. /generate does not resolve it. A source looks like this:

csharp
public class TransactionStreamSource
    : IStreamingReportDataSource<TransactionRecord, TransactionParams>
{
    private readonly ITransactionRepository _repo;

    public TransactionStreamSource(ITransactionRepository repo) => _repo = repo;

    public async IAsyncEnumerable<TransactionRecord> StreamDataAsync(
        TransactionParams parameters,
        [EnumeratorCancellation] CancellationToken ct)
    {
        await foreach (var tx in _repo.StreamByDateRangeAsync(
            parameters.FromDate, parameters.ToDate, ct))
        {
            yield return new TransactionRecord
            {
                Id = tx.Id,
                Date = tx.Date,
                Amount = tx.Amount,
                Description = tx.Description
            };
        }
    }

    public async Task<long> GetEstimatedCountAsync(
        TransactionParams parameters, CancellationToken ct)
    {
        return await _repo.CountByDateRangeAsync(
            parameters.FromDate, parameters.ToDate, ct);
    }
}

Streaming export registration ​

A template is exportable only after it is registered. The source is registered as a scoped service; the record and parameter types are closed, so nothing is resolved by reflection:

csharp
services.AddScoped<IStreamingReportDataSource<TransactionRecord, TransactionParams>, TransactionStreamSource>();
services.AddReportExport<TransactionRecord, TransactionParams>("transactions");

// optional: refuses parameters before any row is read
services.AddScoped<IValidator<TransactionParams>, TransactionParamsValidator>();

The source reads under the session's tenant and must not materialize the result. With EF Core, stream the query:

csharp
public async IAsyncEnumerable<TransactionRecord> StreamDataAsync(
    TransactionParams parameters, [EnumeratorCancellation] CancellationToken ct)
{
    var rows = _db.Transactions
        .AsNoTracking()
        .Where(t => t.Date >= parameters.FromDate && t.Date <= parameters.ToDate)
        .OrderBy(t => t.Id)
        .Select(t => new TransactionRecord { Id = t.Id, Date = t.Date, Amount = t.Amount })
        .AsAsyncEnumerable();

    await foreach (var row in rows.WithCancellation(ct))
        yield return row;   // never ToListAsync
}

GetEstimatedCountAsync may be a cheap estimate: the row ceiling is also enforced while writing. The record type is the CSV: its public properties are the columns. A new output format is a new IReportStreamWriter; the pipeline does not change.

Entity export: one-line registration ​

For a table the host already queries with EF, there is no need to write a source or a parameter type:

csharp
services.AddEntityExport<Customer>(
    "customers",
    sp => sp.GetRequiredService<AppDbContext>().Customers.AsNoTracking().OrderBy(c => c.Id),
    export => export
        .Filterable(c => c.Name, c => c.Status, c => c.CreatedAt)
        .Exclude(c => c.InternalNotes));
  • The query is the host's. It already carries the tenant filter; the export adds conditions to it and nothing else, and streams the result (no ToListAsync).
  • Columns: every scalar property, minus Exclude(...) and [ReportExportIgnore]. The client narrows them with columns. Mark what must never leave (hashes, internal flags) with [ReportExportIgnore] on the entity.
  • Filters: none until Filterable(...) opens a property; asking for another is refused. Filtering on a property that is not an exported column is refused at registration.
  • A request filters with a list of conditions, all of which must hold (at most 20):
json
{
  "templateId": "customers",
  "format": "Csv",
  "parameters": {
    "filters": [
      { "field": "name", "op": "contains", "value": "silva" },
      { "field": "createdAt", "op": "gte", "value": "2026-01-01" },
      { "field": "status", "op": "eq", "value": "Active" }
    ]
  },
  "columns": ["Name", "Status", "CreatedAt"]
}
Field typeOperators
texteq, ne, contains, startsWith (contains and startsWith ignore case)
number, dateeq, ne, gt, gte, lt, lte
boolean, enum, GUIDeq, ne

field ignores case; an enum value is its name or its number; null is accepted by eq and ne on a nullable field. Anything else — an undeclared field, an operator the type does not take, a value of the wrong type — is REPORT_EXPORT_PARAMETERS_INVALID, before any row is read. Values reach the database as parameters, never as SQL text.

Multi-Format Templates ​

Templates can support multiple output formats. The renderer is selected at generation time:

csharp
public class ProductCatalogTemplate : IReportTemplate<CatalogData>
{
    public string TemplateId => "product-catalog";
    public string DisplayName => "Product Catalog";

    public IReadOnlyList<ReportFormat> SupportedFormats =>
        [ReportFormat.Pdf, ReportFormat.Excel, ReportFormat.Csv];

    // ...
}

Each format is rendered by its respective IReportRenderer:

FormatRendererPackageBest For
PdfQuestPDFGrydReports.Infrastructure.QuestPdfPrintable documents with layouts
ExcelClosedXMLGrydReports.Infrastructure.ClosedXmlSpreadsheets with formulas
CsvCsvHelperGrydReports.Infrastructure.CsvHelperData exports, ETL pipelines
HtmlNone shipped; host may provide IReportRendererHost packageRequires a host-registered renderer

Registration ​

Auto-Discovery ​

With AutoRegisterTemplates = true (default), templates are discovered automatically from assemblies:

csharp
opts.AutoRegisterTemplates = true;
opts.TemplateAssemblies.Add(typeof(MyTemplate).Assembly);

Manual Registration ​

csharp
builder.Services.AddSingleton<IReportTemplate<BillingData>, MonthlyBillingTemplate>();
builder.Services.AddScoped<IReportDataSource<BillingData, BillingParams>, BillingDataSource>();

Template Best Practices ​

DRY Templates

Extract common metadata logic into a base class:

csharp
public abstract class CompanyReportTemplate<TData> : IReportTemplate<TData>
{
    public abstract string TemplateId { get; }
    public abstract string DisplayName { get; }

    public ReportMetadata GetMetadata(TData data) => new()
    {
        Author = "Company Name",
        Keywords = "company, report",
        Title = GetTitle(data)
    };

    protected abstract string GetTitle(TData data);
}

Performance

The /generate path fetches a complete result through IReportDataSource before rendering. A per-item async iterator or implementation of IStreamingReportDataSource does not make /generate streaming; register the template with AddReportExport and call /export instead. Bound the query/result size of /generate to the host's available memory.

Released under the MIT License.