Onboarding guide
1. Result & Error Handling
What this group covers. This is the first capability chapter, and it is deliberately first because
the pattern it teaches underpins almost every other one in the guide. Before you read a command
handler, a domain factory, a controller action, or a gRPC call in any later chapter, you need the
Result pattern in your head: in this codebase an operation that can fail in an expected way does
not throw, it returns a value that is either a success or a structured failure. The eighteen types
here are that value (Result and its small combinator surface), the error it carries
(Error), the classification that drives HTTP and gRPC status codes
(ErrorType plus the ErrorTypeSeverity ranking that picks
which error speaks for a multi-error failure), the JSON machinery that lets a result survive a Redis
round trip (ResultJsonConverterFactory,
ResultConverter, PropertyReader), and the collection
envelopes that successful reads come back in, offset
(CollectionResult<T>, PagedCollectionResult<T>,
PaginationMetadata) and keyset
(KeysetPageRequest, KeysetCollectionResult<T>,
KeysetCursor), plus the change-feed entry a delta read pages through
(EntityChange<TEntityDTO, TIdentifierType>) and a small
RFC 4180 reader that turns a malformed upload into a validation failure rather than an exception
(CsvReader, its CsvTable and CsvRow results, and its
private Parser). The primer introduces the idea in
§2; this chapter is where it becomes
concrete. The governing decision is
ADR-013: expected failures are
transport-agnostic values, only the edge maps them to HTTP or gRPC, and exceptions stay for the
genuinely exceptional.
Every type in this chapter lives in MMCA.Common.Shared, the innermost layer, which is why the Blazor
WebAssembly client can reference the exact same Result, Error and PagedCollectionResult<T> the
SQL Server repository produced, with no EF Core or ASP.NET dragged along. That placement is
[Rubric §3, Clean Architecture] in miniature: an HTTP-shaped concept (ErrorType) is modelled as a
pure enum in the core, and the translation to a status code is deferred to the presentation layer.
Why a return value instead of an exception
Exceptions are expensive (stack capture and unwinding), they are invisible in a method's signature,
and they conflate programmer errors with business outcomes. "This order ID does not exist" and
"this email is already taken" are not exceptional, they are routine, expected branches of normal
control flow. Modelling them as data lets the compiler see them (a method that returns Result<T>
advertises that it can fail), lets them be collected into a list, passed through a pipeline,
inspected, and mapped to a response without any try/catch. That decision is the single most
pervasive idiom in the two repos: practically every entity factory method, every CQRS command and
query handler, every controller action, and every client service method returns Result or
Result<T>. This touches [Rubric §2, Design Patterns] (which assesses whether patterns are idiomatic
and solve real problems rather than being "pattern theater", and here Result is the genuine,
codebase-wide error-flow mechanism) and [Rubric §9, API & Contract Design] (which assesses consistent,
standardized error responses, because every failure flows through the same envelope, so every endpoint
produces the same error shape).
Three pieces: classification, carrier, envelope
ErrorType
(MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ErrorType.cs:24) is the classification
axis, a ten-member enum whose per-member doc comments name the HTTP status each maps to:
Validation and Invariant to 400, NotFound to 404, Conflict to 409, Unauthorized to 401,
Forbidden to 403, UnprocessableEntity to 422 (ErrorType.cs:26-45), Unexpected to 500
(ErrorType.cs:47-53), TooManyRequests to 429 (ErrorType.cs:55-59), a temporary refusal such as
a sign-in lockout, and Unavailable to 503 (ErrorType.cs:61-67), a dependency that failed or did
not answer in time. There is deliberately no "unclassified" member: every error names a meaning, and
the remarks give the rule for choosing one, Validation, Invariant or UnprocessableEntity when
the caller can fix the request, Unavailable when retrying later can succeed, and Unexpected when
neither holds (ErrorType.cs:13-16). The numeric values are pinned explicitly so an in-process or
persisted value never moves, and 7 is retired (it was the removed Failure member) and must not be
reused (ErrorType.cs:16-18), which is also why the enum carries a CA1027 suppression
(ErrorType.cs:20-23). Unexpected is the one to internalize: it is reserved for a genuine
server-side fault that the caller cannot fix by changing the request and that retrying will not cure,
and its doc comment is explicit that it must never be used for a business-rule violation
(ErrorType.cs:48-51).
Error (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:15) is the
carrier, an immutable positional record (Error.cs:15-20) with a machine-readable Code (for
example "Order.NotFound", used for programmatic branching and, per
ADR-027, as the localization key), a
human-readable Message, an ErrorType, and optional Source / Target context. Ten factory
methods, one per ErrorType (Error.cs:46-141), each hard-code the correct classification, so a
caller can never accidentally pair Error.NotFoundError(...) with the wrong type. Three pre-built
static singletons (Error.NotFound, Error.AlreadyDeleted, Error.InvalidEntityField,
Error.cs:23-29) cover the ubiquitous cases without re-allocating, and WithSource / WithTarget
(Error.cs:146, Error.cs:152) enrich an error through with-expression copies, with
For<TTarget>(source) (Error.cs:163-164) setting both at once, the target being the simple type
name. One property sits outside the positional record: an optional RetryAfter (Error.cs:38), set
with with { RetryAfter = ... } on a TooManyRequests or Unavailable error so the HTTP edge can
tell the caller how long to wait, as the Retry-After header of a 429 or a 503 (Error.cs:31-37).
The Unexpected factory's doc comment draws the line between the two server-side categories: a
dependency that failed or timed out belongs on Unavailable, not Unexpected (Error.cs:128-141).
Result (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Result.cs:21) is the
outcome envelope, either a success (no errors) or a failure carrying one or more Errors. The
sealed generic Result<T> (same file, Result.cs:192) adds a Value on the success path
(Result.cs:195) and the functional combinators that make the pattern ergonomic.
The railway, in one picture
"Railway-oriented programming" is the mental model: imagine two parallel tracks, a success track and a
failure track. An operation that takes the current result as input is skipped if the result is already
a failure (the train stays on the failure track), and runs only if it is a success, where it may stay
on the success track or switch to failure. Control flows forward without nested
if (result.IsFailure) checks.
The surface is deliberately small. On Result<T> there are four combinators.
Match(onSuccess, onFailure) (Result.cs:269) terminates the railway by collapsing both tracks to a
single value, guaranteeing that exactly one branch runs. Map(mapper) (Result.cs:285) transforms the
success value while propagating errors untouched. Bind(binder) (Result.cs:311) and
BindAsync(binder) (Result.cs:298) are the monadic bind, synchronous and asynchronous: they
short-circuit on failure, returning the original errors without invoking binder, and otherwise hand
the success value to the next result-returning operation. For a sequence of steps, though, the type's
own doc comment names the house idiom as an early return through TryGetValue(out value)
(Result.cs:187-188, Result.cs:206) rather than a long chain: the method carries
[MaybeNullWhen(false)], so the compiler tracks the check, the value needs no ! in the success
branch, and deleting or reordering the check breaks the build instead of letting a null escape
(Result.cs:197-202). Reading Value (Result.cs:195) directly yields the default of T on a
failure, which is exactly the slip TryGetValue exists to prevent.
The non-generic base carries the valueless equivalents, Match (Result.cs:162) and Bind
(Result.cs:176). It also owns Combine(params ReadOnlySpan<Result> results)
(Result.cs:131), the aggregate-all-failures combinator that runs several invariant checks and
returns all their errors at once rather than failing on the first. That is the workhorse of domain
factory methods (Result.Combine(CheckName(name), CheckDate(date), ...)), its ReadOnlySpan
parameter avoids a heap allocation in the common case, it allocates the aggregated error list only
when something actually failed (Result.cs:138-147), and it rejects an empty call outright
(Result.cs:133-136) because combining nothing has no defensible answer.
Three implicit conversions remove the remaining ceremony: an Error lifts into a failed Result
(Result.cs:50, with the named alternate FromError at Result.cs:56 for callers that prefer it) or
into a failed Result<T> (Result.cs:242), and a bare value lifts into a successful Result<T>
(Result.cs:258), so a guard clause writes return someError; and a happy path writes
return theValue;. Keeping the surface to these few members, with no task-lifting extension layer
over Task<Result<T>>, is a [Rubric §15, Best Practices & Code Quality] choice: an await, a
TryGetValue guard and an early return read the same in every handler, so there is one way to
compose a sequence rather than several.
Construction discipline, and the invariant it buys
You cannot new a Result<T> directly: its constructors are internal (Result.cs:220,
Result.cs:226), and the non-generic base's own constructor is private protected
(Result.cs:31), so no subclass outside the assembly can bypass the failure guards
(Result.cs:17-18). The only way to produce a result is through the static factory methods on the
base Result class (Success / Failure, Result.cs:69-109). That is what guarantees the
invariant the rest of the codebase relies on: a result is always either a clean success or a
non-empty failure, never a half-built object. Two details make it airtight. First, the success path is
served by a single cached immutable instance (Result.cs:23, Result.cs:69) and the error list is
allocated lazily (Result.cs:28, Result.cs:36), so the overwhelmingly common success case allocates
nothing. Second, ThrowIfNoErrors (Result.cs:114-122) throws ArgumentException when a failure
factory is handed an empty collection, because IsSuccess is derived from the error count
(Result.cs:39) and an accidentally-empty collection would otherwise turn an explicit Failure(...)
call into a success. Both the non-generic Failure (Result.cs:90-96) and the generic failure
constructor (Result.cs:226-230) route through that guard. Likewise, Error's factory
methods are the canonical construction path because they fix the code-to-classification pairing at the
call site. This is quiet [Rubric §15, Best Practices & Code Quality] work: the type system and the
factories, not documentation, keep the envelope well-formed.
Severity, not position, classifies a failure
Result.Combine aggregates errors in evaluation order, so if a transport picked the first error to
classify the whole failure, an incidental validation failure evaluated early could downgrade a real
403 or 500 into a 400. ErrorTypeSeverity
(MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ErrorTypeSeverity.cs:32) is the answer: one
ranking over ErrorType, held in a FrozenDictionary because the table is fixed at startup and read
on every failure path (ErrorTypeSeverity.cs:39-51). The ranks are Unexpected 70, Unavailable
65, Unauthorized 60, Forbidden 50, TooManyRequests 45, Conflict 40, NotFound 30,
UnprocessableEntity 20, and Invariant and Validation both 10 (ErrorTypeSeverity.cs:41-50), so
a broken server outranks a down dependency, which outranks anything the caller did
(ErrorTypeSeverity.cs:16-27). Rank returns zero for an unmapped
type (ErrorTypeSeverity.cs:60), so a category added to ErrorType without a rank here can never
silently outrank a real 403 or 500. MostSevere(errors) (ErrorTypeSeverity.cs:72) then picks the
representative error with a deliberately index-based loop that keeps the earliest error on a tie
(ErrorTypeSeverity.cs:83-98), the comment at ErrorTypeSeverity.cs:86-87 explaining that a LINQ
MaxBy would allocate an enumerator and a comparer closure on a path that runs for every failure
response.
The point of hoisting this into MMCA.Common.Shared rather than into one presentation package is that
both edges classify the same aggregate identically: the HTTP side calls it from
ErrorHttpMapping.GetStatusCode(IReadOnlyList<Error>)
(MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:54-55) and the gRPC
side from ToRpcException
(MMCA.Common/Source/Presentation/MMCA.Common.Grpc/ResultGrpcExtensions.cs:110). Every error still
travels in the payload; ranking selects the status only. This is the 2026-08-26 and 2026-08-27
revision of ADR-013, and it is
[Rubric §9, API & Contract Design] in the small: the meaning of a failure must not depend on the order
in which its causes happened to be evaluated.
Making a result survive a round trip
The construction discipline above creates a problem the moment a result must be serialized: because
Result<T>'s constructors are internal and its properties are get-only, System.Text.Json's default
reflection-based deserializer cannot rehydrate one. That matters because the CQRS query-caching
decorator
CachingQueryDecorator<TQuery, TResult>
writes whole handler results through ICacheService, skipping only failures
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:118,122),
and those results are Result<...> values (see Chapter 5 and
Chapter 9).
ResultJsonConverterFactory
(MMCA.Common/Source/Core/MMCA.Common.Shared/Serialization/ResultJsonConverterFactory.cs:15) is the
fix: a JsonConverterFactory attached to both Result and Result<T> via [JsonConverter(...)]
(Result.cs:20, Result.cs:191) whose CanConvert matches the non-generic Result and any closed
Result<T> (ResultJsonConverterFactory.cs:21-23) and whose CreateConverter hands back the right
per-type converter (ResultJsonConverterFactory.cs:26-33). It writes a compact
{"value": ..., "errors": [...]} shape and, crucially, rebuilds the object through the public
factory methods (ResultJsonConverterFactory.cs:52, ResultJsonConverterFactory.cs:100), so a
round-tripped result obeys exactly the same success-or-non-empty-failure invariant a freshly built one
does.
ResultConverter (ResultJsonConverterFactory.cs:35) is the concrete
JsonConverter<Result> for the non-generic case, and a private generic ResultConverter<T> sibling
(ResultJsonConverterFactory.cs:63) handles the typed case. Both lean on one small helper, the
PropertyReader delegate (ResultJsonConverterFactory.cs:118), a
ref Utf8JsonReader callback that the shared ReadObject walker
(ResultJsonConverterFactory.cs:121-144) invokes once per JSON property, so the value- and
error-reading logic is written once and reused by both converters, and both emit their errors through
one WriteErrors (ResultJsonConverterFactory.cs:146-153). The typed converter is stricter than the
untyped one on purpose: an object carrying neither value nor errors is a corrupt or truncated
cache entry, so it throws rather than fabricate a success wrapping null
(ResultJsonConverterFactory.cs:95-98), while the same empty object is the legitimate success form
for the non-generic Result (ResultJsonConverterFactory.cs:37-39,52). Without this converter the
distributed result cache could not exist, which makes it quiet
[Rubric §12, Performance & Scalability] plumbing.
How a failure becomes an HTTP response
Follow a typical write through the layers. A domain factory or aggregate method validates its inputs
and returns Result.Combine(...); a command handler in the application layer chains follow-on work
with Bind / BindAsync / Map, so any failure short-circuits the rest of the slice; the controller
receives the Result<T> and, on failure, hands the errors to
ApiControllerBase.HandleFailure
(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:50). That method
resolves the status from the most severe error present, never from position
(ApiControllerBase.cs:62-63), through
ErrorHttpMapping's FrozenDictionary of all ten
categories (ErrorHttpMapping.cs:23-35, TooManyRequests to 429 at ErrorHttpMapping.cs:33 and
Unavailable to 503 at ErrorHttpMapping.cs:34), then renders an RFC 9457 Problem Details body
carrying all the errors in an errors extension, optionally localized through
ErrorLocalizer resolved per request
(ApiControllerBase.cs:65-73). A 429 whose TooManyRequests errors, or a 503 whose Unavailable
errors, carry a RetryAfter also gets a Retry-After header, the longest hint winning
(ApiControllerBase.cs:75, ApiControllerBase.cs:89-112).
An empty error list is defended against too: it becomes a 500 rather
than a silent 200 (ApiControllerBase.cs:54-60). The mapping table is shared rather than duplicated so
that the controller base and
UnhandledResultFailureFilter cannot
drift (ErrorHttpMapping.cs:10-12).
And how the same failure crosses a service boundary, or reaches the browser
On the gRPC side, ResultGrpcExtensions carries a
mirror of that table, ErrorType to Grpc.Core.StatusCode, in its own FrozenDictionary
(MMCA.Common/Source/Presentation/MMCA.Common.Grpc/ResultGrpcExtensions.cs:41-54, with Unexpected
mapping to StatusCode.Internal at ResultGrpcExtensions.cs:51, TooManyRequests to
StatusCode.ResourceExhausted at ResultGrpcExtensions.cs:52 and Unavailable to
StatusCode.Unavailable at ResultGrpcExtensions.cs:53), reachable as an extension member
ToGrpcStatusCode() (ResultGrpcExtensions.cs:63). A service implementation guards with a single
result.ThrowIfFailure() (ResultGrpcExtensions.cs:76), raising a
ResultFailureException that the server
interceptor GrpcResultExceptionInterceptor
(MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/GrpcResultExceptionInterceptor.cs:19)
translates through ToRpcException (ResultGrpcExtensions.cs:105): the status comes from
ErrorTypeSeverity.MostSevere (ResultGrpcExtensions.cs:109-110) and every error is still written
into the trailers as error-{i}-code, error-{i}-message and error-{i}-type entries, plus
-source / -target when present, so the far side can rebuild the list
(ResultGrpcExtensions.cs:117-133). See
ADR-007 and
Chapter 13.
The browser gets the same treatment from the other direction. Every HTTP-typed client service in
MMCA.Common.UI returns Result end to end:
ProblemDetailsResultReader
(MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ProblemDetailsResultReader.cs:59) parses an
RFC 9457 body back into typed errors, and
HttpResultExecutor converts the absence of a
body (connection, DNS, socket, client timeout) into transport errors, so pages branch through
ResultUiExtensions rather than catch. One
fidelity limit is worth carrying in your head and is stated in source: the reverse mapping is lossy on
400 alone, because the forward map collapses Validation and Invariant onto it and the reader can
only pick Validation back (ProblemDetailsResultReader.cs:50-57), so a client that needs
the distinction must consume an endpoint that emits the MMCA error array. Because all three edges are
driven by the same ten-member enum and the same severity ranking, there is one source of truth for
"what does a not-found look like", which is the [Rubric §9, API & Contract Design] payoff of putting
the classification in the core rather than at each edge.
Offset paging: the read-side envelopes
The read side needs shapes of its own. A query that returns a list wraps it in
CollectionResult<T>, a thin [DataContract] record
(MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/PaginationMetadata.cs:92) whose single
required Items property (PaginationMetadata.cs:110) is normalized by the constructor from any
IReadOnlyCollection<T> into a list, reusing the caller's List<T> when it already is one
(PaginationMetadata.cs:102-106). When the read is paged,
PagedCollectionResult<T> (PaginationMetadata.cs:119) extends that base
with one extra required property, PaginationMetadata
(PaginationMetadata.cs:12), the server-side paging state (TotalItemCount, PageSize,
CurrentPage) plus computed derivations (TotalPageCount, FirstRowOnPage, LastRowOnPage,
PaginationMetadata.cs:75-83) that are excluded from the wire with [IgnoreDataMember].
Two details are worth internalizing. The three core values are validated twice, in the constructor
(PaginationMetadata.cs:22-31) and again in each init accessor (PaginationMetadata.cs:38-71),
precisely because object initializers, record with expressions, and System.Text.Json all bypass the
constructor (the comment at PaginationMetadata.cs:33-35 says so). And [DataMember(Order = ...)]
fixes a deterministic wire order so PaginationMetadata always follows Items
(PaginationMetadata.cs:109, PaginationMetadata.cs:138). These envelopes are not part of the
success/failure machinery themselves, a paged query handler returns Result<PagedCollectionResult<T>>,
composing the two ideas, but they belong in this chapter because they are the canonical shapes that
successful reads return. They are also genuinely shared contracts: the controller surface declares
ActionResult<PagedCollectionResult<TEntityDTO>>
(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/IEntityControllerBase.cs:43) and the
Blazor client deserializes the very same type in
EntityServiceBase<TEntityDTO, TIdentifierType>
(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:102,145), so there is no
hand-written mirror DTO to drift
(ADR-034,
ADR-094).
Keyset paging: the same envelope family, a different cost model
Offset paging answers "give me page 37" and costs the database a scan of the 36 pages before it.
KeysetPageRequest
(MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/KeysetPagination.cs:20) asks the other
question, "give me what comes after this row", which costs one index seek regardless of depth, at the
price of losing random page access and a total count (the type's own doc comment lays this out at
KeysetPagination.cs:11-17). The request carries a page size clamped into [1, MaxPageSize] in both
the constructor and the init accessor (KeysetPagination.cs:52, KeysetPagination.cs:63) so a
caller who asks for zero or a million gets a sane page instead of an error. MaxPageSize, fixed at
1000, is the one framework page cap: the query pipeline's unbounded-result ceiling and the list page
URL ceiling are both defined as this value, so no entry point can be talked into an unbounded read
(KeysetPagination.cs:22-27). The request also carries
SortColumn, Descending, and the opaque Cursor (KeysetPagination.cs:68,72,76). Its answer is
KeysetCollectionResult<T> (KeysetPagination.cs:86), a sibling of
PagedCollectionResult<T> over the same CollectionResult<T> base that adds a
single NextCursor (KeysetPagination.cs:108) and deliberately no total and no page number.
KeysetCursor (KeysetPagination.cs:126) is the static codec for that token.
Encode (KeysetPagination.cs:140) builds v1|{hasSortValue}|{sortValue}|{id} with both value
segments themselves base64url encoded so a value containing the separator cannot forge one
(KeysetPagination.cs:144-151), then base64url encodes the whole payload (KeysetPagination.cs:153).
TryDecode (KeysetPagination.cs:170) rejects anything it does not understand, wrong version, wrong
segment count, bad flag, invalid base64 (KeysetPagination.cs:175-186), rather than silently
mis-seeking, and its private base64url helper checks validity before decoding because the BCL's
Base64Url.TryDecodeFromChars throws on an invalid character rather than returning false, which is
exactly the input a client-supplied cursor will contain (KeysetPagination.cs:203-207). The cursor is
opaque but neither signed nor encrypted, so it must never carry anything the caller may not already
see, and by construction it carries only a sort key and an id from a row the caller just received
(KeysetPagination.cs:121-124): that is the [Rubric §11, Security] boundary of this design, stated in
source.
The consumer is the repository layer:
EFReadRepository<TEntity, TIdentifierType>.GetPageByCursorAsync
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:644)
returns a Result<KeysetCollectionResult<TEntity>>, turning an unknown sort column
(EFReadRepository.cs:651-660) or a malformed cursor (EFReadRepository.cs:668-676) into a Result
failure rather than an exception, fetching PageSize + 1 rows so the extra row acts as a next-page
probe instead of paying for a COUNT (EFReadRepository.cs:683-689), and encoding the last kept row
into the next cursor via KeysetQueryBuilder
(EFReadRepository.cs:694-697). The default list contract of
ADR-034 stays offset
paging; keyset reaches HTTP only on a controller that opts in
(ADR-145,
ADR-055). Both
shapes together are the [Rubric §12, Performance & Scalability] story on the read side: no query ever
returns an unbounded list, and deep scrolling has a mode that does not degrade with depth.
The same keyset envelope carries the change feed of
ADR-144. Each entry is an
EntityChange<TEntityDTO, TIdentifierType>
(MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/EntityChange.cs:18), a sealed
[DataContract] record with a required Id, IsDeleted and ChangedOn and an optional Item DTO
that is null for a tombstone (EntityChange.cs:21-35).
EntityQueryService<TEntity, TEntityDTO, TIdentifierType>.GetChangesSinceAsync
(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:630) builds the
entries and returns a Result<KeysetCollectionResult<EntityChange<...>>> (EntityQueryService.cs:663),
and the opt-in GET changes action on
EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>
serves it only on a controller carrying
SupportsChangeFeedAttribute
(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:469-474). The
type's remarks state the client contract: page with the same since until the next cursor is null,
keep the largest ChangedOn as the next since, and apply entries idempotently by Id, because the
inclusive bound sends boundary rows again (EntityChange.cs:12-16).
Reading a CSV upload on the railway
CsvReader
(MMCA.Common/Source/Core/MMCA.Common.Shared/Serialization/CsvReader.cs:23) applies the same rule to
file input: a malformed file is a validation failure naming the line, never an exception, so an upload
endpoint can answer 400 with it (CsvReader.cs:20-21). ReadRecords (CsvReader.cs:77) runs the
private single-pass Parser (CsvReader.cs:96) and, on a quote left open or text straight
after a closing quote, returns Error.Validation with the code Csv.Malformed (CsvReader.cs:29) and
the line number as the error's Target, so the edge localizer can name it in the translated message
(CsvReader.cs:84-92). ReadTable (CsvReader.cs:40) treats the first record as the header row and
fails with Csv.Empty (CsvReader.cs:32, CsvReader.cs:48-51) when there is none, and
ReadTableAsync (CsvReader.cs:65-72) reads a stream honoring a byte-order mark, leaving the size
bound to the caller. The success value is a CsvTable (CsvReader.cs:239), whose
FindColumn matches a header by any of several accepted names ignoring case (CsvReader.cs:247-253)
and FindColumnStartingWith by prefix (CsvReader.cs:277), over CsvRows
(CsvReader.cs:296) that answer an empty string for a short record or an unknown column
(CsvReader.cs:304-316), so a missing optional column reads as blank instead of throwing. The two
callers are the API's
FormFileUploadExtensions
(MMCA.Common/Source/Presentation/MMCA.Common.API/Uploads/FormFileUploadExtensions.cs:124) and ADC's
TicketLeapRosterParser
(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Infrastructure/Tickets/TicketLeap/TicketLeapRosterParser.cs:66).
Where this leads
With these eighteen types you have the full error-and-result vocabulary the rest of the guide assumes.
You will see Result returned by the domain building blocks of
Chapter 2 (factory methods that refuse to construct an invalid
entity), threaded through the CQRS decorator pipeline of Chapter 5 and
cached across a Redis round trip by that same pipeline (Chapter 9), produced by
the querying and persistence layers of Chapter 3 and
Chapter 7, and unwrapped at the edges by the API, gRPC and UI layers
(Chapter 12, Chapter 13,
Chapter 15). Read this chapter's type sections next; everything
after them takes the railway for granted.
CollectionResult<T>
MMCA.Common.Shared ·
MMCA.Common.Shared.Abstractions·MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/PaginationMetadata.cs:92· Level 0 · record
- What it is: a thin envelope wrapping a collection of items for API responses; the base type both paged variants (
PagedCollectionResult<T>andKeysetCollectionResult<T>) extend. - Depends on: nothing first-party. It shares a file with
PaginationMetadataandPagedCollectionResult<T>, and it is inherited from another file byKeysetCollectionResult<T>. - Concept introduced, the collection envelope. Returning a named wrapper (
{ "items": [...] }) instead of a bare JSON array is a small but deliberate[Rubric §9, API & Contract Design]choice (§9 assesses consistent, evolvable response contracts): a wrapper leaves room to add metadata later, pagination state or a cursor, without a breaking change to the response shape that a top-level array would force. That headroom is not hypothetical here, it is exactly what the two subtypes below spend. - Walkthrough
- One property:
required ICollection<T> Items { get; init; }(PaginationMetadata.cs:110).requiredforces every caller to set it, soItemsis never null;initmakes it write-once. - Two constructors, both marked
[SetsRequiredMembers](PaginationMetadata.cs:95,101) so direct construction satisfies therequiredcontract without an object initializer: a parameterless one delegating to the data constructor with an empty collection (PaginationMetadata.cs:96-97), and the data constructor (PaginationMetadata.cs:102-106). - The data constructor null-checks its input with
ArgumentNullException.ThrowIfNulland then normalizes to a list, reusing the instance when the caller already passed aList<T>and copying with a collection expression otherwise (PaginationMetadata.cs:105). That is a real allocation saving on the hot read path, where the repository has already materialized aList<T>. [DataContract]on the type and[DataMember(Order = 1)]onItems(PaginationMetadata.cs:91,109) pin the wire order, matching the serialization disciplinePaginationMetadatauses.
- One property:
- Why it's built this way:
required+initgives "set once, never null" semantics with no hand-written guard on the common path, while the explicit[DataContract]/[DataMember(Order = ...)]pair keeps the serialized shape deterministic instead of leaving it to member-declaration order. - Where it's used: base of
PagedCollectionResult<T>andKeysetCollectionResult<T>. Note that it is the base that carries the reuse: no framework read returns a bareCollectionResult<T>today, every list read returns one of the two subtypes (the offset one throughEntityQueryService<TEntity, TEntityDTO, TIdentifierType>and the generic controllers of Chapter 12, the keyset one through the repository layer of Chapter 7).
EntityChange<TEntityDTO, TIdentifierType>
MMCA.Common.Shared ·
MMCA.Common.Shared.Abstractions·MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/EntityChange.cs:18· Level 0 · record (sealed)
- What it is: one entry of a change feed (a "what changed since this instant" read): either an upsert carrying the row's normal DTO, or a tombstone for a deleted row carrying no item (
EntityChange.cs:5-9). A page of the feed is aKeysetCollectionResult<T>of these. - Depends on: nothing first-party at the type level. Externals:
System.Runtime.Serialization(BCL) for the[DataContract]/[DataMember]wire attributes. The generic constraintwhere TIdentifierType : notnull(EntityChange.cs:19) is the only rule on the type parameters. - Concept introduced, the delta read with tombstones.
[Rubric §9, API & Contract Design](§9 assesses consistent, evolvable response contracts): a client that already holds a copy of a list asks only for what changed, and the contract has to say not just "here are the new and edited rows" but also "this row is gone", or a deleted row would live on in the client's cache forever. The tombstone (IsDeleted = true, noItem) is that second message.[Rubric §12, Performance & Scalability](§12 assesses whether reads stay bounded as data grows): a delta read moves a handful of rows where a full re-read moves the table, and because a feed page is a keyset page it costs one index seek however far into the feed the client is.[Rubric §11, Security]applies to the tombstone's shape: it carries only the id and the change instant, so no field of a deleted row ever leaves the service. - Walkthrough: four
initproperties, each tagged[DataMember(Order = 1..4)]on a[DataContract]record (EntityChange.cs:17,29,33,37,41) so the wire order is pinned, matching the rest of the family.required TIdentifierType Id(EntityChange.cs:30): the changed row's identifier, the key a client applies the entry by.required bool IsDeleted(EntityChange.cs:34): true for a tombstone.required DateTime ChangedOn(EntityChange.cs:31): the UTC instant of the change, the row's last modification, else its creation.TEntityDTO? Item(EntityChange.cs:35): the DTO for an upsert,nullfor a tombstone. It is the one member not markedrequired, since a tombstone legitimately has none.- The type-level remarks state the client protocol (
EntityChange.cs:12-16): page with the samesinceuntil the next cursor is null, then keep the largestChangedOnas the nextsince. The bound is inclusive, so rows on the boundary arrive again, which is why entries must be applied idempotently byId(plus the DTO's row version when it has one).
- Why it's built this way: an inclusive bound plus idempotent application trades a few repeated rows for never missing one that shares the boundary instant, and riding on the existing keyset page means the feed reuses the cursor, the clamp and the next-page probe of
KeysetPageRequestrather than inventing a second paging scheme. See ADR-144. - Where it's used: built by
EntityQueryService<TEntity, TEntityDTO, TIdentifierType>.GetChangesSinceAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:630-664), which reads one keyset page overLastModifiedOnascending throughChangeFeedSpecification<TEntity, TIdentifierType>(EntityQueryService.cs:637-644), maps only the live rows, and setsChangedOntoLastModifiedOn ?? CreatedOn(EntityQueryService.cs:650-661). The contract onIEntityQueryService<TEntity, TEntityDTO, TIdentifierType>declares it with no default body, so every implementation supplies it, and documents a validation failure for a malformed cursor (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityQueryService.cs:178-191). It reaches HTTP throughGET changesonEntityControllerBase<TEntity, TEntityDTO, TIdentifierType>, opt-in per controller throughSupportsChangeFeedAttribute(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:469-490), and in ADC through the bookmarks feed (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/BookmarksController.cs:120-132). - Caveats / not-in-source: a row that leaves the read scope without being deleted yields no tombstone (
EntityControllerBase.cs:466), and only a soft delete is reported; a client that cached either kind of row keeps it until its next full read (ADR-144).
ErrorType
MMCA.Common.Shared ·
MMCA.Common.Shared.Abstractions·MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ErrorType.cs:24· Level 0 · enum
- What it is: an enum that classifies every domain error into one of ten categories, each of which the API layer maps to an HTTP status code and the gRPC layer maps to a status code of its own.
- Depends on: nothing first-party (BCL only). It is the seed of the Result family:
Error(Level 1) carries anErrorType,ErrorTypeSeverity(Level 2) ranks one, andResult(Level 2) carriesErrors. - Concept introduced, the Result pattern.
[Rubric §2, Design Patterns](§2 assesses whether patterns are idiomatic and solve real problems rather than being pattern theater; here the Result pattern is the codebase's canonical error-flow mechanism, used by practically every factory method, handler, and controller action in both repos). Instead of throwing for expected failures (validation, not-found, conflict), an operation returns aResultthat is either a success or a failure carrying one or moreErrors;ErrorTypeis that pattern's classification axis. It also touches[Rubric §9, API & Contract Design](§9 assesses consistent, standardized error responses): every endpoint produces the same error shape out of the same ten categories. And[Rubric §3, Clean Architecture](dependencies point inward, inner layers stay framework-free): this HTTP-shaped concept lives in the innermost assembly as a pure enum with no reference to ASP.NET, and the translation happens only at the edge. See primer §2 for where the pattern sits among the codebase's committed styles. - Walkthrough: ten members, each with a pinned numeric value and documented with the status it is meant to produce (
ErrorType.cs:27,30,33,36,39,42,45,53,59,67):Validation = 0(400),Invariant = 1(400, a broken business rule),NotFound = 2(404),Conflict = 3(409, for example a duplicate or an already-deleted row),Unauthorized = 4(401),Forbidden = 5(403),UnprocessableEntity = 6(422, for example an attempt to change an immutable field),Unexpected = 8(500),TooManyRequests = 9(429, a temporary refusal such as a login or password-change lockout, where retrying later rather than changing the request is the fix), andUnavailable = 10(503, a dependency such as a storage or push provider, a remote service, or an expired request budget failed or did not answer in time,ErrorType.cs:61-66).- There is no "unclassified" member, and the remarks say so first (
ErrorType.cs:12-19): every error names a meaning, eitherValidation,InvariantorUnprocessableEntitywhen the caller can fix the request,Unavailablewhen retrying later can succeed, orUnexpectedwhen neither holds. The values are pinned explicitly so an in-process or persisted value never moves, and 7 is retired (it was the removedFailuremember) and must not be reused. The wire forms (HTTP Problem Details, gRPC trailers) carry the member name, not the integer. The gap at 7 is also why the enum carries a[SuppressMessage]for CA1027 (ErrorType.cs:20-23): with 7 missing the sequence looks like bit flags to the analyzer, and theJustificationstates that a category is never a combination. Unexpectedcarries the sharpest policy in source (ErrorType.cs:47-52, and the matching factory doc atError.cs:128-140): it is reserved for a genuine server-side fault the caller cannot fix by changing the request and that retrying will not cure (a misconfigured host, an unreachable branch, a corrupt state), and never for a business-rule violation. A dependency that failed or timed out belongs onUnavailableinstead, which is what separates "try again later" (503) from "the server is broken" (500).- The type-level doc comment (
ErrorType.cs:5-11) states the aggregation rule the categories obey: when a result carries several errors, the response status is the one belonging to the highest-ranked category present, so an aggregate can never be downgraded by the ordering of its errors. The ranking itself isErrorTypeSeverity.
- There is no "unclassified" member, and the remarks say so first (
- Why it's built this way: separating classification (this enum) from carrier (
Error) from severity (ErrorTypeSeverity) from outcome (Result) keeps each piece tiny and lets the same ten categories drive domain logic, HTTP translation, and gRPC translation from one source of truth. ADR-013 states the rule the enum encodes: the domain never names an HTTP status. - Where it's used:
Error's ten factory methods each hard-code one member (Error.cs:46,55,64,73,82,91,100,112,125,140);ErrorHttpMappingholds the HTTP table as aFrozenDictionary<ErrorType, int>built once at startup (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:23-35) and resolves through it with a 400 fallback (ErrorHttpMapping.cs:41-42). On the gRPC boundary,ResultGrpcExtensionsperforms the mirror translation, mappingTooManyRequeststoResourceExhaustedandUnavailabletoUnavailable(MMCA.Common/Source/Presentation/MMCA.Common.Grpc/ResultGrpcExtensions.cs:52-53; ADR-007). - Caveats / not-in-source: the per-member HTTP status codes written in this enum's doc comments are documentation, not the mapping. The executable table lives in
ErrorHttpMapping.cs:25-34and currently agrees with them member for member.
KeysetCursor
MMCA.Common.Shared ·
MMCA.Common.Shared.Abstractions·MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/KeysetPagination.cs:126· Level 0 · class (static)
- What it is: the encoder and decoder for the opaque cursor string that a keyset page hands back to the client and receives on the next request.
- Depends on: nothing first-party. Externals:
System.Buffers.Text.Base64UrlandSystem.Text.Encoding(BCL). - Concept introduced, the opaque, versioned cursor. A cursor is a position token, not a page number. The client never parses it; it just echoes back whatever the previous page returned. That gives the server freedom to change the encoding without a client change, which is the
[Rubric §9, API & Contract Design]point (§9 assesses evolvable contracts): the format carries an explicitv1prefix (KeysetPagination.cs:128), so a futurev2encoding is additive andTryDecodekeeps rejecting what it does not recognize rather than mis-seeking silently (KeysetPagination.cs:114-120documents exactly this intent). It also touches[Rubric §11, Security]: the doc comment is blunt that the cursor is neither signed nor encrypted (KeysetPagination.cs:121-124), so it must never carry anything the caller may not see. The two values it does carry, a sort key and an id, are already in the rows the caller just received, which is what makes the unsigned form acceptable rather than a leak. - Walkthrough
- Two private constants define the format:
Version = "v1"andSeparator = '|'(KeysetPagination.cs:128-129). Encode(string? sortValue, string id)(KeysetPagination.cs:140-154) null-checks the id, then builds the payloadv1|{hasSortValue}|{sortValue}|{id}wherehasSortValueis the literal"0"or"1"and both value segments are themselves base64url (KeysetPagination.cs:144-151). Encoding the segments is what stops a sort value that happens to contain a|from forging an extra segment. The whole payload is then base64url encoded once more (KeysetPagination.cs:153), which is what makes the result URL-safe and visibly opaque.TryDecode(string? cursor, out string? sortValue, out string id)(KeysetPagination.cs:170-191) is a strict inverse and aTrymethod by design, because its input is client-supplied. It clears both outputs first (KeysetPagination.cs:172-173), then rejects: a blank or non-base64url cursor (KeysetPagination.cs:175-176), a payload that does not split into exactly four segments or whose first segment is notv1(KeysetPagination.cs:178-180), a flag segment that is neither"0"nor"1"(KeysetPagination.cs:182-183), and a segment that is not valid base64url (KeysetPagination.cs:185-186). Only then does it publish the decoded values, honoring the flag by returningnullfor the sort value when the cursor carries none (KeysetPagination.cs:188-190).TryFromBase64Url(KeysetPagination.cs:196-215) holds the subtle bit and says so in a comment:Base64Url.TryDecodeFromCharsthrows on an invalid character instead of returningfalse, and a client-supplied cursor is precisely the input that will contain one, so the method callsBase64Url.IsValidfirst (KeysetPagination.cs:203-207). An empty string short-circuits to a successful empty decode (KeysetPagination.cs:200-201), which is how a cursor with no sort value round-trips.
- Two private constants define the format:
- Why it's built this way: the version prefix plus the total-failure
Trycontract means a malformed or stale cursor becomes a validation failure the caller can see, never a silent reset to the first page.EFReadRepository<TEntity, TIdentifierType>turns afalsereturn intoError.Validation("Error.InvalidCursor", ...)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:670-675). This is the keyset half of ADR-055. - Where it's used:
Encodeis called once per page byEFReadRepository<TEntity, TIdentifierType>with the last row's sort value and id, both rendered invariantly byKeysetQueryBuilder(EFReadRepository.cs:695-697);TryDecodeis called from the same class'sTryBuildSeekPredicateto rebuild the seek predicate (EFReadRepository.cs:715).
KeysetPageRequest
MMCA.Common.Shared ·
MMCA.Common.Shared.Abstractions·MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/KeysetPagination.cs:20· Level 0 · record (sealed)
- What it is: the request for one keyset ("seek") page: how many rows, ordered by which single sort key in which direction, starting after which cursor.
- Depends on: nothing first-party at the type level. It is paired with
KeysetCollectionResult<T>(whoseNextCursorbecomes this request'sCursor) and decoded byKeysetCursor. - Concept introduced, keyset paging versus offset paging. The type's own doc comment teaches the trade directly (
KeysetPagination.cs:11-17): offset paging, the modePaginationMetadatadescribes, answers "give me page 37" and makes the database scan the 36 pages before it; keyset paging answers "give me what comes after this row" and costs one index seek no matter how deep you are, at the price of losing random page access and a total count. The two coexist, keyset does not replace offset. That is a textbook[Rubric §12, Performance & Scalability]concern (§12 assesses query efficiency and whether reads stay bounded as data grows): deep offset paging degrades linearly with depth, keyset does not.[Rubric §9, API & Contract Design]applies too, because the choice is visible in the response contract: a keyset page returns a cursor where an offset page returns a page number and a count. - Walkthrough
public const int MaxPageSize = 1000(KeysetPagination.cs:27) is the one framework page cap. Its doc comment says the other ceilings are defined as this value so no entry point can be talked into an unbounded read (KeysetPagination.cs:22-26), and the source does exactly that:EntityQueryPipelinedeclaresMaxUnboundedResultLimit = KeysetPageRequest.MaxPageSize(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:25), and the UI's list-page URL ceiling isprivate const int MaxPageSize = KeysetPageRequest.MaxPageSize(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/ListPageQueryStateService.cs:49).- Two constructors: a parameterless one delegating with
pageSize: 1(KeysetPagination.cs:30-31), and the full one (KeysetPagination.cs:46-56). - The page size is clamped, not rejected:
Math.Clamp(pageSize, 1, MaxPageSize)in the constructor (KeysetPagination.cs:52) and again in theinitaccessor (KeysetPagination.cs:63), so a caller asking for zero or a million gets a sane page instead of an error. Theinitaccessor uses the C#fieldkeyword to write the clamped value into the compiler-generated backing field, which is what closes the hole that an object initializer, awithexpression, or a System.Text.Json deserialization would otherwise open by bypassing the constructor entirely. - The remaining three properties are plain
initvalues:SortColumn(nullable; null means order byIdalone,KeysetPagination.cs:68),Descending(KeysetPagination.cs:72), andCursor(nullable; null means the first page,KeysetPagination.cs:76). [DataContract]on the record and[DataMember(Order = 1..4)]on the four properties (KeysetPagination.cs:19,59,67,71,75) pin the wire order.
- Why it's built this way: exactly one sort key is supported, with the entity's
Idas the tie-break, because that is what keeps the seek predicate a single composable comparison. A nullSortColumnkeys the page onIdalone (stated on the contract atMMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:308-311). The sort column must name a real public property:EFReadRepository<TEntity, TIdentifierType>resolves it throughKeysetQueryBuilderand returns anError.InvalidEntityFieldcopy carrying the offending column name when it does not (EFReadRepository.cs:651-660), so an unknown name is a validation failure rather than a silently ignored parameter. See ADR-055. - Where it's used: the sole parameter object of
GetPageByCursorAsync, declared onIEntityQuerier<TEntity, TIdentifierType>(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:318-321, inherited byIReadRepository<TEntity, TIdentifierType>atIRepository.cs:332), implemented byEFReadRepository<TEntity, TIdentifierType>(EFReadRepository.cs:644-701) and forwarded byEFReadRepositoryDecorator<TEntity, TIdentifierType>(EFReadRepositoryDecorator.cs:151-152). - Caveats / not-in-source: because the pipeline and list-page ceilings are defined in terms of
MaxPageSize, changing this one constant moves all three caps at once; there is no separate knob for any of them.
PaginationMetadata
MMCA.Common.Shared ·
MMCA.Common.Shared.Abstractions·MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/PaginationMetadata.cs:12· Level 0 · record (sealed)
- What it is: an immutable record carrying offset-pagination state (total items, page size, current page) plus three derived, non-serialized convenience properties.
- Depends on: nothing first-party. It shares a file with
CollectionResult<T>andPagedCollectionResult<T>. - Concept introduced, server-side offset pagination and the explicit
[DataContract]wire shape.[Rubric §9, API & Contract Design](§9 assesses uniform pagination and filtering conventions across endpoints) and[Rubric §12, Performance & Scalability](§12 assesses whether reads page at the database rather than returning whole tables). Carrying explicit metadata is what lets the API page at the source and still tell the client how to navigate. The keyset alternative for deep scrolling isKeysetPageRequest. - Walkthrough
- Two constructors: a parameterless one delegating to the main constructor with zeros (
PaginationMetadata.cs:15-16), and the main constructor which guards all three arguments withArgumentOutOfRangeException.ThrowIfNegativebefore assigning (PaginationMetadata.cs:22-31). Negative pagination is therefore unrepresentable. - Three stored values, each
initand each tagged[DataMember(Order = 1..3)]:TotalItemCount(PaginationMetadata.cs:38-47),PageSize(PaginationMetadata.cs:50-59), andCurrentPage(PaginationMetadata.cs:62-71). - Each
initaccessor re-validates withArgumentOutOfRangeException.ThrowIfNegativeand assigns through the C#fieldkeyword. The comment above them says why (PaginationMetadata.cs:33-35): object initializers, recordwithexpressions, and System.Text.Json (which builds this type through the parameterless constructor plus theinitsetters) all bypass the constructor guards. Without the duplicated check the guard would be decorative on exactly the paths a client controls. - Three computed properties tagged
[IgnoreDataMember], so they are derived rather than transmitted:TotalPageCount, a ceiling division that returns 0 whenPageSizeis 0 (PaginationMetadata.cs:74-75);FirstRowOnPage, which returns 0 for the several empty cases and otherwise computes the 1-based first index (PaginationMetadata.cs:78-79); andLastRowOnPage, clamped toTotalItemCount(PaginationMetadata.cs:82-83). Note the(long)casts inside both row calculations:CurrentPage * PageSizeis a deliberate overflow guard, since two largeints multiply out of range long before either is individually implausible.
- Two constructors: a parameterless one delegating to the main constructor with zeros (
- Why it's built this way:
[DataContract]/[DataMember]/[IgnoreDataMember]make the wire shape explicit and stable, so only the three primary values travel and the rest are recomputed on the other side. Constructor-plus-initvalidation makes an invalid instance unconstructable, which is the same "validate at the boundary of the type" discipline the value objects of Chapter 2 use. - Where it's used: embedded in
PagedCollectionResult<T>; serialized whole into theX-Paginationresponse header byEntityControllerBase<TEntity, TEntityDTO, TIdentifierType>(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:187); the CSV export endpoint on the same base class does not use this type at all, since truncation there is decided byEntityCsvExporter<TEntityDTO>.WriteAsynccomparing rows written against theMaxExportRowsceiling (EntityControllerBase.cs:290-312). Built byEntityQueryService<TEntity, TEntityDTO, TIdentifierType>in one private helper (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:829, called at:422).
Error
MMCA.Common.Shared ·
MMCA.Common.Shared.Abstractions·MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:15· Level 1 · record
- What it is: the immutable error value carried by
Result. Every error has a machine-readableCode, a human-readableMessage, anErrorTypethat drives the status at the edge, optionalSource/Targetcontext, and an optionalRetryAfterhint for a lockout refusal or an unavailable dependency. - Depends on:
ErrorType(Level 0). No externals beyond the BCL. - Concept introduced, the error as a value.
[Rubric §2, Design Patterns](§2 assesses idiomatic patterns that solve real problems): anErroris a value, not an exception. It can be constructed, put in a list, threaded through a pipeline, merged with other errors, and inspected, all without a throw, a stack capture, or an unwind.[Rubric §9, API & Contract Design](§9 assesses consistent, standardized error responses): the triple ofCode(for programmatic branching by the client),Message(for humans), andErrorType(for the status selector) gives every endpoint a uniform error shape with no controller deciding how to format anything. - Walkthrough
- The type is a positional
recordwith five components (Error.cs:15-20):Code,Message,Type, and the two optional context stringsSourceandTarget, both defaulting tonull. Being a record it gets value equality, so two errors with the same components compare equal, which is what makes error assertions in tests trivial. - Three pre-built
static readonlysingletons for the ubiquitous cases (Error.cs:23,26,29):Error.NotFound,Error.AlreadyDeleted, andError.InvalidEntityField. Each is itself built through a factory method, so the singletons cannot drift from the factory contract. - One property outside the positional list:
TimeSpan? RetryAfter { get; init; }(Error.cs:38), null by default. It is not a factory parameter; a producer that knows how long aErrorType.TooManyRequestsrefusal lasts, or when a dependency behind anErrorType.Unavailableerror will be back, sets it with awithexpression (Error.cs:31-37), and the HTTP edge turns it into theRetry-Afterheader of a 429 or a 503. Being an ordinary record property it also takes part in value equality. - Ten factory methods, one per
ErrorTypemember (Error.cs:46,55,64,73,82,91,100,112,125,140):Validation,Invariant,NotFoundError,Conflict,Unauthorized,Forbidden,UnprocessableEntity,TooManyRequests(for a temporary lockout refusal, HTTP 429),Unavailable(a dependency failed or did not answer in time, HTTP 503,Error.cs:115-125), andUnexpected. Each hard-codes the matchingErrorType, so a caller cannot pair the wrong classification with a code, and there is no catch-all factory for an unclassified failure. Two details worth carrying: the factory isNotFoundErrorrather thanNotFoundbecause the static field already owns that name and C# forbids a field and a method sharing one; andUnexpectedcarries a written usage policy on the factory itself (Error.cs:128-140), namely that it is for a genuine server-side fault the caller cannot fix by changing the request and that retrying will not cure, with a failed or timed-out dependency routed toUnavailableand business-rule violations toInvariantorValidation. - Three
with-expression helpers:WithSource(string)andWithTarget(string)each return a copy with one component replaced (Error.cs:146-147,152-153), andFor<TTarget>(string source)sets both at once, the target beingtypeof(TTarget).Name(Error.cs:163-164). That is how a generic framework error gets enriched with caller context without being mutated: the CRUD handlers writeError.NotFound.For<TEntity>(HandlerName)(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/DeleteEntityHandler.cs:74,MutateEntityHandlerBase.cs:297,ChildEntityHandlerBase.cs:129). - The singletons are
records, so they are also freely refinable at the call site:EFReadRepository<TEntity, TIdentifierType>takesError.InvalidEntityField with { Message = ..., Source = ..., Target = ... }to report an unknown keyset sort column (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:653-659), keeping the sharedCodewhile specializing everything else.
- The type is a positional
- Why it's built this way: modeling an expected failure as data rather than as control flow is the whole point of ADR-013. The pre-built singletons keep the common cases allocation-free, and the factory methods fix the
CodetoErrorTypepairing at the point of creation so no mapping table is needed anywhere else in the codebase. - Where it's used: carried by every failing
Resultin both repos;ValidationFailureExtensionsconverts each FluentValidation failure into anError.Validation(...)carrying the rule's code, message, source, and property name (MMCA.Common/Source/Core/MMCA.Common.Application/Extensions/ValidationFailureExtensions.cs:86-87), where a FluentValidation default code (the validator's class name) is replaced by{PropertyPath}.{Rule}such asEmail.Required, and a missing code by{PropertyPath}.Invalid(ValidationFailureExtensions.cs:94-121);ApiControllerBaserenders the whole list into the Problem Detailserrorsextension, optionally through anIErrorLocalizer(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:72-73, projection atErrorHttpMapping.cs:65-70), and on a 429 or a 503 answers the longestRetryAfteramong the errors of the matching type (TooManyRequestsorUnavailable) as aRetry-Afterheader (ApiControllerBase.cs:75,89-111), the valueLoginProtectionServicesets on its lockout error (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:129);ErrorTypeSeveritypicks one of them to classify the whole failure; andResultJsonConverterFactoryserializes the list as theerrorsarray.
KeysetCollectionResult<T>
MMCA.Common.Shared ·
MMCA.Common.Shared.Abstractions·MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/KeysetPagination.cs:86· Level 1 · record (sealed)
- What it is: the response shape for one keyset page, a
CollectionResult<T>plus the cursor that fetches the following page. - Depends on:
CollectionResult<T>(Level 0). It is the counterpart ofKeysetPageRequestand its cursor is produced byKeysetCursor. - Concept: this is the same envelope idea
CollectionResult<T>introduced, extended in one orthogonal step, but the interesting part is what it deliberately omits. There is no total count and no page number (KeysetPagination.cs:79-83), because a keyset read never pays for either. ComparePagedCollectionResult<T>, which carries both. That asymmetry is honest[Rubric §9, API & Contract Design]: the contract advertises exactly what the read mode can actually deliver instead of faking a count with a second query. It is also the[Rubric §12, Performance & Scalability]payoff, since the count query is usually the expensive half of a deep page. - Walkthrough
sealed recordinheritingCollectionResult<T>(KeysetPagination.cs:86), tagged[DataContract](KeysetPagination.cs:85).- Two constructors mirroring the base, both
[SetsRequiredMembers](KeysetPagination.cs:89,99): a parameterless one producing an empty page with no next cursor (KeysetPagination.cs:90-91), and the data constructor that passes items tobase(items)and assigns the cursor (KeysetPagination.cs:100-101). - One added property:
string? NextCursor { get; init; }tagged[DataMember(Order = 2)]so it serializes afterItems(KeysetPagination.cs:107-108). Null means this page is the last one. The doc comment instructs consumers to treat it as opaque and warns that its encoding is versioned (KeysetPagination.cs:103-106).
- Why it's built this way: nullable-means-last is what lets the repository skip a count entirely. It fetches
PageSize + 1rows as a next-page probe, drops the extra row, and only then emits a cursor (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:683-700); the comment there states the trade explicitly, that a one-row probe is cheaper and more honest than aCOUNTover the whole set (EFReadRepository.cs:684-685). See ADR-055. - Where it's used: the success payload of
GetPageByCursorAsync, declared onIEntityQuerier<TEntity, TIdentifierType>asTask<Result<KeysetCollectionResult<TEntity>>>(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:318) and returned byEFReadRepository<TEntity, TIdentifierType>(EFReadRepository.cs:700). Note the composition: the outcome is aResult, the payload is this envelope, which is the standard pairing throughout the codebase.
PagedCollectionResult<T>
MMCA.Common.Shared ·
MMCA.Common.Shared.Abstractions·MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/PaginationMetadata.cs:119· Level 1 · record (sealed)
- What it is: a
CollectionResult<T>augmented with aPaginationMetadataproperty, the standard shape for an offset-paged API response. - Depends on:
CollectionResult<T>(Level 0) andPaginationMetadata(Level 0). - Concept: the same envelope-plus-one-step extension as
KeysetCollectionResult<T>, but for the offset mode, so it carries the count and page number a cursor page cannot.[Rubric §12, Performance & Scalability](paged reads instead of whole tables) and[Rubric §9, API & Contract Design](a stable, evolvable response contract). Reading the two subtypes side by side is the fastest way to internalize the difference between the two paging modes. - Walkthrough
sealed recordinheritingCollectionResult<T>(PaginationMetadata.cs:119), tagged[DataContract](PaginationMetadata.cs:118).- Two constructors mirroring the base, both
[SetsRequiredMembers](PaginationMetadata.cs:122,129): a parameterless one producing an empty result with a defaultPaginationMetadata(PaginationMetadata.cs:123-124), and the data constructor that callsbase(items)and null-checks the metadata withArgumentNullException.ThrowIfNull(PaginationMetadata.cs:130-135). - One added property:
required PaginationMetadata PaginationMetadata { get; init; }tagged[DataMember(Order = 2)](PaginationMetadata.cs:138-139), so it is never null and always serializes afterItems.
- Why it's built this way:
requiredplus a null-checking constructor covers both construction routes (object initializer and direct constructor call), and the explicitOrder = 2keeps the wire shape deterministic across the base/derived split, which member-declaration order alone would not guarantee. - Where it's used: the payload of every offset-paged read, and a genuinely shared contract rather than a server-only shape. The controller surface declares
Task<ActionResult<PagedCollectionResult<TEntityDTO>>>(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/IEntityControllerBase.cs:43, implemented atEntityControllerBase.cs:157) and copies the metadata into theX-Paginationheader (EntityControllerBase.cs:187), while the Blazor client deserializes the very same type (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:71,84,129), so there is no hand-written mirror DTO to drift.EntityQueryService<TEntity, TEntityDTO, TIdentifierType>builds it (EntityQueryService.cs:428-432), and the notification read handlers inMMCA.Common.Applicationreturn it too.
ErrorTypeSeverity
MMCA.Common.Shared ·
MMCA.Common.Shared.Abstractions·MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ErrorTypeSeverity.cs:32· Level 2 · class (static)
What it is: the single severity ranking over
ErrorType, and the helper that picks the one representativeErrorfrom a failure carrying several. Every transport edge classifies an aggregate failure through this one table.Depends on:
ErrorType(Level 0) andError(Level 1). Externals:System.Collections.Frozen.FrozenDictionary(BCL).Concept introduced, ranking an aggregate failure instead of taking its first error.
[Rubric §9, API & Contract Design](§9 assesses consistent, correct error responses across endpoints) and[Rubric §7, Microservices Readiness](§7 assesses whether a capability behaves identically once a module is extracted behind a network boundary). Here is the problem this type exists to solve, and it is worth understanding before the code.Result.Combineaggregates errors in evaluation order, so a domain factory that checks five fields produces a list ordered by the order the checks happened to run. If the edge classified the whole failure by the first error in that list, an incidentalValidationfailure could downgrade a realForbiddenorUnexpectedin the same list to a 400: the response status would depend on the order somebody wrote the guard clauses. Ranking the categories makes the classification independent of ordering.The second half of the concept is where the ranking lives. It is in
MMCA.Common.Shared, the innermost layer, and not insideMMCA.Common.API, because two edges consume it: HTTP and gRPC. Putting the table in one presentation package would leave the other edge to invent its own rule, and the type's own doc comment names exactly that outcome as the thing to avoid (ErrorTypeSeverity.cs:11-15). This is the small, concrete version of a rule the whole framework follows: anything two transports must agree on belongs below both of them.Walkthrough
Ranks, aprivate static readonly FrozenDictionary<ErrorType, int>built once from a dictionary literal (ErrorTypeSeverity.cs:39-51). The ranking, most to least severe:Unexpected70,Unavailable65 (a dependency is down or slow, below a broken server but above every caller-side category),Unauthorized60,Forbidden50,TooManyRequests45 (a lockout ranks above a state conflict but below a missing or insufficient credential),Conflict40,NotFound30,UnprocessableEntity20, and thenInvariantandValidationsharing one rank of 10 (ErrorTypeSeverity.cs:41-50). All tenErrorTypemembers have a rank. The reasoning for each rung is written onto the type itself as a numbered list (ErrorTypeSeverity.cs:16-27): the server being broken outranks a dependency being unavailable, which outranks the caller not having proven who they are, which outranks the caller being known but not allowed, and so on down to the two categories the caller can fix by changing the request.FrozenDictionaryis the chosen shape because the table is fixed at startup and read on every failure path (ErrorTypeSeverity.cs:35-37).Rank(ErrorType)(ErrorTypeSeverity.cs:60) is a one-lineGetValueOrDefault(errorType, 0). The zero default is load-bearing, and the doc comment says why (ErrorTypeSeverity.cs:53-56): a category added toErrorTypewithout a rank here ranks lowest, so a new member can never silently outrank a real 403 or 500. The failure mode of forgetting to update this table is a too-low status, which is visible, not a too-high one, which would be a security-shaped surprise.MostSevere(IReadOnlyList<Error>)(ErrorTypeSeverity.cs:72-99) selects the representative error. It null-checks (ErrorTypeSeverity.cs:74) and rejects an empty list outright withArgumentException(ErrorTypeSeverity.cs:76-81), because a failure with no errors is not classifiable and theResultfactories already make that state unreachable. It then seeds fromerrors[0](ErrorTypeSeverity.cs:83-84) and scans forward keeping strictly greater ranks (ErrorTypeSeverity.cs:88-96). The strict>is what implements "ties keep the earliest error", so a list of same-rank errors behaves exactly as a positional selection would, which is the compatibility property that made the change safe to make.- The scan is a hand-written index loop with a comment defending it (
ErrorTypeSeverity.cs:86-87): a LINQMaxBywould allocate an enumerator plus a comparer closure on a path that runs on every failure response. That is[Rubric §12, Performance & Scalability]reasoning applied at the right scale, a hot path, with the trade written down rather than assumed.
Why it's built this way: ADR-013 records the decision and its history. Only the status is ranked: every error still travels in the payload, in the Problem Details
errorsarray on HTTP (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:62-70) and in the gRPC trailers on the other edge. The ranking answers exactly one question, "what is this failure, in one word", and answers it the same way on both transports.Where it's used: HTTP resolves a status through it,
ErrorHttpMapping.GetStatusCode(IReadOnlyList<Error>)callingMostSevere(ErrorHttpMapping.cs:54-55) on behalf ofApiControllerBase.HandleFailure(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:63). gRPC does the same inResultGrpcExtensions.ToRpcException(MMCA.Common/Source/Presentation/MMCA.Common.Grpc/ResultGrpcExtensions.cs:110, falling back toInternalfor the impossible empty case). The UI uses the other half of the type:ResultUiExtensions.LocalizedErrorMessagesorders the messages it shows a user byRankdescending, so the most severe error is read first (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ResultUiExtensions.cs:143).
Result
MMCA.Common.Shared ·
MMCA.Common.Shared.Abstractions·MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Result.cs:21· Level 2 · class
What it is: the non-generic railway-oriented outcome type, either a success (no errors) or a failure carrying one or more
Errorinstances. The non-generic form covers void-equivalent operations (invariant checks, deletes, commands with nothing to return); the sealed genericResult<T>in the same file (Result.cs:192) adds aValueon the success path and the full combinator set.Depends on:
Error(Level 1) andResultJsonConverterFactory, which is attached to both classes by a type-level[JsonConverter(typeof(ResultJsonConverterFactory))](Result.cs:20,191). Externals:System.Collections.Generic,System.Text.Json.Serialization,System.Diagnostics.CodeAnalysis(BCL).Concept introduced, railway-oriented programming and the combinators.
[Rubric §2, Design Patterns](the Result pattern as the codebase's canonical error-flow mechanism, not an exception crutch),[Rubric §9, API & Contract Design](one structured failure shape behind every endpoint), and[Rubric §12, Performance & Scalability]in the allocation choices below.The railway metaphor: picture two parallel tracks, success and failure. Each step takes the current result as input; if it is already a failure the step is skipped and the train stays on the failure track, and if it is a success the step runs and may stay on the success track or switch. Control flows forward with no nested
try/catchand noif (result.IsFailure)at every line.ErrorTypeclassifies the failure,Errorcarries it,ErrorTypeSeverityranks it when there are several, andResultis the envelope that moves it.The non-generic
Result:- Two shared instances back the cheap paths:
CachedSuccess(Result.cs:23) and an emptyNoErrorsarray (Result.cs:24). Errors live in a lazily allocatedList<Error>? _errors(Result.cs:28), and the comment above it states the reason (Result.cs:26-27): the success path, which is the overwhelming majority of results created per request, never pays for a list allocation. Errorsreturns the list or falls back to the shared empty array (Result.cs:36);IsSuccessis_errors is null || _errors.Count == 0(Result.cs:39) andIsFailureis its negation (Result.cs:42). Success is therefore derived from the error count, not stored, which is the fact the guard two bullets down exists to protect.- Implicit lifting.
public static implicit operator Result(Error error)(Result.cs:50) lets a guard clause writereturn someError;with no factory named, andFromError(Result.cs:56-60) is the named alternate the analyzers require for that operator. The generic type has the same pair plus one more:ErrortoResult<T>(Result.cs:242-246) and, on the happy path,TtoResult<T>(Result.cs:258) so a handler writesreturn theValue;. Both operators carry a[SuppressMessage]with the reasoning written into theJustification(Result.cs:238-241,254-257), which is worth reading as an example of how this codebase documents an analyzer exception at the point of the exception. - The constructor is
private protected(Result.cs:31-33), and the type remarks state why (Result.cs:17-18): a result is built only through the static factories andResult<T>, so no subclass outside this assembly can bypass the failure guards. private protected void AddErrors(IEnumerable<Error> errors)(Result.cs:64) is the only mutation point, and it null-coalescing-assigns the list on first use. Beingprivate protectedrather thanprotected, it is reachable only fromResult<T>inside the same assembly.Result.Success()(Result.cs:69) returns the shared singleton;Result.Success<T>(value)(Result.cs:75) wraps a value in a newResult<T>.- Four failure factories:
Failure<T>(IEnumerable<Error>)(Result.cs:81),Failure(IEnumerable<Error>)(Result.cs:90-96),Failure(Error)(Result.cs:101-102), andFailure<T>(Error)(Result.cs:108-109), the single-error overloads delegating to the collection ones. private protected static void ThrowIfNoErrors(Result result)(Result.cs:114-122) is the guard that makes the derived-success design safe. BecauseIsSuccessis computed from the error count, an accidentally empty collection handed toFailure(...)would otherwise produce a success from a call that explicitly asked for a failure, so the guard throwsArgumentExceptioninstead.Result.Failure(IEnumerable<Error>)calls it after adding (Result.cs:94), and so doesResult<T>'s failure constructor (Result.cs:229).Result.Combine(params ReadOnlySpan<Result> results)(Result.cs:131-152) is the aggregate-all-failures combinator: it walks every input, collects all errors into one list, and returns success only when every input succeeded (Result.cs:140-151). It throwsArgumentExceptionon an empty span, since combining nothing is a logic bug (Result.cs:133-136). Two allocation details:params ReadOnlySpan<Result>means the common call site passes a stack-allocated span rather than an array, andallErrorsis only allocated once a failure is actually seen (Result.cs:138,144).- Two combinators on the valueless type so a void-equivalent step composes the same way:
Match(Result.cs:162-168) andBind(Result.cs:176-180), which returns this same failed instance without running the binder (Result.cs:179).
The generic
Result<T>(Result.cs:192):sealed class Result<T> : Resultaddingpublic T? Value { get; }(Result.cs:195), which is the default ofT(nullfor a reference type) when the result is a failure.bool TryGetValue([MaybeNullWhen(false)] out T value)(Result.cs:206-216) is the house idiom for consuming a result, and the type's own summary names it so (Result.cs:187-188): a step that fails returns early, and the next step uses the unwrapped value (for exampleif (!getResult.TryGetValue(out var found))atMMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:563). Its doc comment gives the reason to prefer it over readingValueafter anIsSuccesscheck (Result.cs:197-203): the compiler tracks the[MaybeNullWhen(false)]contract, so the success branch needs no!, and deleting or reordering the check breaks the build instead of letting a null escape.- Two
internalconstructors (Result.cs:220for success,Result.cs:226-230for failure) so only the base class's static factories can produce an instance. Application code can never writenew Result<Order>(...). Match<TResult>(onSuccess, onFailure)(Result.cs:269-277) terminates the railway by collapsing both tracks into one value; both delegates are null-checked and exactly one branch runs.Map<TOut>(mapper)(Result.cs:285-289) transforms the success value and propagates the errors untouched on failure, so a DTO projection needs noif.Bind<TOut>(binder)(Result.cs:311-315) andBindAsync<TOut>(binder)(Result.cs:298-302) are the monadic bind, sync and async: on failure they short-circuit and return the original errors without invokingbinder.- Every combinator short-circuits on failure, at
Result.cs:288,:301, and:314. That uniformity is the property that makes them composable: you can read a chain top to bottom and know that nothing after the first failure ran.
- Two shared instances back the cheap paths:
Why it's built this way: ADR-013 is the decision record. Expected failures are values, not exceptions, because an exception is invisible in the signature, easy to forget to catch, expensive on the throw path, and conflates "we will not do this" with "the process is broken". Keeping the base constructor
private protected, the value-bearing constructorsinternal, and routing everything through the factories plusThrowIfNoErrorsis what makes the central invariant hold by construction: a result is always either a clean success or a non-empty failure, never a half-built object. The implicit conversions exist so that discipline costs nothing at the call site.Where it's used: as a return type, everywhere. Value-object and entity factories return it, for example
Address.Creategathers its per-field checks withResult.Combine(MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/Address.cs:77), as doesAddressInvariants(MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/AddressInvariants.cs:40); every CQRS handler in Chapter 5 threads one through the decorator pipeline; every controller action in Chapter 12 unwraps one; the repository contract of Chapter 7 returnsResult<KeysetCollectionResult<TEntity>>for a keyset page; andResultGrpcExtensionscarries one across a process boundary in Chapter 13.Caveats / not-in-source: the two halves of the surface get very different amounts of use, and you should calibrate on that when you read the applications.
Result.Combineand the early return throughTryGetValueare the dominant idioms (.TryGetValue(outappears 303 times across 147 files inMMCA.ADC/Source, and in framework code such asMMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:563,616,645). The fluent combinators (Match,Map,Bind,BindAsync) are implemented and unit-tested inMMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Abstractions/ResultTests.cs. Of the four, onlyMaphas production callers, and they sit in the client-side UI service layer, where a fetched result is reshaped for a component: the framework'sEntityServiceBaseprojects its pages with it (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:88,133,145), and the ADC module UI services follow suit (for exampleMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Feedback/OrganizerFeedbackService.cs:37andMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Services/UserService.cs:59). A search ofMMCA.Common/SourceandMMCA.ADC/Sourcefinds no production call site forMatch,BindorBindAsync. Read those three as available surface, not as prevailing style.
CsvRow
MMCA.Common.Shared ·
MMCA.Common.Shared.Serialization·MMCA.Common/Source/Core/MMCA.Common.Shared/Serialization/CsvReader.cs:296· Level 0 · class (sealed)
- What it is: one parsed CSV record: the 1-based line it starts on plus its field values, exactly as written.
CsvReaderproduces every row, andCsvTableholds the data rows below its header. - Depends on: nothing first-party. Externals:
IReadOnlyList<string>(BCL). - Concept introduced, a forgiving cell accessor.
[Rubric §15, Best Practices & Code Quality](§15 assesses defensive, low-ceremony code that removes repeated guard clauses from callers). Real exports end a record early when its trailing cells are empty, so a caller indexing a short row would otherwise need a bounds check on every read. Both accessors here answer an empty string instead, andGet(int?)also absorbs thenullthatCsvTable.FindColumnreturns for a missing optional header, so an importer can resolve its optional columns once and read them unconditionally. - Walkthrough
- Primary constructor
(int lineNumber, IReadOnlyList<string> fields)(CsvReader.cs:296);Parsercalls it with the line the record started on and a copy of the collected fields (CsvReader.cs:225). LineNumber(CsvReader.cs:299): the line the record starts on. A quoted field may span several physical lines, so this is not a record index.Fields(CsvReader.cs:302): the values untrimmed, in column order.- The indexer
this[int column](CsvReader.cs:307): the value whencolumnis within0..Count-1, otherwisestring.Empty(a negative index included). Get(int? column)(CsvReader.cs:316): unwraps a non-null index into the indexer and returnsstring.Emptyfornull.
- Primary constructor
- Why it's built this way: carrying
LineNumberon the row lets an importer report a failure against the line a person sees in a spreadsheet;ImportRowErrorDTOdocuments its line as exactly this value (MMCA.Common/Source/Core/MMCA.Common.Shared/Imports/ImportRowErrorDTO.cs:13). - Where it's used: ADC's
TicketLeapRosterParserreads each roster entry from a row (ReadEntry(CsvRow row, Columns map),MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Infrastructure/Tickets/TicketLeap/TicketLeapRosterParser.cs:120) and builds a row-level failure from one (TicketLeapRosterParser.cs:144). - Caveats / not-in-source: the empty-string fallback cannot distinguish a cell written as empty from a cell the record never had; a caller that needs that difference reads
Fields.Count.
PropertyReader
MMCA.Common.Shared ·
MMCA.Common.Shared.Serialization·MMCA.Common/Source/Core/MMCA.Common.Shared/Serialization/ResultJsonConverterFactory.cs:118· Level 0 · delegate
- What it is: a small private delegate that
ResultJsonConverterFactoryuses to hand each property of aResultJSON payload to a per-converter callback while one shared object-walker drives the reader. - Depends on:
System.Text.Json.Utf8JsonReader(BCL), taken byref. - Concept introduced, a callback shape that can carry a
ref struct.[Rubric §15, Best Practices & Code Quality](§15 assesses DRY and whether shared mechanics are factored out rather than copy-pasted). The two nested converters differ only in which JSON properties they care about, so the property loop is factored into a singleReadObjectand this delegate is howReadObjectcalls back into each one. Therefis not stylistic:Utf8JsonReaderis aref struct, it cannot be a generic type argument, so an ordinaryFunc<Utf8JsonReader, ...>is not expressible. A hand-written delegate with arefparameter is the only shape available, and passing byrefalso means the callback advances the same reader the walker is driving rather than a copy. - Walkthrough: a one-line private declaration,
private delegate void PropertyReader(ref Utf8JsonReader reader, string propertyName)(ResultJsonConverterFactory.cs:118).ReadObjecttakes one as its third parameter (ResultJsonConverterFactory.cs:121), positions the reader on each property's value token, and invokes the delegate once per property (ResultJsonConverterFactory.cs:136-140). - Why it's built this way: keeping all the token-stream bookkeeping (the
StartObjectcheck, theEndObjecttermination, the truncation guards) in one place and passing only "what to do with this property" as a delegate means the JSON walk exists once instead of twice, and a fix to the walk fixes both converters. - Where it's used: only inside
ResultJsonConverterFactory.ResultConverter.Readpasses a lambda of this shape (ResultJsonConverterFactory.cs:44-50) and the genericResultConverter<T>.Readpasses a richer one (ResultJsonConverterFactory.cs:72-88). - Caveats / not-in-source: it is
privateto the factory, so it is not part of any public API and no consumer can name it.
CsvTable
MMCA.Common.Shared ·
MMCA.Common.Shared.Serialization·MMCA.Common/Source/Core/MMCA.Common.Shared/Serialization/CsvReader.cs:239· Level 1 · class (sealed)
- What it is: a parsed CSV file split into its trimmed header names and its data rows (
CsvRow), with two header lookups that turn a column name into an index. - Depends on:
CsvRow. Externals:StringComparison.OrdinalIgnoreCase(BCL). - Concept introduced, header-addressed columns.
[Rubric §9, API & Contract Design](§9 assesses tolerant, stable contracts at a system's edge). An exported file's column order and capitalization are not under the importer's control, so the table resolves a column by name, case-insensitively, and accepts several spellings in preference order. An importer depends on the header text rather than on a position that a vendor can reorder. - Walkthrough
- Primary constructor
(IReadOnlyList<string> headers, IReadOnlyList<CsvRow> rows)(CsvReader.cs:239).CsvReader.ReadTablebuilds it from the first record's fields, each trimmed (CsvReader.cs:53), and the remaining records (CsvReader.cs:54-55). Headers(CsvReader.cs:242) andRows(CsvReader.cs:245): file order, header row excluded fromRows.FindColumn(params string[] names)(CsvReader.cs:253-269): throws on a null array (CsvReader.cs:255), then tries each name in order against every header withstring.Equals(..., name.Trim(), StringComparison.OrdinalIgnoreCase)(CsvReader.cs:261), returning the first match's zero-based index. The outer loop is over names, so the first accepted spelling that exists wins regardless of column position. No match returnsnull(CsvReader.cs:268).FindColumnStartingWith(string prefix)(CsvReader.cs:277-291): the first header that starts with the trimmed prefix, case-insensitively (CsvReader.cs:283), for exports that append a varying label (a question's full text) to a header;nullwhen none does.
- Primary constructor
- Why it's built this way: returning
int?rather than throwing or returning-1pairs directly withCsvRow.Get(int?), so a missing optional column reads as empty and a missing required column is a plainnullcheck the importer turns into its own validation failure. - Where it's used:
TicketLeapRosterParserresolves its required and optional columns withFindColumn(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Infrastructure/Tickets/TicketLeap/TicketLeapRosterParser.cs:176-180,202-206);TicketRosterImportControllerchecks a table for blankness (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/TicketRosterImportController.cs:141); andCsvUploadcarries one beside the raw upload (MMCA.Common/Source/Presentation/MMCA.Common.API/Uploads/FormFileUploadExtensions.cs:24). - Caveats / not-in-source: both lookups are linear scans per call; callers resolve indexes once per file rather than per row. Duplicate headers resolve to the leftmost match.
Parser
MMCA.Common.Shared ·
MMCA.Common.Shared.Serialization·MMCA.Common/Source/Core/MMCA.Common.Shared/Serialization/CsvReader.cs:96· Level 1 · class (private sealed, nested)
- What it is: the private single-pass state machine inside
CsvReaderthat walks the text one character at a time and emitsCsvRowrecords, or stops at the first malformed construct with a message and the line it names. - Depends on:
CsvRowand the enclosing class'sQuoteandCommaconstants (CsvReader.cs:34-35). Externals:StringBuilder,CultureInfo.InvariantCulture(BCL). - Concept introduced, a hand-rolled RFC 4180 tokenizer with errors as values.
[Rubric §15, Best Practices & Code Quality](§15 assesses small, single-purpose members and avoiding exceptions for expected failures). Each private member handles one token kind, and every member returnsstring?:nullto continue, a message to stop. That keeps malformed input on the same return path as success, so the outer reader can wrap it in a validationErrorinstead of catching anything. - Walkthrough
- State (
CsvReader.cs:98-104): the fields of the current record, the current field'sStringBuilder, the read position (starting at 1 when the first character is a byte-order mark,CsvReader.cs:100), the current physical line and the line the current record began on, plus two flags,_recordHasContentand_fieldHasContent. Records(CsvReader.cs:106) andErrorLine(CsvReader.cs:109), the outputs.Run(CsvReader.cs:113-134): aswitchper character (CsvReader.cs:118-124). A quote opens a quoted field only when the field has no content yet; a quote mid-field falls through toAppendas a literal. A comma ends the field, CR or LF ends the line, anything else is appended. The first non-null message is returned; at end of text the last record is flushed (CsvReader.cs:132).AppendandEndField(CsvReader.cs:136-153): both mark the record as having content, so a line holding only a comma is a record of two empty fields.EndLine(CsvReader.cs:155-162): flushes the record, consumes a CRLF pair as one break (CsvReader.cs:158), and moves both line counters forward.ReadQuotedField(CsvReader.cs:164-194): remembers the opening line, appends everything (commas and line breaks included, each break counted throughCountLineBreak), turns""into one quote (CsvReader.cs:178-182), and on the closing quote hands off toFollowsClosingQuote(CsvReader.cs:183-189). Running out of text setsErrorLineto the opening line and returns "A quoted field opened on line N is never closed." (CsvReader.cs:192-193).FollowsClosingQuote(CsvReader.cs:197-206): after a closing quote only end of text, a comma, CR or LF may follow; anything else setsErrorLineand returns "Unexpected text after a closing quote on line N." (CsvReader.cs:204-205).CountLineBreak(CsvReader.cs:209-215) counts a CRLF inside a quoted field once, on its LF;IsAt(CsvReader.cs:217) is the bounds-safe lookahead.EndRecord(CsvReader.cs:219-232): adds the record only when it had content, so a truly blank line is skipped (CsvReader.cs:222), stamping the row with the line the record started on (CsvReader.cs:224-225), then resets the per-record state.
- State (
- Why it's built this way: tracking the record's starting line separately from the current line is what lets a
CsvRowreport the line a person sees even when a quoted field spans breaks, and lets the error name the line where an unclosed quote opened rather than the end of the file. Messages are built with the invariant culture so the line number never picks up a locale's digit formatting. - Where it's used: only by
CsvReader.ReadRecords(CsvReader.cs:81-82); it is private, so no consumer can name it. - Caveats / not-in-source: the delimiter is fixed to a comma (
CsvReader.cs:35); semicolon- or tab-separated exports are not supported. Parsing stops at the first error, so a file with several problems reports only the first.
ResultConverter
MMCA.Common.Shared ·
MMCA.Common.Shared.Serialization·MMCA.Common/Source/Core/MMCA.Common.Shared/Serialization/ResultJsonConverterFactory.cs:35· Level 2 · class (private sealed, nested)
- What it is: the private nested
JsonConverter<Result>for the non-genericResult. A structurally similar generic sibling,ResultConverter<T>(ResultJsonConverterFactory.cs:63), handlesResult<T>and additionally round-trips the successValue. - Depends on:
Result,Error,PropertyReader, and the enclosingResultJsonConverterFactory, which owns the sharedReadObjectandWriteErrorshelpers and the two property-name constants. Externals:System.Text.Json. - Concept introduced, round-tripping a factory-constructed type.
[Rubric §12, Performance & Scalability](the distributed query cache stores handler results, so aResultmust survive a serialize/deserialize cycle) and[Rubric §9, API & Contract Design](a compact, stable wire shape). BecauseResultkeepsinternalconstructors and get-only properties, System.Text.Json's default reflection-based deserializer cannot rebuild one. This converter reads the compact{"value": ..., "errors": [...]}shape and reconstructs through the public factory methods, which is what keeps a rehydrated result subject to the same success-or-non-empty-failure invariant a freshly built one obeys. Setting fields directly would have bypassed exactly that guard. - Walkthrough
Read(ResultJsonConverterFactory.cs:40-53): declaresList<Error>? errors, then drives the sharedReadObjectwith aPropertyReaderlambda that deserializes theerrorsarray on a case-insensitive name match and callsreader.Skip()on everything else (ResultJsonConverterFactory.cs:44-50). It returnsResult.Failure(errors)when errors were present andResult.Success()otherwise (ResultJsonConverterFactory.cs:52).- The comment above
Readrecords a deliberate asymmetry (ResultJsonConverterFactory.cs:37-39): the non-genericResultcarries no value, soWriteemits a bare{}for a success. An empty object is therefore the legitimate wire form here and must stay a success, unlike in the generic converter where it means a corrupt payload. Write(ResultJsonConverterFactory.cs:55-60): opens an object, delegates to the sharedWriteErrors, closes it.WriteErrorsreturns immediately on success, so nothing but{}is written (ResultJsonConverterFactory.cs:146-153).- The generic
ResultConverter<T>(ResultJsonConverterFactory.cs:63) mirrors the shape but tracks two extra booleans,sawValueandsawErrors(ResultJsonConverterFactory.cs:69-70), set as the walker encounters each property (ResultJsonConverterFactory.cs:72-88). If neither was seen it throwsJsonException(ResultJsonConverterFactory.cs:95-98), and the comment explains why in detail (ResultJsonConverterFactory.cs:90-94):Writealways emits one of the two properties, so an object carrying neither is a truncated or partially overwritten cache entry, and returningResult.Success(default!)there would hand the caller a fake success wrapping null. A success whose value genuinely is null still writes"value": null, which setssawValueand stays a success. ItsWrite(ResultJsonConverterFactory.cs:103-115) emitsvalueonly when the resultIsSuccessand then delegates to the sameWriteErrors.
- Why it's built this way: reconstructing through
Result.Failure/Result.Successrather than through field assignment keeps a deserialized result honest (a value only on success, errors only on failure), and the corrupt-payload guard turns a cache-level data problem into a loudJsonExceptioninstead of a silent wrong answer. Writing only the property that applies keeps the payload minimal, which matters when every cached query result pays for it. Nesting both converters privately inside the factory keeps them an implementation detail no consumer can bind to. - Where it's used: instantiated only by
ResultJsonConverterFactory.CreateConverter(ResultJsonConverterFactory.cs:28-32); never referenced by application code.
ResultJsonConverterFactory
MMCA.Common.Shared ·
MMCA.Common.Shared.Serialization·MMCA.Common/Source/Core/MMCA.Common.Shared/Serialization/ResultJsonConverterFactory.cs:15· Level 2 · class (sealed)
- What it is: a
JsonConverterFactorythat produces the right converter forResultor for any closedResult<T>, wired onto both types by a type-level[JsonConverter(typeof(ResultJsonConverterFactory))]attribute (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Result.cs:20,191). - Depends on:
Result,Error,ResultConverterand its generic sibling,PropertyReader. Externals:System.Text.Json(JsonConverterFactory,Utf8JsonReader,Utf8JsonWriter) andSystem.Activator. - Concept introduced, the converter factory for an open generic. A
JsonConverter<T>is bound to one closed type, soResult<Order>,Result<CategoryDTO>, and every other closure would each need their own registration. AJsonConverterFactoryinverts that: it answers "can I handle this type?" at runtime and manufactures the right closed converter on demand, so one attribute covers everyResult<T>in both repos forever.[Rubric §15, Best Practices & Code Quality](the mechanism exists once rather than per type) and[Rubric §12, Performance & Scalability], since without it the distributed result cache could not store a handler result at all. - Walkthrough
- Two private constants fix the wire shape for both converters:
ValuePropertyName = "value"andErrorsPropertyName = "errors"(ResultJsonConverterFactory.cs:17-18). CanConvert(ResultJsonConverterFactory.cs:21-23): true fortypeof(Result)exactly, or for any generic type whose generic type definition isResult<>.CreateConverter(ResultJsonConverterFactory.cs:26-33): returns aResultConverterfor the non-generic case (ResultJsonConverterFactory.cs:28-29), and otherwise pulls the value type off the closed generic and constructsResultConverter<T>reflectively viaActivator.CreateInstance(typeof(ResultConverter<>).MakeGenericType(valueType))(ResultJsonConverterFactory.cs:31-32). That reflective construction happens once per closed type, not once per payload, because System.Text.Json caches converters per type in theJsonSerializerOptions.ReadObject(ResultJsonConverterFactory.cs:121-144) is the shared object walker both converters drive through aPropertyReader. It requires aStartObjecttoken (ResultJsonConverterFactory.cs:125-126), returns onEndObject(ResultJsonConverterFactory.cs:130-131), demands aPropertyNametoken at each step (ResultJsonConverterFactory.cs:133-134), advances onto the value and throws on truncation (ResultJsonConverterFactory.cs:137-138), invokes the callback (ResultJsonConverterFactory.cs:140), and throwsJsonExceptionif the reader runs out before the closing brace (ResultJsonConverterFactory.cs:143). Itsoptionsparameter is deliberately discarded with_ = options(ResultJsonConverterFactory.cs:123).WriteErrors(ResultJsonConverterFactory.cs:146-153) is the shared writer: it returns without writing anything when the result is a success, and otherwise emits theerrorsarray through the ambient options.
- Two private constants fix the wire shape for both converters:
- Why it's built this way: the Result types deliberately keep internal constructors and get-only properties (the construction discipline described under
Result), and the doc comment states the consequence plainly (ResultJsonConverterFactory.cs:7-14): default reflection-based deserialization cannot rehydrate them, so a purpose-built factory is what makes the type round-trippable for the distributed query cache. That cache path is real:CachingQueryDecorator<TQuery, TResult>reads and writes whole handler results (aResult<...>in practice) throughICacheService(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:43-48), andHybridCacheServicehands those values toHybridCache(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/HybridCacheService.cs:298), whichAddHybridCache()registers with no custom serializer (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:199), so its default System.Text.Json path, and with it this converter, carries them into L2. Centralizing the token bookkeeping inReadObject/WriteErrorsand the callback shape inPropertyReaderkeeps the two concrete converters small and structurally parallel. - Where it's used: attached to
ResultandResult<T>by attribute, so System.Text.Json picks it up automatically wherever a result is serialized, most consequentially on the cache path of Chapter 9 and anywhere a result is written to an HTTP or gRPC payload. - Caveats / not-in-source: the doc comment names Redis specifically (
ResultJsonConverterFactory.cs:11-12), but the code path isIDistributedCache-shaped:HybridCacheServiceis registered byAddCommonHybridCachefor any host with a distributed L2, and a host without one keepsMemoryCacheService(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/HybridCacheService.cs:14-15). The converter is backing-store agnostic; which store a given host runs is a composition-time choice, not visible here.
CsvReader
MMCA.Common.Shared ·
MMCA.Common.Shared.Serialization·MMCA.Common/Source/Core/MMCA.Common.Shared/Serialization/CsvReader.cs:23· Level 3 · class (static)
- What it is: the framework's RFC 4180 CSV reader. It turns text or a stream into a
CsvTable(first record as header) or a flat list ofCsvRowrecords, and reports malformed or empty input as aResultfailure, never as an exception. - Depends on:
Result,Error,CsvTable,CsvRow, and its privateParser. Externals:StreamReader,Encoding.UTF8,CultureInfo.InvariantCulture(BCL). - Concept introduced, parsing on the Result railway.
[Rubric §15, Best Practices & Code Quality](§15 assesses using exceptions only for the exceptional). A badly formed upload is an expected input, not a bug, so the reader returns a validationErrorand the doc comment states the intent directly: a malformed file is "a validation failure naming the line, never an exception, so an upload endpoint can answer 400 with it" (CsvReader.cs:20-21).[Rubric §27, Internationalization](§27 assesses whether user-facing messages can be translated): the line number also travels as the error'sTargetso the edge localizer can parameterize the translatedCsv.Malformedmessage on it (CsvReader.cs:84-85). - Walkthrough
- Two public codes (
CsvReader.cs:29,32):MalformedCode = "Csv.Malformed", whose errorTargetcarries the offending line in invariant digits, andEmptyCode = "Csv.Empty"for text with no header row. PrivateQuoteandCommaconstants fix the syntax (CsvReader.cs:34-35). ReadRecords(string text)(CsvReader.cs:77-93): throws on null text (CsvReader.cs:79), runs aParser(CsvReader.cs:81-82), and returns either the records orError.Validation(MalformedCode, message, nameof(ReadRecords), line)withparser.ErrorLineformatted invariantly (CsvReader.cs:86-92). No header interpretation happens here.ReadTable(string text)(CsvReader.cs:40-56): callsReadRecords, passes a malformed failure through unchanged (CsvReader.cs:43-46), returnsEmptyCodewhen there are no records at all (CsvReader.cs:48-51), and otherwise trims the first record's fields into headers and keeps the rest as rows (CsvReader.cs:53-55).ReadTableAsync(Stream, CancellationToken)(CsvReader.cs:65-72): wraps the stream in aStreamReaderthat detects a byte-order mark, falls back to UTF-8 and leaves the stream open (CsvReader.cs:69), reads to the end, then delegates toReadTable. The doc comment puts size limits on the caller (CsvReader.cs:59-60).- Format rules, from the remarks (
CsvReader.cs:11-19): quoted fields may hold commas, line breaks and doubled quotes; records end at CRLF, LF or a lone CR; a leading byte-order mark is dropped; blank lines are skipped; values are returned untrimmed while header names are trimmed.
- Two public codes (
- Why it's built this way: keeping the reader in
MMCA.Common.Sharedwith only BCL dependencies means any layer can parse a file without a third-party CSV package, and splittingReadRecordsfromReadTablelets a header-less caller reuse the tokenizer. Returning the reader's own errors unchanged lets the upload layer surface them as-is:ReadCsvAsyncdocuments that malformed or empty text comes back with these codes (MMCA.Common/Source/Presentation/MMCA.Common.API/Uploads/FormFileUploadExtensions.cs:65-69). - Where it's used: the API upload helper
ReadCsvAsync(FormFileUploadExtensions.cs:72) callsReadTableAsync(FormFileUploadExtensions.cs:124) to build aCsvUpload; ADC'sTicketLeapRosterParsercalls it directly (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Infrastructure/Tickets/TicketLeap/TicketLeapRosterParser.cs:66), andTicketRosterImportControllerrefers toEmptyCode(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/TicketRosterImportController.cs:94). - Caveats / not-in-source:
ReadTableAsyncreads the whole stream into one string before parsing, so it is not a streaming reader; bounding the input is the caller's job (CsvReader.cs:59-60). The comma delimiter is fixed.
CsvWriter
MMCA.Common.Shared ·
MMCA.Common.Shared.Serialization·MMCA.Common/Source/Core/MMCA.Common.Shared/Serialization/CsvWriter.cs:45· Level 5 · class (static)
- What it is: the framework's RFC 4180 CSV writer, the writing half beside
CsvReader(CsvWriter.cs:13). It writes a byte-order mark, a header record and data records one at a time into a caller-suppliedTextWriter, formatting every cell with fixed, invariant rules. - Depends on:
MoneyandCurrencyfor their value forms (CsvWriter.cs:164-165). Externals:TextWriter,UTF8Encoding,SearchValues<char>,ConcurrentDictionary,System.Text.Json,CultureInfo.InvariantCulture(BCL). - Concept introduced, deterministic cell formatting.
[Rubric §15, Best Practices & Code Quality](§15 assesses avoiding needless dependencies and keeping one implementation of a shared mechanic). The remarks record the choice to hand-write the writer rather than take a CsvHelper dependency, because the framework needs exactly three behaviours (quote when required, escape embedded quotes, end with CRLF) and every package it ships is inherited by every consumer (CsvWriter.cs:22-24).[Rubric §27, Internationalization](§27 assesses culture-correct formatting): values are formatted invariantly "so the same row produces the same bytes on every machine" (CsvWriter.cs:27). - Walkthrough
Utf8ByteOrderMark(CsvWriter.cs:58): the BOM as a property rather than a constant so the declared public API stays plain ASCII; it is written unconditionally because Excel reads a BOM-less UTF-8 CSV in the machine's ANSI code page (CsvWriter.cs:51-56).LineEnding = "\r\n"(CsvWriter.cs:61): CRLF regardless of the host operating system.Utf8NoPreamble(CsvWriter.cs:68): UTF-8 with no encoder preamble, for theStreamWriteran export streams through, so the BOM is written once, byWriteByteOrderMark, and nowhere else (CsvWriter.cs:64-66).WriteByteOrderMark(CsvWriter.cs:85-90): throws on a null writer, then writes the BOM; called once before the header row.WriteHeader(CsvWriter.cs:97-113): writes each column name, comma-separated, escaped exactly like a data field (a null name becomes empty,CsvWriter.cs:109), thenLineEnding.WriteRow(CsvWriter.cs:121-137): the same loop overobject?cells, each passed throughFormatCellfirst (CsvWriter.cs:133).FormatCell(CsvWriter.cs:144-153):nullwrites empty, astringverbatim, aboolas lowercasetrue/falseto match the JSON the sibling endpoints emit,DateTimeandDateTimeOffsetin ISO 8601 round-trip"O", any otherIFormattablewith the invariant culture, and everything else falls toFormatObject.FormatObject(CsvWriter.cs:162-168):Moneywrites its amount and currency code ("49.99 USD", or the amount alone when the code is empty,CsvWriter.cs:176-180),Currencywrites its code, a type with no value text writes as compact JSON withJsonSerializerOptions.Web(CsvWriter.cs:166), and anything else writesConvert.ToStringwith the invariant culture.HasNoValueText(CsvWriter.cs:190-198): true when the publicToStringis inherited fromobjectorValueTypeor is compiler-generated (a record'sName { Member = ... }text), cached per type in aConcurrentDictionaryso the reflection runs once per type (CsvWriter.cs:77).WriteField(CsvWriter.cs:206-217): quotes a field and doubles its embedded quotes only when it holds a comma, quote, CR or LF, found with theMustQuotesearch values (CsvWriter.cs:74).
- Why it's built this way: writing into a caller-supplied
TextWriterone row at a time lets the generic export endpoint hold at most one page of rendered CSV in memory, while a report that builds a whole file can write into aStringWriter(CsvWriter.cs:13-18). The"O"date format is chosen over the sortable"s"because it keeps sub-second precision and the offset, so a parsed value equals the one exported (CsvWriter.cs:31-32). - Where it's used:
EntityCsvExporter<TEntityDTO>opens its per-pageStreamWriterwithUtf8NoPreamble(MMCA.Common/Source/Presentation/MMCA.Common.API/Export/EntityCsvExporter.cs:136), writes the BOM and header on the first page (EntityCsvExporter.cs:162-163), each data row (EntityCsvExporter.cs:273), and a one-cell incomplete or truncation marker row (EntityCsvExporter.cs:152,195). Its remarks rely on this writer's value forms to keep value-object columns in an export (EntityCsvExporter.cs:27-30). No ADC or Store source calls it. - Caveats / not-in-source: the writer deliberately does not prefix fields a spreadsheet would evaluate as formulas (a leading
=,+,-or@), because that would corrupt legitimate negative numbers; a host that opens untrusted exports in a spreadsheet should import them as text (CsvWriter.cs:39-42). The comma delimiter is fixed, as inCsvReader.
⬅ Index • Index • Domain Building Blocks (Entities, Value Objects, Aggregates) ➡