Skip to content

Addressed Build Warnings from Code Analysis - #115

Merged
JeremyCaney merged 68 commits into
developfrom
cleanup/code-analysis
Jul 3, 2026
Merged

JeremyCaney merged 68 commits into
developfrom
cleanup/code-analysis

Conversation

@JeremyCaney

Copy link
Copy Markdown
Member

As a follow-up to the platform and language modernization (#114), this applies the associated code analysis cleanup, working through the full backlog of static analysis warnings across CS, CA, and xUnit diagnostic categories. IN addition, this adopts several C# modernization patterns now unlocked by C# 14 / .NET 8 and upgrades GitVersion to its current 6.x release, which had been deferred from the initial update.

Modernization

  • File-scoped namespaces throughout (412d822)
    • This is primarily a whitespace change with adjusted flowerbox padding
  • Primary constructors for DI-heavy classes (6010756), enabled by the Contract.Requires<T> refactor below
  • Contract.Requires<T>(T, …) returns T (97d4978)
    • The new generic, value-returning overload replaces void Requires(object?, …)
    • Enables use in field initializers and primary constructors
    • Uses [AllowNull] + [NotNull] so existing unconstrained call sites continue to bind to the method
  • Pattern-matched switch statements, where practical (43d3e41)
  • Collection expressions (129c2b6); resolves IDE0300, IDE0301, and IDE0305
  • Source-generated regex (921927d); replaces runtime-compiled instances
  • C# 14 field keyword for properties with a backing field used only in their own getter/setter (d6eb2a4)
  • [CallerArgumentExpression] on Contract.Requires() (3708347), allows capturing the failed expression
  • Sealed internal classes that have no subclasses (aeadead)
  • Normalized DateTime to UTC throughout Version comparisons (9957ed6)

Code Analysis

Resolved

Code Description Commits
CA1019 Removed writable setter from attribute Type property 854d383
CA1822 Marked private methods as static 2021d9e, 771e424, 2f81522
CA1851 Materialized queries to avoid multiple enumerations 6a41f51, 7983ac1
CA1854 Replaced ContainsKey() + indexer with TryGetValue() 8a1c5fe
CA1859 Changed private return types to concrete implementations 94e7bf2, d9865f2
CA1860 Replaced Any() with Count == 0 on pre-counted collections 322e99b
CA1861 Eliminated repeated array allocations via char c488b43, ecf7c7e
CA1865 Used char overloads for StartsWith/EndsWith checks c257254, 21d474f, 818fbdc
CA2263 Preferred generic overloads over Type overloads 5b7bb95, 7c618de
CS0618 Suppressed intentional use of obsolete APIs, pending removal 1e53ad1
CS8600 Aligned cast with the nullability contract of the target delegate 9e0e4d6
CS8601 Fixed type mismatches in nullable assignments db08594
CS8602 Resolved null references via type guards, postconditions 744ce53, 4699df3, 2989976,
c0e5516, a30a70b
CS8603 Throw InvalidOperationException if no public constructor d1d0c61
CS8604 Addressed null argument via filtering, casts, &c. caa6bc3, 171b7c1, ffaf6f5,
9daad5e, a22c5fe, 4e1c623, 2862b16
CS8622 Aligned delegate parameter nullability with the referenced signature 085c670
SYSLIB0051 Removed [Serializable] / ISerializable (binary serialization obsolete 4684460, 0f8d134
xUnit1012 Fixed nullability mismatch in [MemberData] 4031d2a
xUnit1030 Removed ConfigureAwait(false) (now a warning in xUnit 3.x) 760494f
xUnit1051 Switched to TestContext.Current.CancellationToken bbd3cdb
xUnit2017 Used Contains() for collection membership assertions 5a0d6b6

Suppressed

Code Description Rationale Commits
CA1024 Methods that resemble properties Method signals non-trivial cost 7eb25ba, b23e51c, 50c681b
CA1032 Missing standard exception constructors Intentional in test fixtures 08f5141
CA1034 Nested types Single-use test fixtures must be public for reflection 6a4df66
CA1044 Write-only properties Testing compatibility in TopicMappingService 4c1484e
CA1515 internal-only types accessed via reflection Required by ASP.NET Core or TopicMappingService injection 4100760, 7a9feee
CA1711 Collection suffix on non-collections xUnit overloads this term for test fixture classes eb47536
CA1859 Use concrete type over interface Interface typing is intentional for DI contracts 7ba2392
CA2227 Writable collection properties Testing write-compatibility in TopicMappingService 8529f50
(events) Unused event handlers Events are obsolete and will be removed 0ace7e1

Infrastructure

  • Upgraded GitVersion from 5.11.1 to 6.7.0 (c7ad458)
    • Required reconfiguring the GitVersion.yml branch configurations

Bug Fixes

  • DateTime null check in Rollback() (e7d7451)
    • Contract.Requires() was boxing a non-nullable DateTime struct and checking it for null, which can never be true
    • Replaced with a meaningful default-value check
  • Contract.Requires<T> test case (ecb7d56)
    • Test passed a raw null where a typed reference-type null is now expected
    • Corrected to match real-world usage
  • Flakey timestamp test: Switched > / < to >= / <= to prevent failures in batch runs (92d5b8b)

Cleanup

  • Fixed UTF-8 encoding corruption on em-dash and special characters in inline comments (6a8f392, 1a1f580)

This ensures that the signature that the handler is being case to agrees with the delegate is represents.
This would only occur if an assembly were dynamically compiled at runtime. That's not something we currently expect, but there's no reason not to support those scenarios. In that case, such assemblies would still be included.
In this case, the scenario should never exist that the `DeclaringType` is null, so we can assure the compiler of that.
In the case that we're trying to call a public getter or setting and one doesn't exist, this would previously throw an error due to a null dereference. This makes that more explicit by detecting that scenario and throwing an error in that case.
There's a previous guard that ensures that there will always be at least one topic in this branch, so we should check for `Last()` not `LastOrDefault()`, since the latter presumes a null possibility.
If there isn't, in fact, a public constructor, then that's not something we will be able to instantiate and, therefore, represents a configuration error that should be reported. In that case, throw a `InvalidOperationException`.
We already know this exists as expected by this point, but the `as` creates ambiguity for the compiler, where as using an explicit case doesn't.
While this is an unexpected issue and would normally represent a configuration problem, it's possible (with e.g., dynamically generated methods) that a parameter won't have a name. In that case, we throw a `InvalidOperationException` to notify the caller of the configuration error.
In this case, the parameter nullability mismatched the delegate it was referencing.
This prevents the query from being executed each time during the loop, which is an obvious performance issue.

While I was at it, I removed an unnecessary null check, since the `OfType<T>()` used to define `filterByAttributes` will never return null (though it may return an empty set).
This is a private method whose single internal caller converts it to a string. As a result, we can just return the string itself, instead of requiring the caller to cast it from an object to a string.
`Split()` allocates the array for each occurrence. We could move it to a static field. But we can instead just pass a `char` instead of a `char` array, which is (now?) accepted, and avoids this issue entirely.
Since we're checking for a single character, pass a `char` instead of a `string`.
We deliberately use `GetUniqueKey()` instead of `UniqueKey` because this is doing dynamic processing, and a method signifies that. Thus, I'm suppressing the property with an explanation.
The `[serializable]` attribute was marked as obsolete in .NET 8 due to a long-standing security issue (SYSLIB0051). We were only using those because prior code analysis suggested it, not because we were actively supporting binary serialization. These objects can still be serialized to e.g., JSON. I'm happy to simplify these!!
Since this is private, it doesn't impact the public interface, and is thus an easy decision.
While this is normally a valid warning, since attributes are meant to be compile-time constants, the public setter is required in this case because we sometime call it via a named property since there isn't a constructor that accepts both. We could just add a constructor that accepts both, but that's only a scenario required for the test cases, so it doesn't make sense to extend the public interface otherwise.
This is a major version update. It required changing the `mode` keys used in our `GitVersion.yml`, as they were given new meanings and options; overriding each of the built-in branch configurations (e.g., `release`, `feature`, `hotfix`) as well as setting the `unknown` mode; and establishing an explicit `regex` for `master`, apparently due to this being an override of the default configuration. I also verified that the `Directory.Build.props` (e.g., `UseFullSemVerForNuGet`) remain honored, since this apparently changed how those are evaluated.

Note that I don't fully understand why 6.x now requires the `regex`, but without it it throws an "Branch configuration 'master' is missing required configuration 'regex'" error.

It's out-of-the-box definition for `master` checks `^master$|^main$`, and I maintained that both for consistency, but also just to ensure there aren't any surprises if/when we migrate from `master` to `main` (an unplanned but likely eventuality).

I'd like to revisit these to determine if they remain the best configuration, especially compared to the defaults (which I'd expect to be well established), but for now this maintains consistency with the previous configuration. That said, our use of `ContinuousDelivery` for non-deployed branches is ensures that the branch name and commit count are included in the version, which allows us to easily push test packages without much fuss.
This takes advantage of newer capabilities to ensure we're using compiled regexes instead of needing to recompile them on each request at runtime.
My prior logic would often fail when ran as a batch. By migrating `>` and `<` to `>=` and `<=` this _should_ fix the issue.
These will be removed in the future as they're obsolete. That said, if they weren't obsolete, it would be okay for them to remain unused within our codebase as they're intended for external extensibility.
This was somehow missed in the previous implementation (4684460), likely because it was being buried under the tests, and not part of the `OnTopic.All` build.
These are just due to disagreements between the nullability assigned and what the code does. This fixes that disagreement. This also addresses a CS8618 warning as well.
This is a legitimate case where the variable (`header`) could potentially be `null`, and it's easy to safeguard it.
This resolves IDE0300, IDE0301, and IDE0305.
Special characters such as an em-dash and "ç" kept getting corrupted by `dotnet format`; this fixes the encoding of them to be true UTF-8 so that it shouldn't trip over them in the future.
In the case of these tests, the object had a null-forgiving operator on a variable that had already been asserted to be `NotNull`. With our upgraded test harness (d1ba9f8), this appears to no longer be necessary, and the original `NotNull()` assertion now tells the compiler that, yes, in fact, the variable is not null. That's a welcome cleanup to this code, which wouldn't have required something like this under our normal `Contract` validation.
Having the two calls to `GetValue()` was causing problems with the compiler's null check since the first instance was entangled within the LINQ syntax. The `< 256` excludes nulls, but the second call doesn't get that. This doesn't address that directly, but at least defines the call once via a variable, then does a null check on the second reference.
If a reference to another topic is null, we shouldn't pass null text to `XText()`, which is an error, but bypass the entire reference element. This can be done using a LINQ clause to filter out nulls.

As in the previous update (9daad5e), the compiler isn't smart enough to understand null checks within LINQ queries, so we must explicitly reassure it that, in fact, `reference.Value` is not null here.
Identified some additional UTF-8 encoding issues that were missed in the first round (6a8f392).
This was previously required by xunit v2. With the upgrade to v3 (d1ba9f8) this is apparently no longer needed—and indeed now throws a warning if it's present. Easy fix, and clear code!
For properties where we were using a private backing field but didn't require e.g., external access to that field (i.e., it's only used in the property's own getter and setter) prefer the use of the new `field` keyword introduced by C# 14.
While it generally makes sense to type variables to their concrete implementation and not their interface, these are all cases where we're either defining variables for use in dependency injection, or where we're specifically testing a target interface that supports dependency injection via its concrete types. Regardless, the only contract that matters and is relevant in these cases is the interface itself. That may have a (slight) performance hit, but it's both safer and clearer to type these as the interface they represent in the code, than some concrete type that is somewhat incidental to the purpose of the code. As such, I'm globally suppressing this warning.

(Technically, this only affected a few assemblies, but as we're so deliberate with how we handle interfaces, I'm confortable adding this at the solution level.)
The test expected an `object`, but one of the test cases passed a `null`.
This picks up an item previously missed (5b7bb95).
This allows the error messages to automatically capture the expression text that was checked. This includes updating the `ContractTest` and explicitly checking the exception message.
"Calls accepting `CancellationToken` should use `TestContext.Current.CancellationToken`"
The initial build report didn't surface these—a recurring pattern!—and so I'm suppressing these in additional assemblies as well. See 4100760.

Unlike the original warning, which was for view models within a test assembly, this affects classes within ASP.NET Core hosts. That included warnings on view models, yes, but also things like controllers, which are required to be public by ASP.NET Core.
This picks up yet another case missed in the initial build reports (7eb25ba, b23e51c). For `OnTopic.Tests`, I chose to globally suppress the warning, since it's just a test library, and there are a number of false positive warnings within it.
Previously, we were relying on an unspoken assumption that `Version` would be the same timezone across the application. In cases where we defined the `DateTime` as part of centralized APIs, we typically defined them as UTC. But in cases where we accepted a `DateTime` via a public interface, we just assumed it would be in the same timezone.

This formalizes that by either explicitly marking dates as UTC, or converting them to UTC if they have a timezone declared.

In practice, we don't anticipate this to be an issue since, by convention, most servers are set to UTC. To help avoid any potential bugs should that expectation not be maintained for an implementer, however, this at least begins to formalize this.

(A stricter, safer version would require that callers provide a `DateTime` with a timezone defined. But as this is an edge case, that's not an immediate priority.)
These classes are all `internal` and have no derivations. Each may need to be extended at some point, but that should be a conscious choice. As such, we'll mark them as `sealed` for now and may optionally reopen them in the future, should we find a need to.
Where practical, prefer `switch` statements with pattern-matching over either normal `switch` statements or, especially, `if`/`then` dispatchers.

Only about half of the candidates identified were a good match for this; some were possible, but resulted in less readable, more complex logic due to e.g., mixed types or inconsistent logic better suited for an `if`/`then` set.
Replaces the `void Requires(object?, ...)` overload with a generic, value-returning `Requires<T>(T, ...)`. This enables validation in field initializers, which is a prerequisite for primary constructors. Uses `[AllowNull]` rather than `T?`/`where T : class`
so unconstrained type parameters at existing call sites continue to bind. `[NotNull]` also preserves the postcondition contract that callers rely on for null  analysis.
Fixed a latent bug in `TopicRepository.Rollback`, where `Contract.Requires(version, ...)` on a non-nullable `DateTime` struct was boxing a value that can never be null. Replaced with a meaningful default-value check.
With dependency injection, primary constructors are especially attractive as they elevate the documentation for the dependencies to the class level, while in conjunction with the recent updates to `Contract.Requires()` (97d4978), simplify the validation syntax a bit.
While a broken test case is a warning sign of a breaking change—and it indeed is (97d4978)—the break is that a null primitive can't be passed, but a _typed_ null can be. When validating reference types, that's what we actually expect. The test took a shortcut, which we wouldn't anticipate in real code; this fixes that.
This is a massive change in terms of the commit difference, but primarily just affects whitespace (by reducing the indent level two spaces) and flowerboxes (by padding them to compensate for those two spaces).
@JeremyCaney JeremyCaney added this to the OnTopic 6.0.0 milestone Jul 3, 2026
@JeremyCaney JeremyCaney self-assigned this Jul 3, 2026
@JeremyCaney JeremyCaney added Severity 1: Minor Priority: 3 Type: Improvement Improves the functionality or interface of an existing feature. Status 5: Complete Task is considered complete, and ready for deployment. labels Jul 3, 2026
@JeremyCaney
JeremyCaney merged commit 66a6407 into develop Jul 3, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Priority: 3 Severity 1: Minor Status 5: Complete Task is considered complete, and ready for deployment. Type: Improvement Improves the functionality or interface of an existing feature.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant