Skip to content

Serenity 10.10.0 Release Notes (2026-11-29)

These release notes detail the changes made in Serenity and StartSharp from version 10.9.0 to 10.10.0. For a complete list of changes, please refer to the Serenity Change Log.

Much of the release is about what runs on its own, and what an administrator can change while it runs:

  • Jobs that show their work. Background jobs get a page of their own, schedules as one text, a stored history with the lines they logged, and a way to run, stop and reschedule them; scheduled reports and the emails about the exception log are built on it.
  • Settings without a deployment. An administrator changes a setting on a Settings page, and the application keeps it in the database.
  • Permissions that bring their own tier. A permission key declares who can grant it, and the settings lists can take a key out of a tier with a ! pattern.
  • An email queue that tracks each delivery. An email says what it is for, who it goes to and what it is about, can be personalized for each recipient, and reaches each recipient on its own.
  • Less for anonymous visitors to see. The work of 10.8.0 on that front continues, and closes the gaps a customer ran into: ES modules without a manifest, client addresses behind a CDN, and denied scripts that gave their existence away.

Hardening the Anonymous Surface, Part Two

10.8.0 let the form and columns scripts, the local texts and the ES modules of an application require a permission, so a visitor who has not logged in learns less about it. A StartSharp customer who replaced their own gate with these settings reported a few gaps while switching over, which this release closes.

ES Modules of a Folder Without a Manifest

The ESM access control decides who gets a file from the build.esm-manifest that tsbuild writes to an esm folder. A folder without one, e.g. of a package built with an older tsbuild, was served without access control, with only a warning in the log. MissingManifestPermission now sets the permission such a folder requires:

{
  "EsmAccessControl": {
    "MissingManifestPermission": "?",
    "MissingManifestAllowedPaths": "/lib/**"
  }
}

The default "*" serves them as before, "?" makes such a folder fail safe for anonymous visitors, and any other permission works too. As any folder named esm is treated as one, list the folders that tsbuild does not build, e.g. libraries copied under wwwroot/lib, in MissingManifestAllowedPaths. See Folders Without a Manifest.

Client Addresses Behind a CDN

The account rate limiter, the logs and the account events use the address of the connection, which is the address of the proxy behind a CDN, a load balancer or a reverse proxy, unless the forwarded headers middleware replaces it. That middleware accepts the headers only from the loopback addresses by default, so turning on UseForwardedHeaders was not enough for a CDN: every visitor shared the addresses of its edge servers, and so one rate limit.

The templates now configure the middleware from a ForwardedHeaders section with services.AddForwardedHeadersSettings() (the Serene template gets this in its next release):

{
  "UseForwardedHeaders": true,
  "ForwardedHeaders": {
    "KnownNetworks": [ "173.245.48.0/20", "2400:cb00::/32" ],
    "ForwardedForHeaderName": "CF-Connecting-IP"
  }
}

The headers are only accepted from the listed proxies, so a visitor can't choose the address the rate limiter sees; for the same reason, the rate limiter has no setting of its own for a client address header. See Forwarded Headers.

Denied Dynamic Scripts Look Missing

A dynamic script that the user may not access answered 403 Forbidden, and a missing one 404 Not Found, so an anonymous visitor could probe /DynJS.axd/Form.<Key>.js or Lookup.<Key>.js to learn which forms and lookups exist. An anonymous visitor now gets the same 404 response for both, like the ES modules. A logged-in user still gets 403, which the lookup error message relies on to point at a missing permission.

Leftover Texts

The Serene and StartSharp templates restrict the Columns., Db., Enums. and Forms. texts that no class claims to the logged-in users (the Serene template gets this in its next release):

{
  "LocalTextPermissions": {
    "Restrict": { "Columns.": "?", "Db.": "?", "Enums.": "?", "Forms.": "?" }
  }
}

The rows, forms and enums keep their own rules, as the longest prefix wins, and the texts used by the forms an anonymous visitor can open are still sent. What falls back to "?" are e.g. texts left over in a JSON file after a row was renamed, and the texts of the enums no form uses. In StartSharp, this takes 105 more keys out of the texts of an anonymous visitor. SiteFormTexts became public, as the login page shows Forms.SiteTitle.

Upgrading

  • Replace services.Configure<ForwardedHeadersOptions>(...) in Startup.cs with services.AddForwardedHeadersSettings();, and list your proxies in the ForwardedHeaders section if they are not on the same machine.
  • Add the Restrict entries above to the LocalTextPermissions section, and Permission = SpecialPermissionKeys.Public to the [NestedLocalTexts] attribute of SiteFormTexts. If an anonymous page of your own reads a Db., Enums. or Forms. text directly, give its texts class a public permission too.
  • If your own code relied on a 403 response from /DynJS.axd/ or /DynamicData/ for an anonymous visitor, check for 404 instead.
  • MissingManifestPermission needs no change, as its default serves the folders without a manifest as before.

