Skip to content

Enable nullable reference types - #1131

Open
KrzysztofPajak wants to merge 30 commits into
developfrom
feature/nullable-reference-types
Open

KrzysztofPajak wants to merge 30 commits into
developfrom
feature/nullable-reference-types

Conversation

@KrzysztofPajak

@KrzysztofPajak KrzysztofPajak commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Type: feature

Issue

None of the projects had nullable reference types enabled, so the compiler could not tell which values may be null. Null mistakes showed up only at runtime, as NullReferenceExceptions in places far from their cause.

Solution

Nullable reference types are enabled, with nullable warnings as errors, in every project except the plugins (src/Plugins) and the test projects (src/Tests), which come in a later step. Nothing is silenced: no NoWarn, no #pragma, no #nullable disable, no <Nullable>warnings</Nullable>. A ! is used only with a comment that names the invariant the compiler cannot see.

The conventions are written down in .ai/knowledge/dotnet.md (section Nullable Reference Types). In short:

  • Domain strings are string?. A field that every validator requires and every creation site sets is string X { get; set; } = null!. That includes the references every record has: the product of an order item, cart item or review, the customer of a review, recurring payment or merchandise return, the order of a shipment, the category of a product mapping and so on. Order.CustomerId stays nullable, since the order number reservation inserts an order without one. Entities do not use required: System.Text.Json would enforce it.
  • A mediator request property that every creation site sets is required. A handler that can return null says so in the request (IRequest<X?>); IRequestHandler.Handle itself is never annotated.
  • A lookup by id takes string? and returns T?.
  • IContextAccessor.WorkContext / StoreContext are non-null and throw when no request context is set. Code that may run outside a request (the installer, background tasks, audit, logging) reads CurrentWorkContext / CurrentStoreContext.
  • Admin loaders return Access<T> (entity or denial, exactly one set). The vendor and store panels read their vendor and store through PanelVendor() / PanelStoreId(), which throw instead of comparing against null.
  • SuppressImplicitRequiredAttributeForNonNullableReferenceTypes is on, so validation stays in FluentValidation.

One commit per layer (Domain, Data, Infrastructure, Business, modules, Web.Common, AdminShared, the panels, Grand.Web), then the fixes the testing found.

Behaviour changes

  • Explicit exceptions instead of later NREs: where develop dereferenced a null a line later, the code now throws a named exception (ArgumentException, GrandException, InvalidOperationException). Every one was checked against develop: none fires where develop worked.
  • No context: IContextAccessor.WorkContext / StoreContext throw when nothing set them. StoreContextSetter throws when the database has no store at all; ContextMiddleware already skips it before installation.
  • Web API: a PUT of a missing record answers 404 and a PUT without an id 400, after the permission check. On develop most answered 500 and Picture answered 200 without saving anything. The update handlers return null for a missing record, so the record is read once. GET and DELETE of a missing customer answer 404 instead of 500.
  • Contracts that plugins implement: they now say what plugins actually return.
    • IPaymentProvider.InitPaymentTransaction / SavePaymentInfo return PaymentTransaction?.
    • IShippingRateCalculationProvider.ShipmentTracker is IShipmentTracker?.
    • IShippingMethodService.GetAllShippingMethods takes string? filterByCountryId.
  • Admin, campaign test e-mail: an empty test address now shows an error. Develop reported success and queued an e-mail with no recipient.
  • Sample data: the sample affiliate gets a name, which its validator requires.
  • EU VAT: an address whose country no longer exists gives no VAT exemption. Develop threw a NullReferenceException there.
  • Downloads: a download set to use a URL but with an empty URL answers "Download data is not available any more." and does not use up one of the allowed downloads.
  • Checkout: the shipping form partial answers with no form for an empty or unreadable shipping option; develop answered 500.
  • Admin, product mappings: a product-category, product-collection or product-attribute mapping posted without its category, collection or attribute is refused with an error. Develop stored the mapping with none.
  • Password change by e-mail: an e-mail with no customer throws GrandException (develop threw ArgumentNullException a line later).

