Files
UA-.NETStandard/tests/Opc.Ua.Gds.Tests/Common.cs
romanett 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

475 lines
18 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;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Opc.Ua.Configuration;
using Opc.Ua.Gds.Client;
using Opc.Ua.Gds.Server;
using Opc.Ua.Security.Certificates;
using Opc.Ua.Server.TestFramework;
using Opc.Ua.Test;
using Opc.Ua.Tests;
namespace Opc.Ua.Gds.Tests
{
public
#if NET7_0_OR_GREATER
partial
#endif
class ApplicationTestDataGenerator
{
#if NET7_0_OR_GREATER
[GeneratedRegex(@"[^\w\d\s]")]
private static partial Regex Regex1();
[GeneratedRegex(@"[^\w\d]")]
private static partial Regex Regex2();
#else
#pragma warning disable IDE0079 // Remove unnecessary suppression
#pragma warning disable SYSLIB1045 //Use 'GeneratedRegexAttribute' to generate the regular expression implementation at compile-time.
private static Regex Regex1()
{
return new(@"[^\w\d\s]");
}
private static Regex Regex2()
{
return new(@"[^\w\d]");
}
#pragma warning restore SYSLIB1045 //Use 'GeneratedRegexAttribute' to generate the regular expression implementation at compile-time.
#pragma warning restore IDE0079 // Remove unnecessary suppression
#endif
private readonly ServerCapabilities m_serverCapabilities;
public ApplicationTestDataGenerator(int randomStart, ITelemetryContext telemetry)
{
m_serverCapabilities = new ServerCapabilities();
RandomSource = new RandomSource(randomStart);
DataGenerator = new DataGenerator(RandomSource, telemetry);
}
public RandomSource RandomSource { get; }
public DataGenerator DataGenerator { get; }
public IList<ApplicationTestData> ApplicationTestSet(int count, bool invalidateSet)
{
var testDataSet = new List<ApplicationTestData>();
for (int i = 0; i < count; i++)
{
ApplicationTestData testData = RandomApplicationTestData();
if (invalidateSet)
{
ApplicationRecordDataType appRecord = testData.ApplicationRecord;
appRecord.ApplicationId = new NodeId(Guid.NewGuid());
switch (i % 4)
{
case 0:
appRecord.ApplicationUri = DataGenerator.GetRandomString();
break;
case 1:
appRecord.ApplicationType = (ApplicationType)RandomSource.NextInt32(
100) +
8;
break;
case 2:
appRecord.ProductUri = DataGenerator.GetRandomString();
break;
case 3:
appRecord.DiscoveryUrls =
appRecord.ApplicationType == ApplicationType.Client
? RandomDiscoveryUrl(
["xxxyyyzzz"],
RandomSource.NextInt32(0x7fff),
"TestClient")
: default;
break;
case 4:
appRecord.ServerCapabilities =
appRecord.ApplicationType == ApplicationType.Client
? RandomServerCapabilities()
: default;
break;
case 5:
appRecord.ApplicationId = new NodeId(100);
break;
}
}
testDataSet.Add(testData);
}
return testDataSet;
}
private ApplicationTestData RandomApplicationTestData()
{
// TODO: set to discoveryserver
var appType = (ApplicationType)RandomSource.NextInt32(
(int)ApplicationType.ClientAndServer);
string pureAppName = DataGenerator.GetRandomString("en");
pureAppName = Regex1().Replace(pureAppName, string.Empty);
string pureAppUri = Regex2().Replace(pureAppName, string.Empty);
string appName = "UA " + pureAppName;
ArrayOf<string> domainNames = RandomDomainNames();
string localhost = domainNames[0];
string locale = (RandomSource.NextInt32(10) == 0 ? null : "en-US")!;
string privateKeyFormat = RandomSource.NextInt32(1) == 0 ? "PEM" : "PFX";
string appUri = ("urn:localhost:opcfoundation.org:" + pureAppUri.ToLowerInvariant())
.Replace("localhost", localhost, StringComparison.Ordinal);
string prodUri = "http://opcfoundation.org/UA/" + pureAppUri;
ArrayOf<string> discoveryUrls = default;
ArrayOf<string> serverCapabilities = default;
int port = (DataGenerator.GetRandomInt16() & 0x1fff) + 50000;
switch (appType)
{
case ApplicationType.Client:
appName += " Client";
break;
case ApplicationType.ClientAndServer:
appName += " Client and";
goto case ApplicationType.Server;
case ApplicationType.DiscoveryServer:
appName += " DiscoveryServer";
discoveryUrls = RandomDiscoveryUrl(domainNames, 4840, pureAppUri);
serverCapabilities = ["LDS"];
break;
case ApplicationType.Server:
appName += " Server";
discoveryUrls = RandomDiscoveryUrl(domainNames, port, pureAppUri);
serverCapabilities = RandomServerCapabilities();
break;
}
return new ApplicationTestData
{
ApplicationRecord = new ApplicationRecordDataType
{
ApplicationNames = [new LocalizedText(locale, appName)],
ApplicationUri = appUri,
ApplicationType = appType,
ProductUri = prodUri,
DiscoveryUrls = discoveryUrls,
ServerCapabilities = serverCapabilities
},
DomainNames = domainNames,
Subject = Utils.Format("CN={0},DC={1},O=OPC Foundation", appName, localhost),
PrivateKeyFormat = privateKeyFormat
};
}
private ArrayOf<string> RandomServerCapabilities()
{
var serverCapabilities = new List<string>();
int capabilities = RandomSource.NextInt32(8);
foreach (ServerCapabilityInfo cap in m_serverCapabilities)
{
if (RandomSource.NextInt32(100) > 50)
{
serverCapabilities.Add(cap.Id!);
if (capabilities-- == 0)
{
break;
}
}
}
return serverCapabilities;
}
private string RandomLocalHost()
{
string localhost = Regex2().Replace(
DataGenerator.GetRandomSymbol("en").Trim().ToLowerInvariant(),
string.Empty);
if (localhost.Length >= 12)
{
localhost = localhost[..12];
}
return localhost;
}
private string[] RandomDomainNames()
{
int count = RandomSource.NextInt32(8) + 1;
string[] result = new string[count];
for (int i = 0; i < count; i++)
{
result[i] = RandomLocalHost();
}
return result;
}
private ArrayOf<string> RandomDiscoveryUrl(
ArrayOf<string> domainNames,
int port,
string appUri)
{
var result = new List<string>();
foreach (string name in domainNames)
{
int random = RandomSource.NextInt32(7);
if ((result.Count == 0) || (random & 1) == 0)
{
result.Add(
Utils.Format(
"opc.tcp://{0}:{1}/{2}",
name,
port++.ToString(CultureInfo.InvariantCulture),
appUri));
}
if ((random & 2) == 0)
{
result.Add(
Utils.Format(
"http://{0}:{1}/{2}",
name,
port++.ToString(CultureInfo.InvariantCulture),
appUri));
}
if ((random & 4) == 0)
{
result.Add(
Utils.Format(
"opc.https://{0}:{1}/{2}",
name,
port++.ToString(CultureInfo.InvariantCulture),
appUri));
}
}
return result;
}
}
public class ApplicationTestData
{
public ApplicationTestData()
{
Initialize();
}
private void Initialize()
{
ApplicationRecord = new ApplicationRecordDataType();
CertificateGroupId = default;
CertificateTypeId = default;
CertificateRequestId = default;
DomainNames = [];
Subject = null!;
PrivateKeyFormat = "PFX";
PrivateKeyPassword = null!;
Certificate = null!;
PrivateKey = null!;
IssuerCertificates = null!;
}
public ApplicationRecordDataType ApplicationRecord = null!;
public NodeId CertificateGroupId;
public NodeId CertificateTypeId;
public NodeId CertificateRequestId;
public ArrayOf<string> DomainNames;
public string Subject = null!;
public string PrivateKeyFormat = null!;
public char[] PrivateKeyPassword = null!;
public byte[] Certificate = null!;
public byte[] PrivateKey = null!;
public byte[][] IssuerCertificates = null!;
}
public class ApplicationMessageDlg : IApplicationMessageDlg
{
private readonly ILogger m_logger;
private string m_message = string.Empty;
private bool m_ask;
public ApplicationMessageDlg(ILogger logger)
{
m_logger = logger;
}
public override void Message(string text, bool ask)
{
m_message = text;
m_ask = ask;
}
public override Task<bool> ShowAsync()
{
if (m_ask)
{
m_message += " (y/n, default y): ";
if (m_logger.IsEnabled(LogLevel.Information))
{
m_logger.LogInformation("ASK: {Message}", m_message);
}
}
else if (m_logger.IsEnabled(LogLevel.Information))
{
m_logger.LogInformation("MSG: {Message}", m_message);
}
return Task.FromResult(true);
}
}
public static class TestUtils
{
public static async Task CleanupTrustListAsync(IOpenStore id, ITelemetryContext telemetry)
{
using ICertificateStore store = id.OpenStore(telemetry);
await CleanupStoreAsync(store).ConfigureAwait(false);
}
public static async Task CleanupTrustListAsync(
CertificateIdentifier id,
ITelemetryContext telemetry)
{
using ICertificateStore? store = CertificateIdentifierResolver.OpenStore(id, telemetry);
if (store == null)
{
return;
}
await CleanupStoreAsync(store).ConfigureAwait(false);
}
private static async Task CleanupStoreAsync(ICertificateStore store)
{
using CertificateCollection certs
= await store
.EnumerateAsync()
.ConfigureAwait(false);
foreach (Certificate cert in certs)
{
await store.DeleteAsync(cert.Thumbprint).ConfigureAwait(false);
}
if (store.SupportsCRLs)
{
X509CRLCollection crls = await store.EnumerateCRLsAsync()
.ConfigureAwait(false);
foreach (X509CRL crl in crls)
{
await store.DeleteCRLAsync(crl).ConfigureAwait(false);
}
}
}
public static void DeleteDirectory(string storePath)
{
string fullStorePath = Utils.ReplaceSpecialFolderNames(storePath)!;
if (Directory.Exists(fullStorePath))
{
Directory.Delete(fullStorePath, true);
}
}
private const int kMinPort = Utils.UaTcpDefaultPort;
public static void PatchBaseAddressesPorts(ApplicationConfiguration config, int basePort)
{
if (basePort is >= kMinPort and <= ServerFixtureUtils.MaxTestPort)
{
var newBaseAddresses = new List<string>();
foreach (string baseAddress in config.ServerConfiguration!.BaseAddresses)
{
var baseAddressUri = new UriBuilder(baseAddress) { Port = basePort++ };
newBaseAddresses.Add(baseAddressUri.Uri.AbsoluteUri);
}
config.ServerConfiguration.BaseAddresses = newBaseAddresses;
}
}
public static string PatchOnlyGDSEndpointUrlPort(string url, int port)
{
if (port is >= kMinPort and <= ServerFixtureUtils.MaxTestPort)
{
var newUrl = new UriBuilder(url);
if (newUrl.Path.Contains("GlobalDiscoveryTestServer", StringComparison.Ordinal))
{
newUrl.Port = port;
return newUrl.Uri.AbsoluteUri;
}
}
return url;
}
public static async Task<GlobalDiscoveryTestServer> StartGDSAsync(
bool clean,
string storeType = CertificateStoreType.Directory,
int maxTrustListSize = 0,
IEnumerable<CertificateGroupConfiguration>? additionalCertGroups = null)
{
GlobalDiscoveryTestServer? server = null;
int testPort = ServerFixtureUtils.GetNextFreeIPPort();
int serverStartRetries = 25;
bool retryStartServer;
do
{
retryStartServer = false;
try
{
server = new GlobalDiscoveryTestServer(true, NUnitTelemetryContext.Create(true), maxTrustListSize);
await server.StartServerAsync(clean, testPort, storeType, additionalCertGroups).ConfigureAwait(false);
}
catch (ServiceResultException sre)
{
serverStartRetries--;
if (serverStartRetries == 0 || sre.StatusCode != StatusCodes.BadNoCommunication)
{
throw;
}
// Dispose the half-initialised server so its
// ApplicationInstance/CertificateManager don't leak.
if (server != null)
{
try
{
await server.DisposeAsync().ConfigureAwait(false);
}
catch
{
}
server = null!;
}
testPort = UnsecureRandom.Shared.Next(
ServerFixtureUtils.MinTestPort,
ServerFixtureUtils.MaxTestPort);
retryStartServer = true;
}
await Task.Delay(UnsecureRandom.Shared.Next(100, 1000)).ConfigureAwait(false);
} while (retryStartServer);
return server!;
}
}
}