Background Jobs Page (StartSharp)

The background jobs of an application, e.g. the one that sends the queued emails, ran on timers of their own: nothing showed whether a job ran, when it would run next, or why it failed, and a schedule could only be changed in the settings or the code. StartSharp now has a Background Jobs page in the Administration menu, and the background job manager of Pro.Extensions schedules the jobs itself, keeps the history of their runs and lets an administrator start, stop and reschedule them.

The page lists the jobs with their schedules, when each runs next, how its last run ended, and a switch that turns it off. Under them is the history of the runs, of all the jobs or of the one that is selected, with the status, the duration, what started the run and the result of each; a run opens with the lines that were logged during it. Run now starts a job whether it is due or turned off, and a job that can be cancelled has a Stop button while it runs. The page reads the list again every 10 seconds.

Schedules

A schedule is one text, in the settings, the database and the code alike:

  • @every 30s runs at an interval, counted from the start of the last run, with s, m, h or d for the unit, e.g. @every 1h30m;
  • a cron expression with the five standard fields (minute, hour, day of month, month, day of week), e.g. 30 2 * * 1-5 for 02:30 on weekdays. Lists, ranges and steps work (0 8-18/2 * * *), months and days can be names (JAN, MON), L is the last day of the month, and @hourly, @daily, @weekly, @monthly and @yearly are short forms. The parser is our own, so there is no new package reference;
  • @manual runs only when someone starts it.

The schedule dialog of the page writes them for you: an interval, daily or weekly at a time, a cron expression, only when started, or as the job says, which goes back to the schedule of the code. It shows the next runs of what you enter, and what is wrong with an expression that is not valid.

The schedule dialog with a weekly schedule and its next runs

The times of a cron expression are on the clock of the time zone of the schedule, which the dialog has a field for, e.g. Europe/Istanbul. A schedule without one is on the clock of the server, or of the time zone of the BackgroundJobs:TimeZone setting. A time that the clock skips when it goes forward runs as late as the clock went forward, and one that it repeats when it goes back runs once.

A schedule can also have an owner, the Runs as field of the dialog: the job then runs as that user, with the permissions of the user, which is what the scheduled reports below do. Without an owner, a job runs without a user, as before. A run whose owner is not found or is not active fails, instead of running without the user.

Writing a Job

A new job derives from BackgroundJob and is registered as a service:

public class NightlyImportJob(IOrderImporter importer) : BackgroundJob
{
    public override string Title => "Nightly import";
    public override JobSchedule DefaultSchedule => JobSchedule.DailyAt(2, 30);

    public override async Task ExecuteAsync(BackgroundJobContext context, CancellationToken cancellationToken)
    {
        var count = await importer.ImportAsync(cancellationToken);
        context.Log.LogInformation("Imported {count} orders", count);
        context.Message = $"{count} orders";
    }
}
services.AddBackgroundJob<NightlyImportJob>();
  • An exception fails the run, is logged as an error, so it reaches the exception log, and the run links to it there. MaxRetries and RetryDelay try a failed run again before the job waits for its next time.
  • What the job logs during the run, through context.Log or any other ILogger, is kept with the run, up to MaxRunLogLines (500) lines of RunLogLevel (Information) or above. The lines of a run that goes on are written every RunLogFlushSeconds (10), so they can be read before it ends.
  • context.Message is a short result for the history. Runs that succeed with no message and no log lines are counted on one entry ("42 runs") instead of filling the history, so a job that had nothing to do should leave it empty.
  • context.LastStart is when the run before this one started, e.g. to handle what happened since then, as the exception log notifications do; context.Skipped = true records a run that had nothing to do as Skipped instead of succeeded, with its Message saying why.
  • The Key of a job, the name of its type by default, is what its schedules and runs are stored by, so it has to stay the same. Title and Description can be the keys of local texts.
  • A job that sets AllowMultipleSchedules can have more schedules than its own one, each with a title and parameters as JSON, which it reads with context.GetParameters<T>().
  • context.Owner is the user a schedule with an owner runs as, e.g. for the email address of the user, and context.TimeZone the time zone of the schedule.

The jobs you already have keep working without a change: PeriodicBackgroundJob and DailyBackgroundJob are scheduled by the manager too, by their interval or their time of day, so they are on the page with their history. They can't be stopped while they run, as InternalRun gets no cancellation token. A job that only implements IBackgroundJob still schedules itself and is listed without the actions.

Stored in the Database