Breaking changes

  • Nullable annotations on public signatures change nothing for code built without nullable (all plugins today). Code that enables nullable sees them.
  • required members: about 114 mediator request properties in Grand.Business.Core are required. The compiler enforces required whatever the nullable setting, so code that creates one of these requests must set those members in its object initializer, or it fails with CS9035. Every plugin in this repository already does. A third-party plugin that creates such a request and sets a member later, or not at all, has to be updated.

Testing

  • Mapper guard: the compiler cannot see Grand.Mapping copy a null. NullIntoNotNullMappingTests lists every profile member that maps a nullable source onto a Domain member declared not null (108 today), each with what refuses the null: a validator rule, a service check or an import condition. A new unguarded mapping fails the test.
  • Every project builds with nullable warnings as errors. All 23 test projects pass; some (Customers, Marketing, Messages) fail randomly on a full parallel run and pass alone, as on develop.
  • End to end on a fresh install with sample data, compared where it matters against develop built from the merge base, with the same scripts and data:
    • Coverage: the installer; the storefront as a guest and as a customer; checkout with every shipping method, pickup in store and the payment methods; the account pages, order details, PDFs and returns; the admin, store and vendor panels (order handling end to end, shipments, payments, refunds, popups, scheduled tasks, impersonation).
    • Form fuzzing: about 4,700 submissions of every POST form in all areas with empty, spaces-only, special, very long, negative and non-numeric input. No server error comes from this branch.
    • Click sequences: about 150 steps (empty cart, odd quantities, every catalog product without its attributes, checkout steps skipped, double Confirm, Back, currency change mid-checkout, registration and sign-in edge cases). Same answers as develop on every step.
    • Deleted references: records deleted while others point at them, then every page that shows them. Same as develop.
    • CRUD round trips: every admin record type, every product type (about 80 fields each) and the settings pages, each field compared after create and after edit.
    • Web API and SCIM: 218 and 48 checks. Every difference from develop is in favour of this branch.

Left for later

  • Plugins and test projects (separate step).
  • KnowledgebaseArticleModelValidator compares a Task with null, so its category rule always passes. Found here, left unchanged.

Bugs the testing found that develop already had are fixed in separate PRs: #1124, #1125, #1126, #1127, #1128, #1129, #1130.

support added 21 commits November 25, 2026 20:33
MVC turns every non-nullable reference property of a nullable-enabled
project into an implicit [Required]. GrandNode validates through
FluentValidation, so the implicit attribute would reject forms that
pass today.
Entity properties without a default are nullable: a document read from
MongoDB may lack the field, so the type now says what the code already
had to cope with. ParentEntity.Id stays non-null - its setter replaces
null with a new identifier.

Where a comparison dereferenced such a property it now uses
string.Equals or ?., which gives the same result for every non-null
value instead of throwing on null.
IRepository.GetById, GetByIdAsync, GetOneAsync and FirstOrDefaultAsync
return T? - each answers null when nothing matches.

A repository created without a connection string (before installation)
has no collection. Collection and Database now throw an
InvalidOperationException naming the repository instead of a
NullReferenceException at the first call.

DataSettingsManager.LoadSettings never returns null: a settings file
holding the literal "null" reads as empty settings, as a missing file
already did.
Configuration classes are nullable where appsettings may leave a value
out. Members that are set by an initialization step (AutoMapperConfig,
PluginManager.StateStore, the repository collection) throw an
InvalidOperationException naming what was not set instead of a
NullReferenceException.

ICacheBase.GetAsync returns the T its acquire returns: a hit is always a
value this class stored from that acquire, the one invariant marked
with ! in MemoryCacheBase.

The audit snapshots before and after are nullable throughout - null is
an insert or a delete - and a change without a path is skipped where
it used to throw inside the catch-all.
The service contracts plugins build against. Result types created with
a null member (ExternalAuthResult, OidcLoginResult, CatalogAccess, ...)
say so in their constructors; CatalogAccess.ShowHidden tells the
compiler that a catalog access limited to a customer has one.

