Repository navigation
Addressed Build Warnings from Code Analysis - #115
Merged
Merged
Conversation
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.
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).
9 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
Contract.Requires<T>refactor belowContract.Requires<T>(T, …)returnsT(97d4978)void Requires(object?, …)[AllowNull]+[NotNull]so existing unconstrained call sites continue to bind to the methodswitchstatements, where practical (43d3e41)fieldkeyword for properties with a backing field used only in their own getter/setter (d6eb2a4)[CallerArgumentExpression]onContract.Requires()(3708347), allows capturing the failed expressioninternalclasses that have no subclasses (aeadead)DateTimeto UTC throughoutVersioncomparisons (9957ed6)Code Analysis
Resolved
TypepropertystaticContainsKey()+ indexer withTryGetValue()privatereturn types to concrete implementationsAny()withCount == 0on pre-counted collectionscharcharoverloads forStartsWith/EndsWithchecksTypeoverloadsc0e5516, a30a70b
InvalidOperationExceptionif no public constructor9daad5e, a22c5fe, 4e1c623, 2862b16
[Serializable]/ISerializable(binary serialization obsolete[MemberData]ConfigureAwait(false)(now a warning in xUnit 3.x)TestContext.Current.CancellationTokenContains()for collection membership assertionsSuppressed
TopicMappingServiceinternal-only types accessed via reflectionTopicMappingServiceinjectionCollectionsuffix on non-collectionsTopicMappingServiceInfrastructure
GitVersion.ymlbranch configurationsBug Fixes
DateTimenull check inRollback()(e7d7451)Contract.Requires()was boxing a non-nullableDateTimestruct and checking it for null, which can never be trueContract.Requires<T>test case (ecb7d56)nullwhere a typed reference-type null is now expected>/<to>=/<=to prevent failures in batch runs (92d5b8b)Cleanup