services.AddBackgroundJobs() alone keeps the schedules and the runs in memory, as before, so what is changed on the page is lost when the application restarts. With AddBackgroundJobStore() they are in the job_Schedules and job_Runs tables, which the migrations of Pro.Extensions create under the new ProBackgroundJobs connection key, which falls back to ProExtensions, ProFeatures and Default. Then:

  • a schedule that was due while the application was down runs once when it starts;
  • when several servers share the database, a schedule that is due runs on one of them, the one that takes it first. A server that stops in the middle of a run loses the schedule after LockSeconds (120), and that run is shown as abandoned, with the log lines it had written;
  • the runs older than RunRetentionDays (30), and more than the latest MaxRunsPerSchedule (200) of a schedule, are removed.

The schedules and the runs keep the ID of the user next to their username (InsertUserId, UpdateUserId, RunRequestedByUserId and TriggeredByUserId), in the type of the ID field of the application's user row, so a run records which user asked for it even after a username changes; BackgroundJobContext.TriggeredByUserId has it too.

Cleanup Jobs

The exception log, the account activity log and the sessions removed their old records while they wrote new ones. They now also have jobs for it, ExceptionLogPurgeJob (every 6 hours), AccountEventLogPurgeJob and AccountSessionPurgeJob (every hour), which are registered with their features and so appear on the page of an application that has background jobs. Once such a job has run, it does the cleanup alone; in an application without background jobs, or with BackgroundJobs:Enabled off, the records are removed while writing as before.

Upgrading

Nothing has to change: an application that keeps its Startup.cs runs its jobs as before, now through the manager. To get the page and the stored schedules:

  1. In Startup.cs, add the store:

    services.AddBackgroundJobs()
        .AddBackgroundJobStore();
    
  2. Add the page, its script and its endpoint under Modules/Administration/BackgroundJob, from the template: BackgroundJobPage.cs, BackgroundJobPage.ts and BackgroundJobEndpoint.cs.

  3. Add the permission key to AdministrationPermissionKeys.cs, and the link to AdministrationNavigation.cs:

    [DescriptionText("Background Jobs")]
    public const string BackgroundJobs = "Administration:BackgroundJobs";
    
    [assembly: NavigationLink(9050, "Administration/Background Jobs", typeof(Administration.BackgroundJobPage), icon: "fa-clock-o")]
    
  4. New jobs are simpler to register with services.AddBackgroundJob<TJob>(), which the manager takes when the application starts. Replace app.UseBackgroundJob<EmailQueueJob>() with services.AddEmailQueue(), see Email Queue below, as the email queue job can't be created without it anymore.

What behaves differently:

  • A PeriodicBackgroundJob that throws is logged as an error, not as information, so its failures reach the exception log. If a job of yours fails often by design, catch what it expects.
  • With the store, a periodic or daily job runs on one server at a time. A job that relied on running on every server, e.g. to clear a cache in memory, should implement IBackgroundJob itself, or the application can keep the store off.
  • A DailyBackgroundJob runs at the minute of GetRunAtTime(); its seconds are not used.

Scheduled Reports (Pro)

A report of the Reports page can now be sent by email on a schedule. The Schedule button of a report, next to the downloads, opens a dialog with the parameters the report was last run with, when to send it, in the time zone of the browser, the files to attach (PDF, Excel and CSV) and the subject. The report is run with the parameters it had in its form, so a date range like last month follows the date of each run. The email has the files, the key figures of the report, the number of its rows and a link that opens it on the page. The scheduled reports of the user are listed under My schedules on the page, with when each is sent next and how its last run ended, e.g. Last sent 2 days ago, or the error of a run that failed; there they can be changed, turned off, deleted or sent now. The dialog of a scheduled report lists its latest runs: when, Sent, Skipped (it had no rows) or Failed, whether it was on schedule or sent by hand, and the result, e.g. Sent to 2 recipients. The log lines of a run and the link to the exception log stay on the Background Jobs page, for the administrators, as they can show what a user should not see.

The schedule dialog of a report with its parameters, recipients and attachments