ISettingService.GetSettingByKey returns T? - the default value when
the setting is missing. GenerateSlug and EnsureMaximumLength return
null only for null input.
143 string fields are required by evidence in the code, and are declared
"string X { get; set; } = null!" - the one ! at the declaration states
the requirement once instead of at every use:

- 100 fields every FluentValidation validator of their model or DTO
  requires unconditionally (a rule inside an if on a setting, or with
  When/Unless, does not count), never assigned null in code;
- 43 keys every creation site in code sets from an entity Id or a
  literal (InventoryJournal.ProductId, BlogComment.BlogPostId, ...).

Left nullable although a validator requires them: Store.Shortcut
(code falls back to Name), Page.SystemName (a page without one is
handled), UserField.Value (tested for empty), QueuedEmail.From/To and
Picture.MimeType (created in code from several sources), and
KnowledgebaseArticle.ParentCategoryId (ITreeNode shares it with
KnowledgebaseCategory, where a root has none). Order.CustomerId and
StoreId stay nullable: the order number reservation inserts an order
without them.
93 properties of the commands and queries in Grand.Business.Core are
"required" and not nullable: every creation site in code sets them and
no code tests them for null, so the compiler now holds every new caller
to it. Objects and ids only - notes, references and who-did-it strings
stay optional.

The guards in the handlers stay, for callers outside nullable checking.
The tests of those guards pass null! - the one place a null is handed
to a not-nullable member on purpose.
All nine Grand.Business.* projects build with no nullable warnings.

- Signatures follow what the code does: a parameter becomes nullable only
  where the body already copes with null (IsNullOrEmpty, ==, ?.), e.g.
  store, warehouse and language ids, the price formatter's currency.
- Inputs every caller sets are required: PlaceOrderContainer, CheckoutClaim,
  ReturnShippingRequest/Option, CampaignRecipient, RefundPaymentRequest,
  InsertContactUsCommand and others.
- A handler that returns null declares it in its request (IRequest<X?>);
  IRequestHandler.Handle keeps Task<TResponse>.
- Where a lookup could only fail on a misconfigured or deleted record, an
  explicit GrandException replaces the NullReferenceException that would
  have followed (primary currency, store, language, e-mail account, the
  products of a cart being ordered).
- A deleted product, tag or slug no longer breaks stock adjustment, tag
  counts or blog post deletion; it is skipped.
- The country report keeps grouping orders without a billing address under
  no country; the Mongo driver translates the guard to $cond.
Api, Scim, ScheduledTasks join Installer and Migration, which had nullable
enabled already; all five build with no nullable warnings.

- API request models: the inputs every caller sets are required; DTO fields
  stay nullable, as a request may leave them out. The login models' e-mail
  and password, which the validators always require, are not null.
- Controllers look an entity up once and answer 404 when it is null,
  instead of Any() then FirstOrDefault()!: one query less, no forgiving
  operator.
- Update handlers throw an ArgumentException naming the missing entity
  where a NullReferenceException followed; ids of request DTOs passed on
  to services are guarded.
- Service lookups by id that already cope with null take a nullable id
  (GetBrandById, GetPictureById, GetCustomerByEmail, ...).
- SCIM: results are read through patterns that carry the resource
  (Outcome Ok with its User/Group); ReadBody returns the body or null.
- JWT: a missing secret key throws the configuration error of the refresh
  token service; empty claim values were already skipped.
- Scheduled tasks: a queued e-mail without account, sender or recipient
  counts as a failed try with a message saying so; an auction whose
  bidder is gone is skipped with a warning.
Both projects build with no nullable warnings.

- IContextAccessor.WorkContext and StoreContext stay not null: the getter
  throws when no context is set, as outside a request. Code that also runs
  without one (settings resolved by the container, the culture middleware,
  the request translation and permission services, the admin component
  texts) reads the new nullable CurrentWorkContext/CurrentStoreContext and
  behaves as before.
