Elarion

Calendars

Read uploaded .ics files into events and to-dos with every problem located, keep what other programs wrote, expand recurrences within a window, resolve time zones, and publish calendars and feeds byte for byte the same, NativeAOT-safe.

Applications import calendars people upload (waste collection, school holidays, an export from Outlook or Google) and publish their own dates as files and feeds that calendar programs subscribe to. Elarion.Calendars reads and writes iCalendar (RFC 5545) without a third-party library and without reflection, so an application keeps publishing with NativeAOT.

PieceRole
CalendarReaderReads an .ics stream leniently into a CalendarReadResult: every event and to-do with its typed value, its component and its located errors.
CalendarEvent, CalendarTodo, CalendarAlarmThe typed model, a view over the component that keeps every property it does not model.
CalendarComponent, CalendarProperty, CalendarParameterThe lossless component tree: everything the file states, in order, with line numbers; built and changed in code too.
CalendarDateTimeA date, a floating time, a UTC time or a time in a zone, with the zone's TimeZoneInfo and the TZID as written.
CalendarRecurrenceExpands items into occurrences within a window: rules, extra and excluded dates, overrides, bounded by caps.
CalendarTimeZonesResolves TZIDs, converts VTIMEZONE to TimeZoneInfo and back.
CalendarWriterWrites calendars to a stream, an ElarionFile or an ElarionStreamedFile, deterministically.

Why it is shaped this way, and what was rejected, is in ADR-0109.

Getting started

dotnet add package Elarion.Calendars
builder.Services.AddElarionCalendars(builder.Configuration.GetSection(CalendarOptions.SectionName));

Importing an uploaded calendar

A handler reads the uploaded file's stream. Reading never throws because of what the file contains: it returns every item, so the handler can show a preview and commit what the person confirms.

[Handler]
public sealed class PreviewImport(CalendarReader reader) : IHandler<PreviewImport.Command, Result<ImportPreview>> {
    public sealed record Command([property: UploadLimits(FileExtensions = [".ics"])] UploadedFile File);

    public async ValueTask<Result<ImportPreview>> HandleAsync(Command command, CancellationToken ct) {
        await using var stream = command.File.OpenReadStream();
        var result = await reader.ReadAsync(stream, cancellationToken: ct);
        if (result.FileErrors.Count > 0) return result.ToAppError("file");

        foreach (var entry in result.Events.Where(e => e.HasValue && e.Value!.Start!.Value.Date < today))
            entry.AddError("import.date_in_past", "The event lies in the past.", "DTSTART");

        return new ImportPreview([.. result.Events.Select(e => new Row(e.Index, e.Value?.Summary, e.Value?.Start, e.Errors))]);
    }
}
  • HasValue says whether an entry has a typed item. Only a time that cannot be read (DTSTART, DTEND, DURATION, DUE, RRULE, RDATE, EXDATE, RECURRENCE-ID or its zone), a missing DTSTART on an event, or a per-item limit clears it. Any other unreadable property is reported as calendar.invalid_value, left out of the value and kept in the component.
  • AddError(code, message, property?, lineNumber?) adds the application's own errors, under its own prefix; they are located like the package's and appear in Errors and in ToAppError.
  • ToAppError(fieldPath, format?, maxMessages) converts to a validation AppError with at most 100 messages by default and one that counts the rest. Pass a formatter to word each error from its Code and data in the application's language; the package's messages are English, and it ships no translations, as the other file-format packages do not:
static string German(CalendarError e) => e.Code switch {
    CalendarErrorCodes.UnknownTimeZone => $"Zeile {e.LineNumber}: Zeitzone „{e.TimeZoneId}“ ist unbekannt.",
    CalendarErrorCodes.InvalidValue => $"Zeile {e.LineNumber}: {e.Property} ist kein gültiger Wert ({e.ExpectedKind}).",
    _ => e.ToString(),
};
return result.ToAppError("file", German);
  • Reading is lenient (see below). An application that refuses broken files instead refuses when CalendarErrorCodes.IsStructural(error.Code) holds for an error: the file is not a calendar or past a file limit, a line is malformed, too long or holds a control character, a component ends unexpectedly or exceeds a per-item limit. An application that imports leniently instead skips the entries that have errors and keeps the rest: where an error is reported says what it affects (FileErrors the file, an entry's Errors only that item, which has no value when a per-item limit stopped it). CalendarErrorCodes.IsLimit(error.Code) tells a configured limit (too_large, line_too_long, too_many_*, nesting_too_deep, recurrence_limit) apart from a broken file, to word it as "too large" rather than "broken". Strict = true in the read options also reports what the lenient reader accepts silently: a rule with both COUNT and UNTIL (calendar.invalid_value, the item has no value) and a value with a control character other than tab (calendar.control_character, the line is skipped).
  • Reading and expanding are CPU-bound and run synchronously on the calling thread once the stream is buffered. An application that imports uploads under load passes a token with a time budget to both, and may run them on a bounded number of worker threads rather than the request thread.

Files as producers write them

The reader accepts a byte-order mark, also at the start of a later line of files concatenated from several exports, UTF-16, lines that were never folded, LF and CR line ends, folds with a tab, quoted and vendor-prefixed TZIDs (/mozilla.org/…/Europe/Berlin, "W. Europe Standard Time"), dates where date-times belong, truncated or doubled time suffixes, and Exchange's all-day flag. A line that is not valid UTF-8 is decoded with the fallback encoding (Windows-1252 by default, FallbackEncoding to change it); UsedFallbackEncoding says when that happened. The code pages are held by the package, never registered process-wide.

Time zones

A TZID resolves through the system's zones first, as an IANA or a Windows id, and otherwise through the file's VTIMEZONE of that id. Legacy ids such as US/Eastern or Asia/Calcutta resolve to the zone they link to, also on hosts that ship them separately (Debian's and Ubuntu's tzdata-legacy). An id neither knows is calendar.unknown_time_zone on each item that uses it. A vendor prefix is removed by trying the id's last few segments, so resolution is linear in the id's length; an id longer than MaxTimeZoneIdLength (128 characters) is not resolved at all, and a VTIMEZONE or X-WR-TIMEZONE with such an id is not used. Only zones the system knows are cached process-wide; an id from a file that does not resolve leaves nothing behind. A floating time stays floating; it converts to UTC only in a zone the caller passes (CalendarExpandOptions.FloatingTimeZone). X-WR-TIMEZONE is reported as CalendarHeader.SuggestedTimeZone.

Resolution depends on the host's tzdata. Slim and NativeAOT container images often lack it: install tzdata.

A VTIMEZONE converts to a TimeZoneInfo with one adjustment rule per year. TimeZoneInfo evaluates rules per calendar year, so two historical shapes are approximate: the New Year hour of a zone's first year that ends in daylight time, and a year with three different offsets.

Recurrences

var week = result.Expand(monday, monday.AddDays(7), new CalendarExpandOptions { FloatingTimeZone = vienna });
foreach (var occurrence in week.Occurrences)
    Console.WriteLine($"{occurrence.StartUtc}–{occurrence.EndUtc}: {occurrence.Item.Summary}");

Expansion implements RFC 5545 recurrence for the Gregorian calendar: every FREQ and BY part, BYSETPOS, WKST, COUNT, UNTIL, RDATE, EXDATE and overrides matched by UID and RECURRENCE-ID. A local time in a daylight-saving gap moves forward by the gap, and the occurrence shows the wall-clock time it resolves to while its RecurrenceId keeps the time the rule named; an ambiguous one takes its first offset. COUNT counts the local times a rule names, before a gap moves them: on the spring day BYHOUR=2,3 names 02:00 and 03:00, which are one instant, so they use two of the count and give one occurrence, and the series has one occurrence fewer than COUNT. An item may have several rules (RecurrenceRules): its occurrences are the union of theirs, each rule counting its own COUNT, and an instance two rules share is one occurrence. Hourly and shorter rules step in elapsed time. A repeated value of a BY list counts once, as RFC 5545 allows repeats: BYMONTH=1,1,1 is January, however many items the list has. Parsing is linear in the rule's length, which the line limit bounds (calendar.line_too_long).

  • Overrides match their instance exactly, as RFC 5545 says: an override whose recurrence id is no instance (the right day at another time, say) is an extra occurrence, as the major clients treat it. A date RECURRENCE-ID against date-time instances matches the day's instance. RANGE=THISANDFUTURE is read as an override of its one instance.
  • Updates sent again: of several overrides of one instance, only the latest counts (the highest SEQUENCE, then the latest DTSTAMP, then the later one), as calendar clients do. ResolveOverrideVersions = false keeps them all. CalendarRecurrence.LatestVersions(result.Items) returns the items without the versions that lose, by the same rule, for an application that stores or shows items rather than occurrences.
  • Cancelled items: by default an item with STATUS:CANCELLED is an occurrence like any other, because the expansion reports what the file states. SkipCancelled = true leaves them out: a cancelled override removes its instance, a cancelled master its series. An application that shows a calendar turns it on.
  • EXRULE (RFC 2445, deprecated by RFC 5545 but still written by older producers) is read into ExceptionRules, written back, and applied: its instances are excluded, DTSTART never.
CapDefaultExceeded
MaxOccurrences10,000The expansion stops with calendar.too_many_occurrences and the occurrences found.
MaxIterations100,000A series whose rule finds no instance in that many periods stops with calendar.recurrence_limit.
MaxCandidates1,000,000A series whose rule builds that many candidates stops with calendar.recurrence_limit, counted as they are built within a period.

A rule without COUNT starts a few periods before the window, whatever its frequency, so a rule from a distant DTSTART costs only the periods near the window. A rule with COUNT must be counted from DTSTART; MaxCandidates bounds that. Expand takes a cancellation token, checked per series and per period of a rule. Each occurrence says where its end comes from (EndKind: stated, from a duration, a default day or no time).

Alarms resolve their trigger times per occurrence with CalendarAlarm.GetTriggerTimes(occurrence).

Publishing a calendar or a feed

// A small export to any transport:
return await CalendarWriter.ToFileAsync(events, "shifts.ics", new CalendarHeader { Name = "Shifts" }, cancellationToken: ct);

// A feed an HTTP endpoint streams:
return CalendarWriter.ToStreamedFile(db.Shifts.AsNoTracking().AsAsyncEnumerable().Select(ToEvent), "shifts.ics",
    new CalendarHeader { Name = "Shifts", RefreshInterval = TimeSpan.FromHours(6) });
  • Output is UTF-8 without a byte-order mark, CRLF, lines folded at 75 octets, served as text/calendar; charset=utf-8.
  • One VTIMEZONE per zone is written before the first item that uses it; IncludeTimeZones = false leaves out those of zones with an IANA id. A zone is written with its IANA id where the system can name one.
  • The writer never reads a clock: DTSTAMP comes from the item, else its LAST-MODIFIED, else CalendarWriteOptions.Timestamp. The same input writes the same bytes; a change in the written bytes between package versions is noted in the changelog.
  • An item without UID or timestamp, one that ends before it starts, or a zone without an id fails with a CalendarWriteException naming the item and the property.
  • Name and refresh interval are written as NAME and X-WR-CALNAME, REFRESH-INTERVAL and X-PUBLISHED-TTL.

Properties and components the model does not cover (X-APPLE-*, X-MICROSOFT-*, unknown components) are kept on the typed item and written back unchanged. The model is mutable: Clone() on an event, a to-do, an alarm or an attendee copies it deeply, where assigning another item's lists would share them. The component tree can be pruned or built in code and written with CalendarWriter.WriteAsync(stream, root).

Limits and options

OptionDefaultExceeded
MaxBytes16 MiBOne calendar.too_large error; nothing past the limit is read.
MaxComponents50,000Reading stops with calendar.too_many_components; the items before it are kept.
MaxLineBytes4 MiBThe line is dropped with calendar.line_too_long; the item keeps its value.
MaxPropertiesPerComponent1,000The item has no value (calendar.too_many_properties); reading continues.
MaxDepth8The item has no value (calendar.nesting_too_deep); reading continues.
MaxLines1,000,000Reading stops with calendar.too_many_lines; the items before it are kept.
MaxItems50,000Reading stops with calendar.too_many_items; the items before it are kept. Only events and to-dos count.
MaxTimeZoneIdLength128A longer TZID is calendar.unknown_time_zone without a lookup.
StrictfalseReports COUNT with UNTIL and control characters (see above).

The cancellation token of ReadAsync is checked every 1,024 lines while the file is parsed, and per item while items are mapped.

The keys are listed in the configuration reference.

Error codes

calendar.unreadable, calendar.too_large, calendar.line_too_long, calendar.too_many_components, calendar.too_many_properties, calendar.nesting_too_deep, calendar.malformed_line, calendar.unexpected_end, calendar.required, calendar.invalid_value, calendar.unknown_time_zone, calendar.duplicate_uid, calendar.too_many_occurrences, calendar.recurrence_limit, calendar.too_many_lines, calendar.too_many_items, calendar.control_character — constants of CalendarErrorCodes, whose IsStructural(code) says which are about the file's form and IsLimit(code) which report a configured limit. Each error carries the item's index and line, the component and UID, the property, its line and value, and the expected kind, the limit or the time-zone id where they apply.

On this page