A scheduled report runs with the permissions of the user who scheduled it, so it can't send more than that user can see:

  • Scheduling needs the new Reports:Schedule permission. A user who loses it keeps seeing the own scheduled reports, and can delete them, but they are not sent anymore.

  • The report has to be one the user can run, when it is scheduled and at every run. A user who loses the permission of a report, or is deactivated, gets nothing more; the run fails, and shows why on the Background Jobs page.

  • A user sends a scheduled report only to the own email address. Other addresses need the new Reports:ScheduleForOthers permission, which is checked at every run too.

  • A report can be sent at most once every 60 minutes, and a user can have at most 10 scheduled reports, so a schedule can't send a report every minute. The new Reports:ScheduleUnlimited permission lifts both limits along with the cooldown of Send now, and only a super admin can grant it, as its key declares, see Permission Tiers in Code below. The cron expressions are checked by their shortest gap, so */10 8-17 * * 1-5 is too often, and 0 8-17 * * 1-5 is fine.

    The ReportSchedules settings are SchedulePermission, SendToOthersPermission, UnlimitedPermission, MinIntervalMinutes (60), MaxSchedulesPerUser (10), MaxRecipients (20) and SendNowCooldownSeconds (60).

  • Only the user sees and changes their scheduled reports on the Reports page. An administrator sees all of them on the Background Jobs page, as schedules of the Report schedules job, with their owner.

A scheduled report can have a message at the top of its email, e.g. for its recipients. To change the parameters of one, open the report from its dialog (Open the report), change them in the form, run it, and use Schedule: the dialog of the schedule opens with the parameters in the form. Send now can't be used again for a minute after a send (SendNowCooldownSeconds).

The PDF is made by the PDF renderer of the structured reports, as the user, without a browser session, with the in-process requests of Puppeteer, in the language of the user who scheduled it. That also fixes a PDF downloaded from the reports page, which was in the language of the browser that converts it rather than the one of the user. The link to the report needs the URL of the site, which a job without a request only knows from EnvironmentSettings:SiteExternalUrl; without it, the email has no link.

Upgrading

Reports can be scheduled in an application that calls AddStructuredReports() and keeps the schedules of the background jobs in the database, AddBackgroundJobs().AddBackgroundJobStore(), see above; the Reports page shows the Schedule button and My schedules only then. Grant Reports:Schedule to the roles that may schedule reports, and Reports:ScheduleForOthers to the ones that may send them to others, and set EnvironmentSettings:SiteExternalUrl for the link in the emails. The emails go through IEmailSender, so through the email queue when the application uses it.

Exception Log Notifications

The exception log can now send an email when an error happens for the first time, or comes back after it was marked as resolved. Turn it on in the Exception Log Notifications group of the Settings page, or in the DbSettings:ExceptionLogNotifications section of appsettings.json:

Setting Default
Enabled false Whether the emails are sent.
Recipients The email addresses, separated by commas or new lines.
MinLevel Error The lowest level of the issues that are told about.
NotifyNew true Whether new issues are told about.
NotifyRegressed true Whether issues that came back are told about.
MaxIssuesPerEmail 20 The most issues listed in one email; it tells how many more there are.

The Exception log notifications job checks every 5 minutes, and sends one email for all the issues since its last run, with their level, exception type, message and origin, and a link that opens each in the exception log. The links need EnvironmentSettings:SiteExternalUrl, as a job has no request to take the address of the site from, and point to ExceptionLogOptions.PagePath, Administration/ExceptionLog by default. Ignored issues are never told about, so the rules of the exception log also keep the noise out of the emails.

Permission Tiers in Code

The PermissionGrants:SuperAdminOnly list of appsettings.json grew with every feature that has a permission only a super admin should grant, and an application had to add each new one by hand. A permission key can now declare its tier next to its constant:

[DescriptionText("Settings of the Application")]
[PermissionGrantTier(PermissionGrantTier.SuperAdminOnly)]
public const string Settings = "Administration:Settings";

The lists of the settings add to the declared tiers, and a key gets the most restrictive of them, so the settings can still make a key stricter. To take one or two keys out of a tier, a pattern can now start with !, which excludes the keys it matches from the other patterns of its list and from the tier they declare:

"PermissionGrants": {
  "Grantable": "*",
  "HolderOnly": "Administration:*, !Administration:Translation",
  "SuperAdminOnly": "!Administration:Settings"
}

Here the translations are grantable by any administrator who manages permissions, and the settings permission by the ones who have it, while the other keys declared as super admin only keep that tier. "UseDefaultTiers": false turns all the declared tiers off, for an application that wants its lists to decide alone, like the UseDefault... options of the dashboards.

StartSharp declares Administration:Security, Administration:Credentials, Administration:Impersonate and Administration:Settings as super admin only in AdministrationPermissionKeys.cs, and Pro declares Reports:ScheduleUnlimited, so the SuperAdminOnly list is gone from the template's appsettings.json.

Upgrading

Nothing has to change: the keys you list keep their tiers. To follow the template, add the attribute to those keys in AdministrationPermissionKeys.cs and remove them from PermissionGrants:SuperAdminOnly.

Settings Page (StartSharp)

Some settings are better changed by an administrator in the application than by editing appsettings.json on the server. StartSharp has a Settings page for them under Administration, and Pro.Extensions a configuration provider that keeps the changed values in the database.