- IWorkContext: only CurrentVendor, StoreManager and
  OriginalCustomerIfImpersonated are nullable; the work context is built
  in one go, in the same order. No store, language or currency throws
  "could not be loaded", as the language and currency already did.
- Tag helpers: ViewContext and the attributes an element is matched on are
  set by the framework (= null!, with the reason next to each).
- The MVC helpers copied for the admin templates follow the annotations of
  the originals (template and field names nullable, the buffered writer's
  inner writer known once it stops buffering).
- Lookups that cope with null take it (permission check of a missing
  customer, slug and active-slug lookups, audit actor fields); missing
  configuration of an enabled feature (Redis, Azure key vault) throws a
  message naming the setting.
- The specification filter looks its option up once instead of four times
  with a forgiving operator.
- Access<T> replaces the (entity, denied) tuples of the panel loaders, so a
  denied load can no longer be read as an entity; the 14 `return denied!`
  are gone
- data scope checks state the null check the scope makes itself
- search filters (SearchOrders, SearchProducts, GetAllCustomers, ...) take
  string? and pass "" on, as the queries below expect
- ids posted by popups and grids get ArgumentException.ThrowIfNullOrEmpty
  where the controller has already loaded the entity by that id
- view-only collections and sub-models default to empty instead of null
- PanelVendor() names the vendor panel's invariant (AuthorizeVendor lets in
  only a customer with a vendor); a missing vendor never widens a scope
- an order without a billing address shows no billing card instead of
  failing; a deleted picture, product or tag is skipped where it was
  dereferenced
- PanelVendor() and PanelStoreId() name what AuthorizeVendor and
  AuthorizeStore guarantee; a missing vendor or staff store throws instead
  of widening a check (null == null)
- grid updates that load by the posted id throw "No ... found with the
  specified id" instead of failing on null, as the other actions do
- SiteMap.Load() returns the root node the menus draw
- AdminStoreService.GetActiveStore() returns "" (all stores) when there is
  no store at all, the scope it already gives for an empty choice
- SCIM mapping passes "" for no store and no vendor, which the service reads
  the same as before
- a cart line of a deleted product is not listed; a picture kept on disk is
  skipped by the conversion
- restriction grids read their nested dictionaries with TryGetValue
- tests: two mapping snapshots now show the empty condition model, the SCIM
  and active-store tests expect "" instead of null
- storefront mediator requests: 400+ properties made required where every
  creation site sets them and nothing tests them for null (same evidence
  as for Business); the rest stay nullable
- handlers that really return null declare it (IRequest<X?>): user
  agreement, page block, sub-account, order approval, base price, return
  note, subscription activation, product attribute
- mappers that answer a null entity with null say so with
  [return: NotNullIfNotNull]; IsDownloadAllowed / CustomerSendsBack /
  CustomerPrintsDocument / CustomerEntersTrackingNumber carry NotNullWhen
- fields the validators require get ArgumentException.ThrowIfNullOrEmpty
  in the handler or action that uses them
- a related/similar/recommended list of a deleted product is empty, a
  return or line of a deleted product is skipped, a download without data
  answers "Download data is not available any more."
- view models: sub-models nobody null-checks default to new(); brand and
  vendor on the product page are nullable, as the views already treated
  them
- tests: two external-registration tests post the password the validator
  asks for; required members get placeholder values
- every project outside src/Plugins and src/Tests sets Nullable and
  WarningsAsErrors=nullable in its csproj; Grand.SharedUIResources joins
  them (three editor templates read their ViewData flags with patterns)
- the 87 #nullable enable directives are gone: the project setting covers
  those files
- .ai/knowledge/dotnet.md describes the conventions; it said nullable was
  enabled everywhere, which it was not
- plugins and test projects stay as they were, for a later step
It said nullable was enabled everywhere; plugins and tests are not yet. The
conventions the rollout settled on are listed.
… have none

