This guide is the starting point for contributing to the OPC UA .NET Standard stack. It covers what to install, how to build and test, the coding standards ("dos and don'ts"), and task-oriented "how to" recipes (starting with how to add logging). It links out to the topic-specific documents in docs/README.md rather than repeating them.
If you are new here, read the sections in order: Prerequisites → Repository layout → Building → Running tests → Coding standards. The How-to guides and Packages, platform support, and versioning sections are reference material you can jump to as needed.
- .NET SDK 10.0 — the whole repository builds and restores with the .NET 10 SDK. Older SDKs are not supported for building
main. The class libraries still target older frameworks (see Packages, platform support, and versioning), but you build them with the .NET 10 SDK. - An IDE (optional but recommended) — Visual Studio 2026, Visual Studio Code with the C# Dev Kit, or JetBrains Rider. Everything can also be done from the command line with
dotnet. - git — to clone and to create feature branches.
- Docker Desktop (optional) — only needed to run the containerized reference server; see ContainerReferenceServer.md.
The C# language version is pinned (LangVersion 14) and analyzer/style rules are enforced by the build, so no extra tooling install is required to get the same diagnostics locally that CI produces.
| Path | Contents |
|---|---|
src/ |
The core stack and higher-level libraries: Opc.Ua.Types, Opc.Ua.Core*, Opc.Ua.Client, Opc.Ua.Server, Opc.Ua.Configuration, Opc.Ua.PubSub (+ transports), the GDS / DI / LDS / WoT libraries, and the Opc.Ua.Redundancy* family. |
samples/ |
Reference and sample apps: ConsoleReferenceServer, ConsoleReferenceClient, Quickstarts.Servers, the Minimal* / PumpDeviceIntegrationServer NativeAOT samples, Redundant*, etc. |
tests/ |
Unit and integration test projects, mirroring the library structure, plus shared test frameworks. |
tools/ |
Source generators, migration analyzers, and the installable Opc.Ua.Mcp tool. |
docs/ |
This documentation set (indexed by docs/README.md). |
fuzzing/ |
SharpFuzz / libFuzzer fuzz targets (see Fuzzing.md). |
Central build configuration lives at the repository root and is imported by every project:
UA.slnx— the solution containing all projects.Directory.Build.props/Directory.Build.targets— global MSBuild properties and targets.Directory.Packages.props— Central Package Management: every NuGet version is declared here.common.props/targets.props— shared properties, analyzer settings, and the target-framework matrix..editorconfig— the authoritative code-style and analyzer-severity rules (enforced at build time).
From the repository root:
dotnet restore UA.slnx
dotnet build UA.slnxNotes:
-
Warnings are errors.
TreatWarningsAsErrorsis enabled, so compiler (CSxxxx) and Roslynator (RCSxxxx) diagnostics fail the build. Microsoft Code Analysis (CAxxxx) diagnostics are emitted as non-fatal warnings unless a rule is promoted to error in.editorconfig. Fix all of them before opening a pull request. -
Building a single target framework. By default the libraries multi-target the whole matrix (see Packages, platform support, and versioning). To restrict a local build to one framework, pass
-p:CustomTargetFrameworks, for example:dotnet build src/Opc.Ua.Core/Opc.Ua.Core.csproj -f net10.0 -p:CustomTargetFrameworks=net10.0
-
Offline / restricted networks.
NuGetAuditis enabled and fails the build withNU1900when it cannot reach the audit service. If you build offline, pass-p:NuGetAudit=false.
Run the whole suite from the solution:
dotnet test UA.slnxConventions and requirements:
- Frameworks. Test projects use either NUnit (with
Assert.Thatassertions and Moq for mocking) or TUnit (with its own assertions and mock helpers). Do not mix the two in one project, and do not use the classic NUnit asserts (Assert.AreEqual, …). - Coverage. Coverage is measured with Coverlet and must not regress; every non-application, non-test project should stay at or above 80 %.
- Before a pull request the
UA.slnxsuite must pass on at least .NET Framework 4.8 and .NET 10.0. - Testing a specific target framework. The libraries multi-target, but the test executables run on one framework at a time. To run the suite against a non-default framework, set
CustomTestTarget(supported values:netstandard2.0,netstandard2.1,net472,net48,net8.0,net9.0,net10.0). The batch filetests/customtest.batcleans, restores, and runs the tests for a chosen target; in Visual Studio, uncomment and set theCustomTestTargetproperty intargets.props. A clean build for the target is recommended when switching. - CI matrix. To keep pull-request builds fast, only net48 and net8.0 are exercised in the qualifying CI build; the other frameworks run in scheduled/manual CI. Fix all failing, flaky, and CodeQL findings in the pipelines.
All rules apply to new code and to existing code you touch. The .editorconfig is authoritative and enforced at build time; the highlights below are the ones most often missed.
Formatting and style
- Add the OPC Foundation MIT license header to every new source file.
- 4-space indentation, max line length 120, CRLF line endings, UTF-8, final newline, no trailing whitespace.
- Allman braces; always specify access modifiers explicitly; member order is constructors → properties/events → methods → fields, each
public→protected→internal→private. - Do not use
#region/#endregionor comment-only section dividers. Do not add#nullable enableto a file when the project already sets<Nullable>enable</Nullable>. - Put every XML-doc
<summary>text on its own line (never a single-line/// <summary> … </summary>). - Follow standard C# naming; no underscores in method or test-method names (tests use PascalCase).
API and language
- Async only. New code uses
async/await(TAP). Do not add APM or sync-over-async (.Result,.Wait(),GetAwaiter().GetResult()) unless explicitly requested. - No
objectin public API (except when overridingEquals). For OPC UA values useVariant. INullabletypes must not be wrapped inSystem.Nullable<T>(T?); use.IsNull/.Nullinstead. On struct types preferTryGet/TryGetValueover casting; never useVariant.AsBoxedValueorIUnion.Value.- Prefer
ArrayOf<T>over read-only collection types /IReadOnlyList<T>/ arrays in new public API; preferByteStringoverbyte[]; preferSpan<byte>/ReadOnlySpan<byte>overbyte[]. - Do not use
[Obsolete]API (outside test code) and do not add API that is not NativeAOT-compatible. - Maintain backward compatibility with 1.5.378; mark replaced API
[Obsolete]rather than removing it.
Concurrency
- Never expose locks in any API surface. For a synchronous lock use
System.Threading.Lock(a polyfill is provided for older TFMs) — neverprivate readonly object m_lock = new(). PreferSemaphoreSlimwhere async coordination is needed.
Architecture
- Make non-abstract public classes
sealedby default; prefer a provider model with injectable providers over inheritance. - Wire new functionality into the dependency-injection infrastructure (with a direct "construct it yourself" fallback) and expose it through the fluent API where possible.
- Reuse the existing base services (telemetry, file system, certificate/secret stores, state machines, sessions, source generators, …) instead of re-implementing them.
Security
- Never hardcode credentials, certificates, or secrets. Manage certificates through the certificate store system and secrets through the secret store (see CertificateManager.md and Certificates.md).
- Use only SHA-2 or stronger hash algorithms; use the audit and redaction APIs for sensitive data.
Logging — use source-generated logging; never call ILogger.LogInformation/LogError/… directly. See Add a log message (source-generated).
The stack uses LoggerMessageAttribute source-generated logging everywhere. It avoids boxing value-type arguments, caches the message formatter, and emits an IsEnabled check so a disabled level costs nothing. Direct ILogger.LogInformation/LogError/… calls are not allowed. The runtime/observability side (how the ILogger is created from ITelemetryContext) is documented in Diagnostics.md; this section is the authoring recipe.
Recipe
- Get a logger. Obtain an
ILoggerfrom the ambientITelemetryContext(telemetry.CreateLogger<T>()); most types already hold one in anm_loggerfield. - Find or create the log class. Each file that logs has, at its end, an
internal static partial class <PrimaryClass>Logholding[LoggerMessage]extension methods onILogger. Add your message there. If several closely-related files emit the same messages, use one shared<Area>Logclass instead of duplicating (for example the encoders/decoders inOpc.Ua.TypesshareEncodingLog). - Reserve an event id. Each project has one
internal static class <AssemblyToken>EventIdsat its root (see Event-id convention). Use the existing per-class offset. - Declare the message. Add a partial method with
[LoggerMessage(EventId = <AssemblyToken>EventIds.<Class> + <index>, Level = LogLevel.<Level>, Message = "…")](see Log class convention). - Call it. Replace the old
logger.LogXxx(...)call withlogger.<MethodName>(args).
Each project owns exactly one event-id class, named <AssemblyToken>EventIds, in namespace Opc.Ua, in a file EventIds.cs at the project root. <AssemblyToken> is the assembly name with the Opc.Ua. prefix removed and dots dropped — for example Opc.Ua.Core → CoreEventIds, Opc.Ua.Core.Types → CoreTypesEventIds, Opc.Ua.Client → ClientEventIds.
The token prefix is required because the stack uses InternalsVisibleTo: two internal classes with the same name in the same namespace collide across an IVT boundary (CS0436). The class holds one public const int offset per log class. Offsets are assigned in class-alphabetical order starting at 0; each block reserves at least five spare slots for future messages and is then rounded up to the next multiple of ten, so ids stay documented and managed in one place. Every log method sets EventId = <AssemblyToken>EventIds.<Class> + <zero-based message index within that class>.
- One log class per file, named
<PrimaryClass>Log,internal static partial, appended at the end of the file inside the same namespace. - Methods are extension methods on
ILogger(public static partial void <Name>(this ILogger logger, …)) so call sites read naturally aslogger.<Name>(…). - Identical
this ILoggeroverloads (same name and parameter types) declared in more than one class of the same namespace collide (CS0121) — deduplicate them into a single shared<Area>Logclass. Overloads that differ by name or by parameter type are fine.
- Message text is exact and static; use named placeholders (
{ChannelId}) that match a parameter of the same name. Never interpolate ($"…"). AnExceptionargument is detected by its type and does not need a placeholder. - Parameter types must match the real argument type. Do not use
object/object?, and do not call.ToString()on an argument (type the parameter instead, e.g. an enum orint); an unnecessary.ToString()tripsRCS1097/CA1305. Declare a parameter nullable (string?,Uri?,Exception?) only when the argument can actually be null, otherwise the compiler reportsCS8604. - Guard only expensive arguments. If a call passes an expensive computed argument (
string.Join(...), a LINQ projection,.ToString()on a complex object) wrap it inif (logger.IsEnabled(<level>)); source generation does not suppress eager evaluation of the arguments, andCA1873flags it. Do not guard cheap arguments (locals, fields, ids) — over-guarding tripsRCS1006/RCS1061. A guard must never gate an expression that has an observable side effect. - Dynamic levels stay hand-written.
[LoggerMessage]needs a compile-timeLevel. A call whose level is only known at runtime keeps the structuredlogger.Log(logLevel, "{Template}", args)form wrapped inif (logger.IsEnabled(logLevel)). These are the only remaining directILogger.Logcalls. - Shared/linked source files that are
<Compile Include>-d into more than one project (for example a sample file linked into a test project) cannot reference another assembly's<AssemblyToken>EventIdsclass — give their log class literalEventIdintegers in a high, dedicated range instead. - Duplicate generator on netstandard. A project that also references an R9 package (
Microsoft.Extensions.Http.Resilience,.Compliance,.Telemetry, …) gets theMicrosoft.Gen.Logginggenerator in addition to the in-box one; onnetstandardboth implement every partial method (CS0757). The repo'sDirectory.Build.targetsremoves the R9 analyzer onnetstandardonly — no per-project action is needed.
Worked example
// EventIds.cs (project root) — the assembly-token prefix avoids CS0436 across
// InternalsVisibleTo boundaries.
namespace Opc.Ua
{
internal static class TypesEventIds
{
public const int Encoding = 20; // shared codec block (reserves 20)
public const int Matrix = 50; // per-file block (reserves 10)
}
}
// end of Matrix.cs
internal static partial class MatrixLog
{
[LoggerMessage(EventId = TypesEventIds.Matrix + 0, Level = LogLevel.Debug,
Message = "ReadArray read dimensions[{Index}] = {Dimensions}. Matrix will have 0 elements.")]
public static partial void ReadArrayZeroDimension(this ILogger logger, int index, int[] dimensions);
}
// call site
logger.ReadArrayZeroDimension(index, dimensions);Checklist
- Message text and level are unchanged from the original call (behavior-preserving).
- Placeholders are named and match parameter names; no interpolation.
- Parameter types match the arguments; nullable only where needed; no
object. - Expensive arguments are guarded with
IsEnabled; cheap ones are not. -
EventIduses the project's<AssemblyToken>EventIdsoffset (or a literal range for a shared/linked file). - When testing with a mocked
ILogger, stubIsEnabled(...) => trueand match onEventId.Name, not the (empty) source-generated stateToString().
- Add a new feature — implement it in the right library, add unit and (for client/server/pubsub) integration tests, update or add a doc under
docs/, and keep backward compatibility (see Coding standards). - Add a document — put it in
docs/and link it from docs/README.md. - Add a dependency — declare the version in
Directory.Packages.props(Central Package Management), prefer AOT/trimmable and permissively licensed packages, and get maintainer approval first. - Certificates and secrets — see Certificates.md and CertificateManager.md.
- Source-generated node managers / data types — see SourceGeneratedNodeManagers.md and SourceGeneratedDataTypes.md.
- Dependency injection — see DependencyInjection.md.
- NativeAOT — see NativeAoT.md.
The following NuGet packages are released on a monthly cadence (with hot fixes for security issues). The OPCFoundation prefix is reserved, and the assemblies and packages are signed by the OPC Foundation.
- OPCFoundation.NetStandard.Opc.Ua — a convenience meta-package that pulls in everything except PubSub. Prefer referencing the individual packages below to reduce your dependency surface.
- OPCFoundation.NetStandard.Opc.Ua.Types
- OPCFoundation.NetStandard.Opc.Ua.Core.Types — the generated OPC UA NodeSet models and state classes.
- OPCFoundation.NetStandard.Opc.Ua.Core and OPCFoundation.NetStandard.Opc.Ua.Security.Certificates — required by both client and server projects.
- OPCFoundation.NetStandard.Opc.Ua.Configuration — configure a UA application from file or with the fluent API.
- OPCFoundation.NetStandard.Opc.Ua.Server — build a UA server.
- OPCFoundation.NetStandard.Opc.Ua.Client and OPCFoundation.NetStandard.Opc.Ua.Client.ComplexTypes — build a client; the complex-type library adds support for complex types.
- OPCFoundation.NetStandard.Opc.Ua.Bindings.Https — optional
opc.httpstransport. - OPCFoundation.NetStandard.Opc.Ua.PubSub (Beta) — publisher/subscriber model.
For improved source-level debugging, symbol packages are published on nuget.org in snupkg format, and Debug-compiled packages are available with a .Debug suffix. In addition, every successful master build publishes preview packages to the Azure DevOps preview feed.
The class libraries currently target:
- .NET Standard 2.0 (
Opc.Ua.Typesonly) - .NET Standard 2.1
- .NET Framework 4.7.2 (limited support)
- .NET Framework 4.8
- .NET 8.0
- .NET 9.0
- .NET 10.0
To keep pull-request CI fast, only (4) and (6) are part of the qualifying build; the other platforms are covered by scheduled or manual CI. See Running tests for how to build and test a specific framework locally with CustomTestTarget / tests/customtest.bat.
From 2.0 onward, package versions are produced by Nerdbank.GitVersioning (nbgv) from the version.json file at the repository root. That file holds the base version (currently 2.0-preview) and requests SemVer 2.0 package versions (nugetPackageVersion.semVer: 2); nbgv derives the version height, prerelease tag, and build metadata from the git history, and version.props maps the computed values onto the assembly and package version properties. Stable (public-release) versions are produced only on the main, master, develop/*, and release/<x.y.z> branches — every other branch yields a prerelease build.
The earlier 1.x packages used a different, spec-derived scheme in which the first two digits encoded the embedded NodeSet spec version (for example
1.5.378.xcorresponds to OPC UA spec V1.05, mapped to release branches such asrelease/1.4.372). That scheme no longer applies from 2.0 onward.
- Fork the repository (or, if you have write access, push a branch prefixed with your username) and open a pull request. You must agree to the Contributor License Agreement; the "I AGREE" prompt appears automatically on your first PR. See CONTRIBUTING.md.
- Before submitting: all tests pass, code analysis is clean (no new warnings), the change keeps backward compatibility, and security implications are reviewed.
- The pull-request template asks you to confirm the CLA, added tests/coverage, documentation, a warning-free build, that the
UA.slnxsuite passed on .NET Framework 4.8 and .NET 10.0, and that CI and CodeQL are green. - You can run the
opc-ua-codestyle-enforceragent to drive analyzer warnings to zero before opening the PR.
- Documentation index — all topic guides.
- Diagnostics — telemetry context, logging runtime, metrics, audit events, server diagnostics nodes, and packet capture.
- Dependency Injection, Certificates / Certificate Manager, NativeAOT, Migration Guide, What's New in 2.0.
- Fuzz testing.