A setting is a property of an options class that opts in:

[DbSettings, DefaultSectionKey(SectionKey)]
[DisplayName("Site"), Description("General settings of the site.")]
public class SiteDbSettings
{
    public const string SectionKey = "DbSettings:Site";

    [DisplayName("Support Email"), EmailAddressEditor]
    public string SupportEmail { get; set; }

    [DisplayName("Page Size")]
    public int PageSize { get; set; } = 20;

    [DisplayName("Maintenance Message"), TextAreaEditor, ModifyPermission("Administration:Security")]
    public string MaintenanceMessage { get; set; }
}
  • [DbSettings] lists the class on the page. Its section key must start with DbSettings:, and the application does not start otherwise. Being under that section is not enough without the attribute.
  • The public read/write properties of simple types (texts, numbers, booleans, enumerations, dates, time spans, GUIDs) are the settings. Lists and nested objects are not supported yet. A property with [Ignore] is left out, and one with [ReadOnly(true)] is shown but can't be changed.
  • The page shows each class as a property grid, so [DisplayName], [Hint], [Category], the editor attributes and the validation attributes work as in a form.
  • The permission attributes work as on a row. [ReadPermission] and [ModifyPermission] on the class are needed to see and to change any of its settings. The same attributes on a property are needed besides the ones of the class, so they add up. [FieldReadPermission] and [FieldModifyPermission] on the class are the defaults of the properties that have none of their own. Without any of them, everyone who can open the page can see and change the settings. A user does not get the settings they may not see at all.
  • The texts are translated like the ones of a form whose key is the section key. For DbSettings:Site, the display name of PageSize has the key Forms.DbSettings.Site.PageSize, its hint Forms.DbSettings.Site.PageSize_Hint, and the display name and the description of the class Forms.DbSettings.Site.GroupTitle and Forms.DbSettings.Site.GroupDescription. The texts of the attributes are their defaults, so they appear on the Translations page and in the generated texts files.
  • [RequiresRestart] on the class or a property shows Applies after restart next to the setting. Use it when the value is read once, e.g. from IOptions<T> in a singleton. A value read through IOptionsMonitor<T> or IOptionsSnapshot<T> changes without one.

Code uses the class like any other options class, e.g. IOptionsMonitor<SiteDbSettings>. The value of a setting is the one from the database if it was set on the page, otherwise the one under DbSettings:Site in appsettings.json if there is one, otherwise the one the class sets.

On the page each setting has a check box. A ticked setting is set here: its value is kept in the database, also when it is the same as the default, so it stays when the default changes. An unticked setting has its default, which its editor shows, and can't be edited. Unticking a setting and saving puts it back to its default, and Back to defaults does that for all the settings of a class. A ticked setting that is saved empty also goes back to its default.

The Settings page with the settings of the site and their check boxes

Settings of Existing Options Classes

A value from the database is only ever provided under the DbSettings section. To let the page change a setting of another section, a property names the one key it overlays:

[DbSettings, DefaultSectionKey("DbSettings:Localization"), RequiresRestart]
public class LocalizationDbSettings
{
    [OverlayConfig(typeof(LocalizationSettings), nameof(LocalizationSettings.BaseLanguage))]
    public string BaseLanguage { get; set; }

    [OverlayConfig("Localization:DefaultLanguage")]
    public string DefaultLanguage { get; set; }
}

When such a setting has a value in the database, it is also the value of Localization:BaseLanguage, so the existing LocalizationSettings gets it, with no change to that class. Its default on the page is the value of the overlaid key. StartSharp has this class as its sample.

What a Row of the Table Can Do

The changed values are in the cfg_Settings table (SettingKey, e.g. Site:PageSize, and SettingValue), under the new ProDbSettings connection key, which falls back to ProExtensions, ProFeatures and Default. The database is part of what an attacker may reach, e.g. through a SQL injection elsewhere, so the provider does not trust the table:

  • it only reads the rows of the settings that the classes declare, and not the ones of read-only properties;
  • a value is provided under DbSettings: and, for a setting with [OverlayConfig], under that one key. No row can set a connection string, a secret or any other setting;
  • [OverlayConfig] can't name the ConnectionStrings, Data or DbSettings sections, and two settings can't overlay the same key. The application does not start otherwise.

The database settings come last in the configuration, so for their keys they win over the settings files and the environment variables. A change is logged as a warning with the old and the new value and the user, and the row keeps the ID and the username of the user who made it.

Several Servers, and a Missing Table

A change applies to the configuration of the server that saved it at once. The other servers of the application read the table every 30 seconds (ReloadSeconds), and tell the options monitors only when a value is different. When the table can't be read, e.g. before the migrations ran, the application starts with the defaults, the page says so, and the settings are read as soon as the table is there.