The audit filter, the audit recorder and the logging middleware also run for the
installer, before ContextMiddleware has a store to build a work context for. Reading
IContextAccessor.WorkContext there threw, so /install answered 500.
The affiliate validator requires a name and Affiliate.Name is declared non-null, but
the sample data created one without it, so saving it in the admin failed validation.
The shipped payment methods return no payment transaction from InitPaymentTransaction
and SavePaymentInfo, the shipping methods have no shipment tracker, and a shipping
provider passes the country of an address that may have none. The checkout and the
shipment pages already handled each null; the contracts now say so.
The customer tab grids loaded the customer only to check access and kept it in a
discard. The comment on a payment's other subscription ending sits above the check
it explains again.
The update handlers now refuse a record they cannot load, so a PUT naming no record or a
missing one ended in a 500; some of them used to report success without saving anything.
The PUT actions check the key and the record first, as PATCH and DELETE already did, and
answer 400 or 404.
Copilot AI balanced review requested due to automatic review settings November 26, 2026 20:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

support added 7 commits November 26, 2026 22:39
An address whose country was deleted counted as outside the VAT zone, so the order was
placed without VAT. A missing country now gives no exemption.
The download count of an order item was raised before the empty-URL check, so a click
that delivered nothing still counted. The check comes first now, and the repeated
URL redirect is one helper per controller.
The shipping form partial split the posted option without checking it, so an empty
option or one without a provider part threw. It now answers with no form. Saving the
shipping method validates the form with the provider it has already parsed, so the
empty-option check is made once.
A request naming no customer threw ArgumentNullException for the request, which reads
as a null-argument bug. It throws GrandException instead.
The PUT actions loaded the record to answer 404 and the update handler loaded it again.
The handlers now return null for a missing record, which the actions answer with 404,
and the permission check comes before the 400 for a missing key.
Access<T>.TryGet replaces the load / IsDenied / Entity sequence repeated in the panel
controllers, and the Deconstruct only the tests used.
Three places repeated a condition only so the compiler could see a value was not null:
the page ACL, the configured plugin list and the viewable recurring order. Each now
reads from one variable.
support added 2 commits November 27, 2026 05:33
Thirty-three Id fields were left nullable although every creation site sets them: the
product of an order item, cart item, review, bundle item or price, the customer of a
review, recurring payment, payment transaction, merchandise return or loyalty points
entry, the order of a shipment or note, the category and collection of a product
mapping, and the like. They are declared "string X { get; set; } = null!", as the
Domain fields required by evidence already were, and the "?? \"\"", OfType<string>()
and != null checks written only for them are gone. RecurringPayment.InitialOrderId
joins them, and MerchandiseReturnSubmitRequest.CustomerId is required.

Where a value came from a source that may be empty, the source is fixed:
- the place-order, recurring-cycle and approval code take the customer from the
  customer they hold, not from Order.CustomerId, which the order number reservation
  leaves empty;
- an order note and a product price take the id of the record already loaded;
- the admin panels refuse a product-category, product-collection or attribute
  mapping without its category, collection or attribute (develop stored the mapping
  with none), and the add-product popups and bundle grid guard the posted id;
- the Web API mapping handlers guard the id their validator requires.

Left nullable on purpose: Order.CustomerId and StoreId (the order number reservation),
CampaignHistory.CustomerId (a newsletter subscriber may have no account),
Bid.CustomerId (the auction bid of a placed order is written from the order).
Grand.Mapping copies a null string as it is, and the compiler does not see the
expression trees it builds. A new test walks every profile that maps onto a Domain type
and lists each member assigned straight from a nullable source onto a member declared
not null, as MappingCompiler does it: ignored members, MapFrom, collections (null
becomes empty) and nested mappings (null leaves the destination as it is) are left out.

All 108 members found today are listed with what refuses a null: an unconditional
NotEmpty/NotNull in every validator of the source for 100, a parent validator or a
service check for four, and for the import DTOs a Condition plus the import's own rule
that a new record needs a name. A new unguarded mapping fails the test, and so does an
entry that no longer matches. Grand.Mapping exposes its member configuration to the
test project for this.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants