Files
romanettandClaude Opus 5.5 9b034f8291 Enable nullable reference types centrally; migrate all unset and annotations-only projects (#4700)
# Description

Nullable reference types are now enabled once, in `common.props`, and
every project in the repository builds warning-clean with them.

**Configuration**
- `<Nullable>enable</Nullable>` lives in `common.props`. All per-project
`<Nullable>` settings are removed: 178 project files (enable,
annotations, and the `disable` in the three Aot test projects).
- 419 per-file `#nullable enable`/`restore` directives and the 4
`#nullable disable` directives are removed.
- Kept on purpose:
- The 5 `<auto-generated>` schema files (`UANodeSet.cs`, `UA Type
Dictionary.cs`, `OPCBinarySchema.cs`, `SecuredApplication.cs`,
`PInvokeHelper.cs`) keep `#nullable enable`. The compiler ignores the
project setting in generated code, so the directive is required there.
- `tests/Opc.Ua.Interop.LegacyPeer` keeps `disable`. It builds against
the 1.5.378 packages and does not import the repository props.
- `docs/DeveloperGuide.md` and `.github/copilot-instructions.md` now
describe the central setting.

**Migration** (the 43 unset and 13 annotations-only projects, roughly
10k diagnostics)
- **Production code: annotated at the declarations.** Covers
`tools/Opc.Ua.SourceGeneration.Core`, `src/Opc.Ua.Lds.Server` and the
LDS sample.
- Members, parameters and returns are nullable where null actually
flows.
- Null-check helpers carry `[NotNullWhen]` (`IsNull`, `IsValidXmlName`,
`IsMethodTypeDesign`).
- `CoreUtils.Format`, `Utils.Format`, `ITemplateWriter.WriteLine` take
`params object?[]`. `Template.AddReplacement` takes `string?` (rendering
already skips null replacements).
- `IRegisteredServerStore.RegisterAsync` returns
`Task<RegistrationEntry?>`: it returns null when a registration is
removed.
- Dereferences backed by an invariant (for example, the validated model)
use `!`, so runtime behaviour is unchanged.
- **Behavioural changes in production code** (small, deliberate):
- `NodeSetToModelDesign` throws `InvalidOperationException` when the
file is not a NodeSet. Before, it threw a NullReferenceException on the
next line.
- `ModelDesignValidator` starts its lookup tables empty instead of null.
A redundant `if (m_nodes == null) return;` guard is gone.
- **Test code: minimal annotations.**
  - `?` on values that can be null, `!` where the test asserts non-null.
  - `= null!` for fixture members assigned in SetUp.
- `TryGetStructure<T>(out T? x)` where the inferred `T?` broke the
`IEncodeable` constraint.
- A few redundant `== null` checks on structs (`NodeId`, `ArrayOf<T>`)
folded into the adjacent `IsNull`/`Count` checks.

**Notes for reviewers**
- The diff is large (~1,500 files) but almost entirely mechanical: `?`,
`!` and directive removal. The non-annotation changes are listed above.
- Known follow-up, not done here:
`IModelDesign.Namespaces/TargetNamespace/NamespaceUris` stay
non-nullable even though the validator returns null before it loads a
dictionary. Making them nullable would ripple through every generator
call site.

## Related Issues

- Fixes #4439

## Checklist

- [ ] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [ ] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

The "no new warnings" box covers net10.0 and net48: full non-incremental
builds of `UA.slnx`, `tools/SourceGeneration.slnx`,
`tools/MigrationAnalyzer.slnx` and the Aot test projects finished with 0
warnings and 0 errors under the repository's warnings-as-errors
settings. net9.0 and net8.0 also had no nullable diagnostics, but they
were not rebuilt after the final fixes. Tests have not been run locally
yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 08:48:13 +02:00

344 lines
14 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System.Collections.Generic;
using System.Threading.Tasks;
using NUnit.Framework;
using Opc.Ua.Client.AliasNames;
namespace Opc.Ua.Client.Tests.AliasNames
{
/// <summary>
/// Mocked-session unit tests for <see cref="AliasNameClient"/>
/// — covers <c>FindAlias</c> / <c>AddAliasesToCategory</c> /
/// <c>DeleteAliasesFromCategory</c> / <c>ReadLastChange</c> and the
/// hardcoded standard-method-id fast-path used when the client is
/// rooted at the well-known categories.
/// </summary>
[TestFixture]
[Category("AliasNames")]
[Parallelizable]
public class AliasNameClientTests
{
[Test]
public async Task FindAliasAsyncTargetsAliasesFindAliasMethodAsync()
{
var harness = AliasNameSessionHarness.Create();
// Server returns a single AliasNameDataType.
harness.CallHandler = _ =>
{
var entry = new AliasNameDataType
{
AliasName = new QualifiedName("Tag1"),
ReferencedNodes = new[] { new ExpandedNodeId("Target", 2) }
.ToArrayOf()
};
ArrayOf<AliasNameDataType> arr = new[] { entry }.ToArrayOf();
return new CallMethodResult
{
StatusCode = StatusCodes.Good,
OutputArguments =
new[] { Variant.FromStructure(arr) }.ToArrayOf()
};
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
IReadOnlyList<AliasNameDataType> result = await client
.FindAliasAsync("%", referenceTypeFilter: null).ConfigureAwait(false);
Assert.That(harness.CallRequests, Has.Count.EqualTo(1));
Assert.That(harness.CallRequests[0].ObjectId, Is.EqualTo(ObjectIds.Aliases));
Assert.That(harness.CallRequests[0].MethodId,
Is.EqualTo(MethodIds.AliasNameCategoryType_FindAlias),
"Generated AliasNameCategoryTypeClient proxy invokes the " +
"type's method-declaration NodeId; the server resolves it " +
"against the supplied ObjectId.");
Assert.That(harness.CallRequests[0].InputArguments.Count, Is.EqualTo(2));
Assert.That(result, Has.Count.EqualTo(1));
Assert.That(result[0].AliasName.Name, Is.EqualTo("Tag1"));
}
[Test]
public async Task FindAliasAsyncPassesNullFilterAsNodeIdNullAsync()
{
var harness = AliasNameSessionHarness.Create();
CallMethodRequest? captured = null;
harness.CallHandler = req =>
{
captured = req;
return new CallMethodResult
{
StatusCode = StatusCodes.Good,
OutputArguments = new[]
{
Variant.FromStructure(
System.Array.Empty<AliasNameDataType>().ToArrayOf())
}.ToArrayOf()
};
};
var client = AliasNameClient.OpenStandardTopics(harness.Session);
await client.FindAliasAsync("Foo", null).ConfigureAwait(false);
Assert.That(captured, Is.Not.Null);
Assert.That(captured.ObjectId, Is.EqualTo(ObjectIds.Topics));
Assert.That(captured.MethodId,
Is.EqualTo(MethodIds.AliasNameCategoryType_FindAlias));
captured.InputArguments[1].TryGetValue(out NodeId filter);
Assert.That(filter.IsNull, Is.True);
}
[Test]
public async Task ReadLastChangeAsyncTargetsStandardAliasesLastChangeAsync()
{
var harness = AliasNameSessionHarness.Create();
harness.ReadHandler = read =>
{
Assert.That(read.NodeId,
Is.EqualTo(VariableIds.Aliases_LastChange));
return new DataValue(new Variant((uint)42), StatusCodes.Good);
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
uint? lastChange = await client.ReadLastChangeAsync().ConfigureAwait(false);
Assert.That(lastChange, Is.EqualTo((uint?)42));
}
[Test]
public async Task AddAliasesToCategoryAsyncReturnsPerEntryStatusCodesAsync()
{
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = _ =>
{
ArrayOf<StatusCode> codes = new StatusCode[]
{
StatusCodes.Good,
StatusCodes.BadBrowseNameDuplicated
}.ToArrayOf();
return new CallMethodResult
{
StatusCode = StatusCodes.Good,
OutputArguments = new[] { Variant.From(codes) }.ToArrayOf()
};
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
client.Options.AllowVerboseProbe = false;
StatusCode[] result = await client.AddAliasesToCategoryAsync(
[
new AliasNameAddRequest("A",
new ExpandedNodeId("T1", 2),
null, ReferenceTypeIds.AliasFor),
new AliasNameAddRequest("A",
new ExpandedNodeId("T1", 2),
null, ReferenceTypeIds.AliasFor)
]).ConfigureAwait(false);
Assert.That(result, Has.Length.EqualTo(2));
Assert.That(result[0].Code, Is.EqualTo(StatusCodes.Good));
Assert.That(result[1].Code,
Is.EqualTo(StatusCodes.BadBrowseNameDuplicated));
}
[Test]
public void AddAliasesToCategoryRejectsMixedReferenceTypes()
{
var harness = AliasNameSessionHarness.Create();
var client = AliasNameClient.OpenStandardAliases(harness.Session);
Assert.That(async () =>
{
await client.AddAliasesToCategoryAsync(
[
new AliasNameAddRequest("A",
new ExpandedNodeId("T", 2),
null, ReferenceTypeIds.AliasFor),
new AliasNameAddRequest("B",
new ExpandedNodeId("T", 2),
null, ReferenceTypeIds.Organizes)
]).ConfigureAwait(false);
}, Throws.ArgumentException);
}
[Test]
public async Task DeleteAliasesFromCategoryAsyncSendsParallelArraysAsync()
{
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = _ =>
{
ArrayOf<StatusCode> codes =
new StatusCode[] { StatusCodes.Good }.ToArrayOf();
return new CallMethodResult
{
StatusCode = StatusCodes.Good,
OutputArguments = new[] { Variant.From(codes) }.ToArrayOf()
};
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
StatusCode[] result = await client.DeleteAliasesFromCategoryAsync(
[
new AliasNameDeleteRequest("A", new ExpandedNodeId("T", 2))
]).ConfigureAwait(false);
Assert.That(result, Has.Length.EqualTo(1));
Assert.That(harness.CallRequests, Has.Count.EqualTo(1));
Assert.That(harness.CallRequests[0].InputArguments.Count, Is.EqualTo(2));
}
[Test]
public void AddAliasesMapsBadUserAccessDeniedToUnauthorizedAccessException()
{
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = _ => new CallMethodResult
{
StatusCode = StatusCodes.BadUserAccessDenied
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
Assert.That(async () =>
{
await client.AddAliasesToCategoryAsync(
[
new AliasNameAddRequest("A",
new ExpandedNodeId("T", 2),
null, ReferenceTypeIds.AliasFor)
]).ConfigureAwait(false);
}, Throws.TypeOf<System.UnauthorizedAccessException>());
}
[Test]
public async Task EnumerateSubCategoriesAsyncFollowsBrowseContinuationPointsAsync()
{
var harness = AliasNameSessionHarness.Create();
var continuationPoint = new ByteString(new byte[] { 0x01 });
harness.BrowseHandler = description =>
{
Assert.That(description.NodeId, Is.EqualTo(ObjectIds.Aliases));
return new BrowseResult
{
StatusCode = StatusCodes.Good,
ContinuationPoint = continuationPoint,
References = new[]
{
CreateCategoryReference("Page1", "Page1")
}.ToArrayOf()
};
};
harness.BrowseNextHandler = cp =>
{
Assert.That(cp, Is.EqualTo(continuationPoint));
return new BrowseResult
{
StatusCode = StatusCodes.Good,
ContinuationPoint = ByteString.Empty,
References = new[]
{
CreateCategoryReference("Page2", "Page2")
}.ToArrayOf()
};
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
var names = new List<string>();
await foreach (AliasNameSubCategoryInfo info in
client.EnumerateSubCategoriesAsync().ConfigureAwait(false))
{
names.Add(info.BrowseName.Name!);
}
var expectedNames = new[] { "Page1", "Page2" };
Assert.That(names, Is.EqualTo(expectedNames));
Assert.That(harness.BrowseRequests, Has.Count.EqualTo(1));
Assert.That(harness.BrowseNextRequests, Has.Count.EqualTo(1));
static ReferenceDescription CreateCategoryReference(
string browseName,
string nodeId)
{
return new ReferenceDescription
{
NodeId = new ExpandedNodeId(new NodeId(nodeId, 2)),
BrowseName = new QualifiedName(browseName, 2),
DisplayName = new LocalizedText(browseName),
TypeDefinition = ObjectTypeIds.AliasNameCategoryType
};
}
}
[Test]
public async Task EnumerateSubCategoriesAsyncIncludesSubtypesOfAliasNameCategoryTypeAsync()
{
var harness = AliasNameSessionHarness.Create();
var vendorCategoryType = new ExpandedNodeId(new NodeId("VendorCategoryType", 2));
var derivedCategoryType = new ExpandedNodeId(new NodeId("DerivedCategoryType", 2));
harness.Supertypes[vendorCategoryType] = ObjectTypeIds.AliasNameCategoryType;
harness.Supertypes[derivedCategoryType] = vendorCategoryType;
harness.BrowseHandler = _ => new BrowseResult
{
StatusCode = StatusCodes.Good,
ContinuationPoint = ByteString.Empty,
References = new[]
{
CreateReference("Standard", ObjectTypeIds.AliasNameCategoryType),
CreateReference("Vendor", vendorCategoryType),
CreateReference("Derived", derivedCategoryType),
CreateReference("Folder", ObjectTypeIds.FolderType),
CreateReference("Untyped", ExpandedNodeId.Null)
}.ToArrayOf()
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
var names = new List<string>();
await foreach (AliasNameSubCategoryInfo info in
client.EnumerateSubCategoriesAsync().ConfigureAwait(false))
{
names.Add(info.BrowseName.Name!);
}
string[] expectedNames = ["Standard", "Vendor", "Derived"];
Assert.That(names, Is.EqualTo(expectedNames));
static ReferenceDescription CreateReference(
string name,
ExpandedNodeId typeDefinition)
{
return new ReferenceDescription
{
NodeId = new ExpandedNodeId(new NodeId(name, 2)),
BrowseName = new QualifiedName(name, 2),
DisplayName = new LocalizedText(name),
TypeDefinition = typeDefinition
};
}
}
}
}