Adding It to an Application

  1. In Startup.cs, right after the type source is registered, as what follows may read the settings:

    services.AddApplicationPartsTypeSource();
    services.AddDbSettings(Configuration);
    

    Configuration must be the one of the WebApplicationBuilder, as in the template.

  2. Add the page, its script and its endpoint under Modules/Administration/DbSettings, from the template: DbSettingsPage.cs, DbSettingsPage.ts and DbSettingsEndpoint.cs, and LocalizationDbSettings.cs if you want the sample.

  3. Add the permission key to AdministrationPermissionKeys.cs, and the link to AdministrationNavigation.cs:

    [DescriptionText("Settings of the Application")]
    public const string Settings = "Administration:Settings";
    
    [assembly: NavigationLink(9750, "Administration/Settings", typeof(Administration.DbSettingsPage), icon: "fa-cog")]
    
  4. In appsettings.json, add Administration:Settings to PermissionGrants:SuperAdminOnly, so only a super admin can grant it.

Email Queue (StartSharp)

The email queue of Pro.Extensions kept each email as one row and sent it to all its recipients at once, so one bad address failed, and on a retry sent again, the email of everyone else. Its page was an entity grid and dialog that showed the raw columns, and the template didn't use the queue at all. This release rebuilds it around deliveries, gives it a page of its own, and lets an email say what it is for, who it goes to and what it is about.

The Page

The Email Queue page in the Administration menu starts with the health of the delivery: the SMTP server, when an email was last sent, the failure rate of the last 24 hours with a chart of the failed attempts in each hour, the emails sent in that time with the average time the server took to accept one, and what is waiting to be sent. It tells when the queue is paused, when the background jobs are off, and when the application sends its emails without the queue.

The email queue page with the delivery health and the list of the emails

The list has a tab for each state (queued, sending, sent, failed and cancelled), a search of the subject, the recipients, the records and the ID, and filters by purpose and time. The failed emails can be retried together, and the checked ones retried, cancelled or sent now. Live refreshes the list as emails are sent.

An email opens beside the list with its recipients, purpose, template, priority, attempts and size, and tabs for a preview at desktop or mobile width, the plain text, the headers, the deliveries to each recipient and the history of every attempt with the reply of the server. Its attachments can be downloaded. An email can be retried, cancelled, sent now, or duplicated, which queues it again for the same recipients.

An email sent to 14 recipients, personalized for each, with one failed delivery

The page also pauses and resumes the queue, tests the connection to the SMTP server, and removes the sent emails older than a number of days.

The queue has the emails of every user, including the password reset links that would let whoever reads them sign in as that user. So:

  • Administration:EmailQueue can only be granted by a super admin, as its key declares, see Permission Tiers in Code.
  • The links and the codes of an email sent as sensitive, e.g. a password reset, an activation or a two-factor code, are hidden on the page.
  • The preview is served by its own address with a strict content security policy, in a sandboxed frame, so the HTML of an email can't run scripts on the page.

Deliveries, Retries and History

An email is stored once, in mail_Messages, and sent through deliveries: one for an email to all its recipients together, as a mail client sends it, or one for each recipient of an email sent individually. Each delivery is tried on its own:

  • A failed attempt waits RetryDelay (60 seconds), and each next one twice as long, up to MaxRetryDelay (an hour), until RetryLimit (5) attempts. A permanent 5xx reply, e.g. an unknown mailbox, fails it at once.
  • A delivery is claimed by its row before it is sent, so when several servers share the database, each email is sent once.
  • MaxPerMinute keeps the queue under the limit of a mail provider, and BatchSize (50) is the most deliveries of one run.
  • An email that is sensitive or urgent is sent right after it is queued, instead of waiting up to 30 seconds for the next run of the job (SendUrgentImmediately), so a user who asked for a sign-in code doesn't wait for it.
  • EmailQueuePurgeJob removes the sent emails after SentRetentionDays (30), and the failed and cancelled ones after FailedRetentionDays (90).

mail_Recipients keeps the recipients with their users, mail_Associations the records an email is about, and mail_Events its history. An email to several recipients can end up partly sent.

The SMTP server accepting an email doesn't mean it reached the inbox. When the mail provider reports what happened later, e.g. through a webhook for bounces, the application can record it with EmailQueueProcessor.RecordDeliveryStatus(messageId, EmailDeliveryStatus.HardBounce, detail), and it is shown in the history of the email.

What an Email Is For, and Who It Goes To

IEmailSender and IEmailQueue take an EmailSendOptions with the message:

emailSender.Send(message, new EmailSendOptions
{
    Purpose = "Invoice",
    Template = "Northwind/Invoice",
    Recipients = [new EmailRecipient(customer.Email) { DisplayName = customer.ContactName }],
    Associations = [EmailAssociation.For<OrderRow>(order.OrderID)]
});
  • Purpose is what the email is for, which the page shows and filters by. Unlike the template, it stays the same when the template is renamed. EmailPurposes has the ones of the framework, e.g. PasswordReset and Invitation.
  • Recipients replace the addresses of the message, and can say which user each one is.
  • Associations are the records an email is about, by the row identifier of their row, e.g. Northwind.Order, so the emails of a record can be found.
  • Sensitive hides the links and the codes of the email on the page.
  • ScheduledDate has the queue send it later.

The emails of the framework (account changes, password reset, activation, invitation, two-factor code, scheduled reports and exception log notifications) give their purpose and recipients. An implementation of IEmailSender or IEmailQueue of your own keeps working, as the new methods have default implementations.

Personalized Emails

An email to many recipients, e.g. a bulletin, is sent with DeliveryMode = EmailDeliveryMode.Individually, so each recipient gets a copy of their own and doesn't see the others. Such an email can also be personalized:

emailSender.Send("Your {{ Branch }} order is ready", "<p>Dear {{ DisplayName }},</p>...", null, new EmailSendOptions
{
    DeliveryMode = EmailDeliveryMode.Individually,
    Personalize = true,
    Recipients = customers.Select(x => new EmailRecipient(x.Email)
    {
        DisplayName = x.ContactName,
        Values = new Dictionary<string, object?> { ["Branch"] = x.City }
    }).ToList()
});

The subject and the text parts are Scriban templates, filled for each recipient with Address, DisplayName, Username, UserId and the Values of the recipient, with numbers and dates in the culture of the recipient (EmailPersonalizer, which also expands a message to the messages of its recipients). A few rules keep it safe:

  • The values are HTML-encoded in an HTML part, so a display name can't add markup. | raw writes a value as it is, so use it only for values you trust.
  • A placeholder that a recipient has no value for fails when the email is sent or queued, rather than sending some recipients an email with a gap.
  • Templates can't include other files, and loops, recursion and the output have limits.
  • Text that is not part of the template, e.g. the name of a record that was rendered into the body, must not be read as template text. Wrap it in ScribanEmailTemplateRenderer.Escape(text).

The queue stores the template once and fills it when it sends each delivery. The same renderer, IEmailTemplateRenderer, is meant for the email templates of a later release.

Upgrading

  1. In Startup.cs, register the queue after the email sender, and remove the line that started its job:

    services.AddEmailSender();
    services.AddEmailQueue();
    
    app.UseBackgroundJob<Serenity.Pro.EmailQueue.EmailQueueJob>(); // remove
    
  2. Add the page, its script and its endpoint under Modules/Administration/EmailQueue, from the template: EmailQueuePage.cs, EmailQueuePage.ts and EmailQueueEndpoint.cs, and point the Email Queue link of AdministrationNavigation.cs to the new page:

    [assembly: NavigationLink(9300, "Administration/Email Queue", typeof(Administration.EmailQueuePage), icon: "fa-envelope-o premium-feature")]
    
  3. To send the emails through the queue, as the template now does, set SmtpSettings:AutoUseQueue to true. The emails are then sent by the background jobs, so keep it off in an application without them. Remove EmailQueueJob:AutoUse, which did nothing.

What behaves differently:

  • The migrations rename the Mail table to mail_Messages and add the new columns and tables. The emails that were waiting are sent by the new job. Code or reports of your own that read the Mail table need the new name.
  • The old grid, dialog, form, columns, endpoint and request handlers of the email queue are removed, and EmailQueue.SendById is obsolete. The new page has its own services under Services/Administration/EmailQueue.
  • Only a super admin can grant Administration:EmailQueue now. The roles that have it keep it.
  • The files that EmailSender writes to the pickup folder have a random suffix after the time, so the emails written in the same millisecond don't overwrite each other.

The Public Demo

The email queue was off in the public demo, as its visitors would have seen the emails of each other. The demo now keeps AutoUseQueue off, so no email of a visitor reaches the queue, and fills it with made-up Northwind emails instead: order confirmations, invoices, shipping notices, scheduled reports, a newsletter, and a few that fail or wait to be retried. They are "sent" by a sender that sends nothing, and a few new ones come in every few minutes, so the page has something to show. This is services.AddEmailQueueSampleData(), which only exists in the demo and Debug builds.

