Files
UA-.NETStandard/docs/migrate/2.0.x/source-generation.md
Marc Schier c4e0721a29 Add a documentation learning path and fix issues found while verifying it (#4555)
## Summary

### Documentation
- Stage the documentation index as a learning path: a first application,
independent client, server, and PubSub paths, then data and services,
companion models, production, advanced integration, and draft or
experimental capabilities.
- Add Getting started (repository samples or NuGet packages), OPC UA
concepts, Your first information model, and a production readiness
checklist.
- Add Native AOT application publishing, a first PubSub publisher and
subscriber exchange, and the UDP transport options.
- Add or expand contents navigation throughout `docs/`, and keep
contributor documentation separate.
- Correct outdated SDK examples and capability guidance, consolidate
repeated explanations into canonical guides, and repair local links and
heading structure.
- Rewrite What's New in 2.0 as a concise feature overview with short
linked details; keep migration instructions in the Migration Guide.
- Expand the feature catalogue with specification IDs, GDS, LDS, the OPC
10000-21 onboarding registrar, ISA-95, xRegistry, OpenUSD, and
sample-local models; distinguish draft status, explain crypto
pluggability, and bring performance guidance forward.
- Address review feedback on wording, active monitored items during
shadow reload, and the `Samples.md` filename and references.
- Regenerate the `opcua-v20-migration` plugin's bundled copy of the
migration guides so it matches the edited `docs/migrate/2.0.x` guides.
- Merge the latest `master`, preserving upstream resource-isolation
guidance within the task-based documentation index.
- Retain deferred Lingity findings where appropriate; this PR does not
claim that every document meets the Lingity score thresholds.

### Fixes found while verifying the guides
Each fix has regression tests that fail without it.
- **Client:** V2 subscriptions compared their lifetime with the
operation timeout instead of the session timeout, and logged a spurious
warning. `ISubscriptionEngineContext`, which is new in 2.0, gains a
`SessionTimeout` property; implementations must add it.
- **PubSub:** a subscriber now registers the `DataSetMetaData`
configured on its readers (OPC 10000-14 6.2.9.4), and the UADP decoder
decodes DataSetMessages that carry no ConfigurationVersion. Before, a
secured subscriber of the reference sample received no DataSets.
- **Source generator:** a ModelDesign method that declares its arguments
inline, without a method type, produced code that did not compile; it
now uses `MethodState`. The generated code of existing models is
unchanged.
- **MinimalClient sample:** waits for its first data-change notification
before it disconnects.

### Known issues, not addressed here
- UDP multicast: the publisher does not send on the interface that the
subscriber joins, and `MulticastLoopback` defaults to false. The PubSub
guide uses unicast for the exchange on one computer.
- The UDP metadata announcement is sent unsecured on secured writer
groups; a secured subscriber drops it with a warning.
- A server does not start in globalization-invariant mode, because
`ResourceManager` creates `CultureInfo("en-US")`. The Native AOT guide
cautions against the mode.

## Validation
- `git diff --check` and
`./.azurepipelines/validate-migration-plugin.ps1` (15 bundled migration
docs validated, plugin manifests synchronized).
- Local Markdown links, anchors, file-link casing, and contents lists
checked across all 87 documents under `docs/`. The index links every
top-level guide and every target of the previous index.
- Both Getting started routes, Your first information model, the PubSub
exchange, and the Native AOT publish of the Getting started client and
server were run as documented. The NuGet route and the tutorial use the
public `2.0.0-preview.5` packages.
- The changed libraries build for all target frameworks in Release
without warnings.
- Tests on .NET 10: Opc.Ua.SourceGeneration.Tests 199 passed;
Opc.Ua.SourceGeneration.Core.Tests 3,977 passed, 8 skipped;
Opc.Ua.Server.Tests `Fluent` category 621 passed; Opc.Ua.Client.Tests
subscription-engine tests 70 passed; Opc.Ua.PubSub.Tests 1,374 passed, 2
skipped; PubSub fuzz replay 145 passed. The new and affected tests also
pass on .NET Framework 4.8.
- Earlier merge validation: 174 resource-isolation tests passed on .NET
10.
- The full solution suite was not run locally.

Review and validation artifacts are maintained outside the repository.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-09-28 19:19:39 +00:00

8.6 KiB

Source Generation

When to read this: Read this for the move from pre-generated code files to the source-generated NodeManager / data-type model, including the project-structure changes and the new default for boolean properties.

Contents

Migrating model projects

Instead of generating code for OPC UA design files using the ModelCompiler, this version of the stack uses Source Generators to generate code behind for your project. Input into the source generator can be NodeSet2.xml files or ModelDesign.xml files (the same that ModelCompiler consumes). Example projects are provided under samples/. Source generators are Roslyn analyzers, that are called by the Roslyn compiler and emit code during the build process.

Model compiler generated csharp code is not supported in this version!

To migrate remove all your generated files (ending in *.Classes.cs, *.Constants.cs, etc.) and only leave the design file(s) (.xml and .csv files) in your project. Add an entry into your csproj file similar to the following to provide the location of the design files to the source generation process:

  <PropertyGroup>
    <!-- Optional: to configure whether to allow sub types - see model compiler documentation -->
    <ModelSourceGeneratorUseAllowSubtypes>true</ModelSourceGeneratorUseAllowSubtypes>
  </PropertyGroup>
  <ItemGroup>
    <!-- Generate code behind for the following design or nodeset2.xml files during build-->
    <AdditionalFiles Include="Boiler\Generated\BoilerDesign.csv" />
    <AdditionalFiles Include="Boiler\Generated\BoilerDesign.xml" />
    <AdditionalFiles Include="MemoryBuffer\Generated\MemoryBufferDesign.csv" />
    <AdditionalFiles Include="MemoryBuffer\Generated\MemoryBufferDesign.xml" />
    <AdditionalFiles Include="TestData\Generated\TestDataDesign.csv" />
    <AdditionalFiles Include="TestData\Generated\TestDataDesign.xml" />
  </ItemGroup>

The source generator model has several benefits that go beyond custom msbuild targets: Among the most important is that the generator ships with the stack and therefore code that is generated conforms to the stack version that ships the analyzer (the source generator will be part of Opc.Ua.Core nuget package). Therefore when updating to a newer version the code generated automatically takes advantage of the improvements made across the entire stack.

Code generation during compilation also allows not just emitting code ahead of time, but also to generate code while you are developing. We now take advantage of this feature to generate IEncodeable implementations for partial POCO types on the fly using the [DataType] and [DataTypeField] attributes as annotation (similar to DataContract/DataMember).

The stack itself uses source generators to generate the core opc ua code. Therefore all pre-generated code files (Generated/ folders) have been removed and are now generated at build time. As a result of using source generators to generate the stack code all *.nodeset2.xml files previously included as embedded zip have been removed. Also, all *.Types.xsd and *.Types.bsd files are now included as string resource instead of embedded resources. If you need access to these, use the new Schemas.XmlAsStream and Schemas.BinaryAsStream APIs in the node manager namespace which produce a utf8 stream. Alternatively you can use the existing ModelCompiler tool to generate these files.

When you encounter slower build times use incremental compilation and avoid changes to code in Opc.Ua and Opc.Ua.Core project. In addition you can change your builds to only build for your target framework using the dotnet -f <tfm> command line option, e.g. -f net10.0.

Default value of boolean properties in source-generated data types is now false

Breaking Change: Boolean properties on source-generated data types now correctly default to false instead of true.

Generated code produced by the model compiler contained a bug because it inverted the default value for boolean fields in generated data types. Boolean fields without an explicit <DefaultValue> in the model design XML were initialized to true instead of false as expected and defined in Part 6. This has been fixed.

Impact: Any code that creates instances of source-generated data types and relies on boolean properties being true by default must now explicitly set those properties to true. This primarily affects PubSub configuration types:

Type Property Old Default New Default
PubSubConfigurationDataType Enabled true false
PubSubConnectionDataType Enabled true false
WriterGroupDataType Enabled true false
ReaderGroupDataType Enabled true false
DataSetWriterDataType Enabled true false
DataSetReaderDataType Enabled true false
PublishedDataSetCustomSourceDataType CyclicDataSet true false

Other affected types include all source-generated structures with boolean fields (e.g., AggregateConfiguration.TreatUncertainAsBad, MonitoringParameters.DiscardOldest, CreateSubscriptionRequest.PublishingEnabled) as well as some hand-written types in Opc.Ua.Types (such as BrowseDescription, RelativePathElement).

Migration: Add explicit initialization where your code depends on true as the default:

// Before (relied on incorrect true default)
var connection = new PubSubConnectionDataType
{
    Name = "MyConnection"
};

// After (explicitly set Enabled)
var connection = new PubSubConnectionDataType
{
    Enabled = true,
    Name = "MyConnection"
};

Server default Aggregate configuration now treats Uncertain as Bad (Part 13)

Behavioral Change (Part 13 compliance): The server-side default aggregate configuration returned by AggregateManager.GetDefaultConfiguration(...) — used when a ReadProcessedDetails request sets AggregateConfiguration.UseServerCapabilitiesDefaults = true — now sets TreatUncertainAsBad = true, matching the default mandated by OPC 10000-13 (Aggregates) v1.05.07 §4.2.1.2. Previously it defaulted to false.

Impact: Processed (aggregate) history reads that rely on the server-capabilities defaults now treat Uncertain-quality samples as Bad when computing aggregate StatusCodes (unless a specific aggregate definition states otherwise). Clients that require the previous behavior should send an explicit AggregateConfiguration with TreatUncertainAsBad = false instead of UseServerCapabilitiesDefaults = true.

MIG01 resolution playbook

The migration analyzer's source generator emits temporary <Type>Collection : List<T> compatibility wrappers. It reports MIG01 when it cannot identify one element type for a referenced legacy wrapper:

MIG01: Cannot resolve a unique element type 'Foo' for legacy wrapper 'FooCollection'.

The generator checks, in order:

  1. Its catalog of element types renamed across the 1.5.378 → 2.0 boundary.
  2. A unique matching type declared in the consumer compilation.
  3. Metadata types named exactly System.<Type> or Opc.Ua.<Type>.

A using directive, PackageReference, or ProjectReference does not extend the metadata search to arbitrary dependency namespaces. Resolve the warning by replacing the wrapper with the intended fully qualified List<T> or ArrayOf<T>. If the legacy wrapper must remain temporarily, define that wrapper explicitly in consumer source so the unresolved reference binds and the generator does not try to synthesize it.

Project Structure

New Opc.Ua project as an intermediate project. Impact:

  • Most applications using NuGet packages are not affected. Continue linking to Opc.Ua.Core project as it includes the Opc.Ua intermediate assembly
  • Assembly loading order may change

See also