Smaller Changes

  • Text keys for the options of other things than forms. The texts of a form ([FormScript]) or of columns ([ColumnsScript]) have local text keys that their class implies, e.g. Forms.Northwind.Customer.CompanyName, with the texts of their attributes as the defaults. Any attribute of a class can now give such a prefix, by implementing IPropertyItemsTextPrefixProvider:

    public class MyOptionsAttribute : Attribute, IPropertyItemsTextPrefixProvider
    {
        public string GetPropertyItemsTextPrefix(Type type) => "Forms.MyOptions." + type.Name + ".";
    }
    

    The display names, hints, placeholders, categories and select items of the properties of a class with the attribute are then registered with those keys, its property items have the keys in place of the texts, and a property grid that gets the prefix as localTextPrefix looks them up. [FormScript], [ColumnsScript] and [DbSettings] implement the interface themselves, with the prefixes they had.

  • One rule for the module of a type. ModuleAttribute.AutoModuleFor(type) gives the module that the inferred keys of a type start with: the one of its [Module] attribute, or of the row it is based on, or else its namespace without its first part and without a last part that only says what kind of types the namespace has: .Columns, .Endpoints, .Entities, .Enums, .Forms, .Lookups, .Pages, .Repositories, .RequestHandlers or .Scripts. The inferred key of a form or of columns uses it, at runtime and in the generated ServerTypes. Only .Forms and .Columns were left out before, so a form or columns class with InferKey = true in a namespace that ends with one of the others, e.g. MyApp.Northwind.Endpoints.SaveRequest, changes its key from Northwind.Endpoints.Save to Northwind.Save, and the keys of its texts with it. Give such a class an explicit key if you have translations for the old one.

  • The options of the dashboard widgets can be translated (Enterprise). The options of a widget type, e.g. Chart Type or the hint of Aggregate, were English texts without keys, apart from the shared ones like Title and the click options. They now have the keys of a form of their options class, e.g. Forms.Pro.Dashboards.ChartWidgetOptions.ChartType, and the name of a widget type has a key with the module of its options class, like Controls.Pro.Dashboards.WidgetType.Chart, so they are on the Translations page. A widget type of your own gets them the same way, from its [DashboardWidgetType] attribute.

  • The generated texts declare their types in place. The files of the generated texts, e.g. SiteFormTexts.ts, declared the type of their export in a namespace texts of their own. When a package bundled its declarations, every file after the first had that namespace renamed in the index.d.ts of the package, so it was full of texts2, texts31 and so on. The type is an object literal on the constant now, export const SiteFormTexts: { ... } = proxyTexts(...), with the leaf texts as readonly properties, and asKey() / asTry() return the type of their branch of that constant. A text key that is a JavaScript keyword, which was left out before, is a member too. The exports, their members and their runtime behavior are the same, but code that used the texts namespace type of a generated file has to use the type of the constant. The generated typings of Serenity, business and enterprise features are regenerated this way.

  • Request handlers for the roles of users (StartSharp). UserRoleRepository, the last repository of the Administration module, is replaced by request handlers like the other services: UserRoleUpdateHandler, UserRoleListHandler, and RoleMemberListHandler, RoleMemberAddHandler and RoleMemberRemoveHandler for the members of a role, which UserRoleEndpoint takes through their interfaces. The request and response classes moved to UserRole/ServiceModels, and Update returns a UserRoleUpdateResponse instead of a SaveResponse. The service URLs and requests are the same. An application that did not change UserRoleRepository can take the UserRole folder of the template as it is.

  • The public demo protects the ADMIN user its visitors share (StartSharp). The sessions of ADMIN can't be signed out and invitations can't be sent, as a visitor would spoil them for the others (PublicDemoGuardFilter); the password grant of the token endpoint no longer asks ADMIN for a two-factor code, like the login page; and the scheduled reports of ADMIN are limited to 3 per user and to one an hour, as nobody has the permission that lifts the limits. The demo also shows a fixed demo host name instead of the real server names and the details of the server that holds a lock of a background job.

Smaller Fixes

  • The select-all checkbox of a grid was shown when there was nothing to select all of. GridRowSelectionMixin displayed its select-all button, unchecked, for a view without a row that can be checked, e.g. an empty list or one whose rows are all refused by its selectable option. The button is hidden in that case now, and it is refreshed when the number of rows changes, not only when the rows change, so a view that becomes empty hides it too.
  • A soft delete recorded the impersonated user as the one who did it. A delete that soft deletes a row (IIsDeletedRow, IIsActiveDeletedRow) or writes a delete log (IDeleteLogRow) put the identifier of the impersonated user in DeleteUserId or UpdateUserId, unlike the insert and update audit fields, the capture log and the data audit log, which use the impersonator (ClaimsPrincipal.GetAuditIdentifier()). The delete request handlers, synchronous and asynchronous, record the user who acted now, so a row deleted while impersonating is audited to the administrator who did it.