## 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>
38 KiB
OPC UA Complex Types
Overview
The Opc.Ua.Client and Opc.Ua.Client.ComplexTypes libraries let client
applications handle custom data types (complex types) in Open Platform
Communications Unified Architecture (OPC UA). Complex types include:
- Custom Structures: User-defined structured data types with multiple fields
- Custom Enumerations: User-defined enumeration types with custom values
The libraries let clients discover and load server-specific types. Clients can then read and write structured values without manually defining each type.
Contents
- Overview
- Key Concepts
- Getting Started
- Approaches for Working with Custom Types
- Advanced Usage
- Common Patterns
- Error Handling
- Performance Considerations
- Troubleshooting
- Server-Side Complex Types
- API Reference
- Known Limitations
- Additional Resources
- See Also
Key Concepts
What are Complex Types?
In OPC UA, complex types are custom data types that a server defines beyond the built-in data types. They commonly represent structured data such as:
- Configuration structures with multiple parameters
- Device status information with multiple fields
- Custom enumerations specific to a domain or device
Type Discovery and Loading
The ComplexTypeSystem class discovers and loads custom types from an OPC UA
server. It:
- Browses the server's type system to discover custom types
- Loads type definitions (using DataTypeDefinition attribute or binary/XML dictionaries)
- Registers types that match those definitions in the session's type factory for encoding and decoding.
Supported Type Systems
The library supports multiple type definition mechanisms:
- OPC UA 1.04+ DataTypeDefinition Attribute: Modern structured type definitions
- OPC UA 1.03 Binary Schema Dictionaries: Legacy binary type dictionaries
- OPC UA 1.03 XML Schema Dictionaries: Legacy XML type dictionaries
The library automatically uses the most appropriate mechanism available on the server.
Getting Started
Type builders
Default type builder
A type builder builds the types that are registered in the EncodeableFactory by the ComplexTypeSystem class. The default type builder registers in memory IEncodeable "adapter" classes that wrap discovered DataTypeDefinition and provide "state" (a list of Variants for the properties) clone, compare, and encode/decode behavior. The default type builder is part of the Opc.Ua.Core.Schema library (namespace Opc.Ua) and is shared by client and server. It is used when no type builder is provided in the constructor of the ComplexTypeSystem class.
Reflection.Emit based type builder
The OPCFoundation.NetStandard.Opc.Ua.Client.ComplexTypes nuget package extends the Opc.Ua.Client library by adding a type builder implementation that supports dynamically generating .NET types via Reflection.Emit at runtime. This has the added benefit over the default approach that the types can be reflected over by other tools, e.g. serializers. However, this is not NativeAOT compliant, and therefore building against a NativeAOT runtime will always fall back to the default behavior.
To use the Reflection.Emit type builder add the NuGet package to your project:
dotnet add package OPCFoundation.NetStandard.Opc.Ua.Client.ComplexTypes
Or via Package Manager:
Install-Package OPCFoundation.NetStandard.Opc.Ua.Client.ComplexTypes
Basic Usage
1. Loading All Custom Types from a Server
The most common approach is to load all custom types after establishing a session:
using Opc.Ua; // ComplexTypeSystem, IComplexTypeResolver, default type builder
using Opc.Ua.Client;
using Opc.Ua.Client.ComplexTypes; // client Create(...) helpers + NodeCacheResolver
// Create and connect session
var session = await Session.Create(...);
// Uses the default NativeAOT-friendly builder.
using var complexTypeSystem = ComplexTypeSystem.Create(
session, session.MessageContext.Telemetry);
await complexTypeSystem.LoadAsync();
Console.WriteLine($"Loaded {complexTypeSystem.GetDefinedTypes().Count} custom types");
The type system owns its resolver; the using declaration releases it even when
loading fails. Types already loaded remain registered with the session. The
optional Reflection.Emit builder is selected through the
custom factory overload, using
new ComplexTypeBuilderFactory() from the separate Client.ComplexTypes package.
After loading, the session can automatically encode and decode custom types when reading or writing values.
2. Reading Values with Complex Types
Once the type system is loaded, reading complex type values is straightforward:
// Read a value that contains a complex type
NodeId nodeId = new NodeId("ns=2;s=MyCustomStructVariable");
DataValue dataValue = await session.ReadValueAsync(nodeId);
// The value is automatically decoded to a .NET type
// Note: DataValue.Value is obsolete. Use WrappedValue (Variant) instead.
if (dataValue.WrappedValue.TryGetValue(out ExtensionObject extensionObject))
{
// Access the structured data
if (extensionObject.Body is IStructure complexType)
{
// Access properties by name
Variant temperatureValue = complexType["Temperature"];
Variant pressureValue = complexType["Pressure"];
Console.WriteLine($"Temperature: {temperatureValue}");
Console.WriteLine($"Pressure: {pressureValue}");
// Enumerate all properties
foreach (IStructureField property in complexType.GetFields())
{
Console.WriteLine($"{property.Name}: {complexType[property.Name]}");
}
}
}
3. Writing Values with Complex Types
To write complex type values, modify the properties and write back:
// Read current value
DataValue dataValue = await session.ReadValueAsync(nodeId);
dataValue.WrappedValue.TryGetValue(out ExtensionObject extensionObject);
var complexType = (IStructure)extensionObject.Body;
// Modify properties
complexType["Temperature"] = 25.5;
complexType["Pressure"] = 101.3;
// Write the modified value back
var writeValue = new WriteValue
{
NodeId = nodeId,
AttributeId = Attributes.Value,
Value = new DataValue
{
WrappedValue = extensionObject,
SourceTimestamp = DateTime.UtcNow
}
};
var writeValues = new WriteValueCollection { writeValue };
var response = await session.WriteAsync(null, writeValues, CancellationToken.None);
if (StatusCode.IsGood(response.Results[0]))
{
Console.WriteLine("Value written successfully");
}
Approaches for Working with Custom Types
There are three ways to work with custom data types from an OPC UA server. The right approach depends on your use case.
Approach 1: Hand-Written IEncodeable + EncodeableFactory Registration
If you have already implemented (or generated) a class that implements IEncodeable, you can register it with the session's EncodeableFactory. The stack will then automatically decode incoming ExtensionObject values into instances of your type.
Step 1 – Implement IEncodeable
// Required namespaces:
// using Opc.Ua;
// using System.Runtime.Serialization;
[DataContract(Namespace = "http://www.siemens.com/simatic-s7-opcua")]
public class UDT_SemVer : IEncodeable
{
public UDT_SemVer() { Initialize(); }
[OnDeserializing]
private void Initialize(StreamingContext context = default) { }
[DataMember(Name = "Major", IsRequired = true, Order = 1)]
public byte Major { get; set; }
[DataMember(Name = "Minor", IsRequired = true, Order = 2)]
public byte Minor { get; set; }
[DataMember(Name = "Patch", IsRequired = true, Order = 3)]
public byte Patch { get; set; }
// TypeId must match the DataType NodeId on the server.
// The "DT_" prefix is a Siemens S7 OPC UA convention for data type nodes;
// the quoted name is the Siemens-specific identifier format.
public ExpandedNodeId TypeId =>
new ExpandedNodeId(
"nsu=http://www.siemens.com/simatic-s7-opcua;s=DT_\"UDT_SemVer\"");
// BinaryEncodingId must match the Binary Encoding NodeId on the server.
// The "TE_" prefix is the Siemens S7 OPC UA convention for type encoding nodes.
public ExpandedNodeId BinaryEncodingId =>
new ExpandedNodeId(
"nsu=http://www.siemens.com/simatic-s7-opcua;s=TE_\"UDT_SemVer\"");
public ExpandedNodeId XmlEncodingId => ExpandedNodeId.Null;
public void Encode(IEncoder encoder)
{
encoder.WriteByte("Major", Major);
encoder.WriteByte("Minor", Minor);
encoder.WriteByte("Patch", Patch);
}
public void Decode(IDecoder decoder)
{
Major = decoder.ReadByte("Major");
Minor = decoder.ReadByte("Minor");
Patch = decoder.ReadByte("Patch");
}
public bool IsEqual(IEncodeable encodeable) =>
encodeable is UDT_SemVer other &&
Major == other.Major && Minor == other.Minor && Patch == other.Patch;
public void EncodeJson(IJsonEncoder encoder)
{
encoder.WriteByte("Major", Major);
encoder.WriteByte("Minor", Minor);
encoder.WriteByte("Patch", Patch);
}
public void DecodeJson(IJsonDecoder decoder)
{
Major = decoder.ReadByte("Major");
Minor = decoder.ReadByte("Minor");
Patch = decoder.ReadByte("Patch");
}
public object Clone() => MemberwiseClone();
}
Important
:
BinaryEncodingIdmust match the Binary Encoding NodeId returned by the server (visible in the OPC UA address space as theDataTypeEncodingTypechild node named"Default Binary"). This is what the decoder uses to look up the registered type.
Step 2 – Register the Type Before Reading
Register the type with the session's factory before reading any values that use it. The simplest way is to add the Type directly:
// Create and connect the session
var session = await Session.Create(...);
// Register the custom type with the session's encodeable factory
session.Factory.Builder
.AddEncodeableType(typeof(UDT_SemVer))
.Commit();
// Now read – the stack decodes the ExtensionObject automatically
DataValue result = await session.ReadValueAsync(
"ns=3;s=\"H35dispenser\".\"ID\".\"ElectricalVersion\"");
if (result.WrappedValue.TryGetValue(out ExtensionObject extObject) &&
extObject.Body is UDT_SemVer semVer)
{
Console.WriteLine($"Major={semVer.Major} Minor={semVer.Minor} Patch={semVer.Patch}");
}
You can also register all types from an entire assembly at once:
session.Factory.Builder
.AddEncodeableTypes(typeof(UDT_SemVer).Assembly)
.Commit();
Or register multiple types individually in a single builder chain:
session.Factory.Builder
.AddEncodeableType(typeof(UDT_SemVer))
.AddEncodeableType(typeof(UDT_AnotherType))
.Commit();
Note
:
ComplexTypeSystem.LoadAsync()is not required when using this approach. If you callLoadAsync()after registering your own types, the ComplexTypeSystem will skip types that are already registered in the factory.
Approach 2: Source-Generated IEncodeable (Recommended for New Code)
Starting with version 2.0, you can annotate a POCO class with [DataType] and
optional [DataTypeField] attributes and the OPC UA source generator will
automatically generate the IEncodeable implementation for you. This eliminates
the need to hand-write Encode, Decode, IsEqual, and Clone methods.
See Source-Generated Data Types for full details.
using Opc.Ua;
[DataType(Namespace = "http://www.siemens.com/simatic-s7-opcua",
BinaryEncodingId = "s=TE_\"UDT_SemVer\"")]
public partial class UDT_SemVer
{
[DataTypeField(Order = 1)]
public byte Major { get; set; }
[DataTypeField(Order = 2)]
public byte Minor { get; set; }
[DataTypeField(Order = 3)]
public byte Patch { get; set; }
}
After adding the source generator NuGet package, the generated registration extension method can be used:
session.Factory.Builder
.AddMyNamespaceDataTypes()
.Commit();
Approach 3: Runtime IStructure (No Pre-defined Types Required)
If you do not know the type structure at compile time, or prefer not to create
.NET types for every server type, use ComplexTypeSystem to load the type
definitions at runtime and access fields via the IStructure interface. This
requires no hand-written types.
See the Basic Usage and Advanced Usage sections below for examples.
Advanced Usage
Loading Specific Types
Instead of loading all types, you can load specific types or namespaces:
Load a Specific Type
using var complexTypeSystem = ComplexTypeSystem.Create(session, session.MessageContext.Telemetry);
// Load a specific type by NodeId
ExpandedNodeId typeNodeId = new ExpandedNodeId("ns=2;i=3001");
IType? systemType = await complexTypeSystem.LoadTypeAsync(typeNodeId);
if (systemType != null)
{
Console.WriteLine($"Loaded type: {systemType.XmlName}");
}
Load a Specific Type with Subtypes
// Load a type and all its subtypes
ExpandedNodeId typeNodeId = new ExpandedNodeId("ns=2;i=3001");
IType? systemType = await complexTypeSystem.LoadTypeAsync(typeNodeId, subTypes: true);
Load All Types from a Namespace
using var complexTypeSystem = ComplexTypeSystem.Create(session, session.MessageContext.Telemetry);
// Load all custom types from a specific namespace
string namespaceUri = "http://mycompany.com/MyCustomTypes";
bool success = await complexTypeSystem.LoadNamespaceAsync(namespaceUri);
if (success)
{
Console.WriteLine($"Successfully loaded types from namespace: {namespaceUri}");
}
Working with Complex Type Properties
The IStructure interface provides flexible access to complex type fields:
Access by Name
if (extensionObject.Body is IStructure complexType)
{
// Get property value by name
Variant value = complexType["PropertyName"];
// Set property value by name
complexType["PropertyName"] = newValue;
}
Access by Index
if (extensionObject.Body is IStructure complexType)
{
// Get property value by index
Variant value = complexType[0];
// Set property value by index
complexType[0] = newValue;
}
Enumerate Properties
if (extensionObject.Body is IStructure complexType)
{
// Enumerate with detailed information
foreach (IStructureField property in complexType.GetFields())
{
Console.WriteLine($"Property: {property.Name}");
Console.WriteLine($" Type: {property.TypeInfo}");
Console.WriteLine($" IsOptional: {property.IsOptional}");
Console.WriteLine($" Value: {complexType[property.Name]}");
}
}
Handling Enumeration Types
Custom enumerations are also supported:
// After loading the type system, enum values are automatically decoded
DataValue dataValue = await session.ReadValueAsync(enumNodeId);
if (dataValue.WrappedValue.TryGetValue(out EnumValue enumValue))
{
// The value is the numeric representation
Console.WriteLine($"Enum value: {enumValue}");
// You can also get the enum type from the factory
ExpandedNodeId enumTypeId = ...;
if (session.Factory.TryGetEnumeratedType(enumTypeId, out IEnumeratedType enumType))
{
Console.WriteLine($"Enum type: {enumType.XmlName}");
}
}
Type Information and Introspection
Get All Loaded Types
using var complexTypeSystem = ComplexTypeSystem.Create(session, session.MessageContext.Telemetry);
await complexTypeSystem.LoadAsync();
// Get all types that were dynamically created
IReadOnlyList<XmlQualifiedName> definedTypes = complexTypeSystem.GetDefinedTypes();
foreach (XmlQualifiedName type in definedTypes)
{
Console.WriteLine($"Type: {type.Namespace}.{type.Name}");
}
Get Type Definitions
// Get the DataTypeDefinition for a specific type
ExpandedNodeId dataTypeId = new ExpandedNodeId("ns=2;i=3001");
var definitions = complexTypeSystem.GetDataTypeDefinitionsForDataType(dataTypeId);
foreach (var kvp in definitions)
{
Console.WriteLine($"NodeId: {kvp.Key}");
Console.WriteLine($"Definition: {kvp.Value}");
}
Get Loaded Data Type IDs
// Get all NodeIds for loaded data types
IEnumerable<ExpandedNodeId> dataTypeIds = complexTypeSystem.GetDefinedDataTypeIds();
foreach (var dataTypeId in dataTypeIds)
{
Console.WriteLine($"Loaded type: {dataTypeId}");
}
Using Custom Type Factories
You can provide a custom type factory for advanced scenarios:
// Create a custom factory (implement IComplexTypeFactory)
IComplexTypeFactory customFactory = new MyCustomComplexTypeFactory();
// Use it with the ComplexTypeSystem
using var complexTypeSystem = ComplexTypeSystem.Create(
session, customFactory, session.MessageContext.Telemetry);
await complexTypeSystem.LoadAsync();
Working with Telemetry and Logging
Pass the session's telemetry context, or an application-provided ITelemetryContext,
to the factory. The type system logs loading diagnostics through that context.
ITelemetryContext telemetry = session.MessageContext.Telemetry;
using var complexTypeSystem = ComplexTypeSystem.Create(session, telemetry);
await complexTypeSystem.LoadAsync();
Keep the type system alive while loading types, and dispose it afterward even if loading fails. Loaded types remain registered with the session's factory.
Common Patterns
Pattern 1: One-Time Type Loading at Session Start
After establishing a session with the managed client API, load its types before reading custom values:
await using ManagedSession session = await new ManagedSessionBuilder(configuration, telemetry)
.UseEndpoint(endpoint)
.ConnectAsync(ct);
using var complexTypeSystem = ComplexTypeSystem.Create(session, telemetry);
await complexTypeSystem.LoadAsync(ct: ct);
Keep the session alive for subsequent reads. Disposing the loader releases its resolver, not the types registered in the session.
Pattern 2: Lazy Loading on Demand
Load a known DataType only when needed, then read its value. This avoids keeping a loader field alive merely to retain registered types:
using var complexTypeSystem = ComplexTypeSystem.Create(session, session.MessageContext.Telemetry);
IType? loadedType = await complexTypeSystem.LoadTypeAsync(typeNodeId);
if (loadedType == null)
{
throw new InvalidOperationException("The server DataType could not be loaded.");
}
DataValue value = await session.ReadValueAsync(variableNodeId);
Coordinate concurrent loading at the application's session boundary rather than using an unsynchronized Boolean flag. See type system caching for reuse guidance.
Pattern 3: Reading Multiple Complex Values
public async Task ReadMultipleComplexValuesAsync(IList<NodeId> nodeIds)
{
// Load types once
using var complexTypeSystem = ComplexTypeSystem.Create(session, session.MessageContext.Telemetry);
await complexTypeSystem.LoadAsync();
// Read all values
var nodesToRead = nodeIds.Select(id => new ReadValueId
{
NodeId = id,
AttributeId = Attributes.Value
}).ToList();
var response = await session.ReadAsync(
null,
0,
TimestampsToReturn.Both,
new ReadValueIdCollection(nodesToRead),
CancellationToken.None
);
// Process results
for (int i = 0; i < response.Results.Count; i++)
{
var dataValue = response.Results[i];
if (dataValue.WrappedValue.TryGetValue(out ExtensionObject extensionObject) &&
extensionObject.Body is IStructure complexType)
{
Console.WriteLine($"NodeId: {nodeIds[i]}");
foreach (IStructureField property in complexType.GetFields())
{
Console.WriteLine($" {property.Name}: {complexType[property.Name]}");
}
}
}
}
Error Handling
Handling Type Loading Failures
try
{
using var complexTypeSystem = ComplexTypeSystem.Create(session, session.MessageContext.Telemetry);
bool success = await complexTypeSystem.LoadAsync(throwOnError: true);
if (success)
{
Console.WriteLine("All types loaded successfully");
}
else
{
Console.WriteLine("Some types could not be loaded");
}
}
catch (ServiceResultException ex)
{
Console.WriteLine($"Failed to load types: {ex.Message}");
// Handle error appropriately
}
Handling Missing Type Definitions
// Try to load a specific type
using var complexTypeSystem = ComplexTypeSystem.Create(session, session.MessageContext.Telemetry);
IType? systemType = await complexTypeSystem.LoadTypeAsync(typeNodeId, throwOnError: false);
if (systemType == null)
{
Console.WriteLine($"Type {typeNodeId} could not be loaded");
// Fall back to reading as ExtensionObject with opaque body
}
Performance Considerations
Type System Caching
- The
ComplexTypeSystemloads types once and caches them in the session's factory - Subsequent reads/writes use the cached types automatically
- Types remain available for the lifetime of the session
Minimizing Load Time
// Load only enumerations (faster)
using var complexTypeSystem = ComplexTypeSystem.Create(session, session.MessageContext.Telemetry);
await complexTypeSystem.LoadAsync(onlyEnumTypes: true);
// Or load only specific namespaces
await complexTypeSystem.LoadNamespaceAsync("http://mycompany.com/MyTypes");
Batch Operations
When reading multiple values with complex types, read them in batches to minimize round-trips:
// Read multiple values in one call
var response = await session.ReadAsync(
null,
0,
TimestampsToReturn.Both,
new ReadValueIdCollection(nodesToRead),
CancellationToken.None
);
Troubleshooting
Types Not Loading
Problem: LoadAsync() completes but types are not available
Solutions:
- Verify the server supports DataTypeDefinition or provides type dictionaries
- Check server logs for encoding/dictionary availability
- Use verbose logging to see what types are discovered
// Enable detailed logging through telemetry context
var telemetry = session.MessageContext.Telemetry;
using var complexTypeSystem = ComplexTypeSystem.Create(session, telemetry);
// The ComplexTypeSystem will log detailed information during type loading
await complexTypeSystem.LoadAsync();
Values Still Encoded as ExtensionObject
Problem: Values are read as ExtensionObject with opaque body instead of structured types
Solutions:
- If using
ComplexTypeSystem: ensureLoadAsync()was called before reading the value, verify the type is actually loaded withcomplexTypeSystem.GetDefinedTypes(), and check if the server's type definition is complete and valid. - If using a hand-written
IEncodeable(Approach 1): ensure the type is registered withsession.Factory.Builder.AddEncodeableType(typeof(YourType)).Commit()before reading. TheBinaryEncodingIdon your type must exactly match the Binary Encoding NodeId reported by the server — use a generic OPC UA client (e.g. UA Expert) to inspect the correct NodeId. - If using source-generated types (Approach 2): ensure the generated
Add...DataTypes()extension method is called onsession.Factory.Builderbefore reading.
Performance Issues
Problem: Type loading takes too long
Solutions:
- Load only required namespaces instead of all types
- Load types once at session start rather than on-demand
- Consider caching type information across sessions if reconnecting frequently
Server-Side Complex Types
Servers can build the same dynamic stand-in encodeables for custom DataTypes in their address space. This is useful when a server loads a NodeSet2 at runtime and its DataTypes have no compiled .NET types. Without a matching encodeable, the server cannot encode or decode instances of those DataTypes.
Server-side complex types prime the server's IEncodeableFactory with
stand-ins built from each custom DataType's DataTypeDefinition attribute.
This reuses the client's NativeAOT-friendly ComplexTypeSystem path in
Opc.Ua.Core.Schema. StandardServer runs this by default; control it with
LoadComplexTypes.
The server uses compiled, source-generated DataTypes as-is because the
generator already registers them in IEncodeableFactory. It builds stand-ins
only for DataTypes missing from the factory, such as types loaded from a
NodeSet at runtime.
If you are using Runtime NodeSets, the server-side complex-type pass runs automatically after startup imports and before each live lifecycle generation is published. No extra configuration is needed. See RuntimeNodeSets.md for startup and live add/reload/remove semantics, compatible DataType rules, and the stream ownership contract.
How compiled types reach the factory
Compiled DataTypes register explicitly, not through reflection. The OPC UA
source generator emits an Add<Namespace>(this IEncodeableFactoryBuilder)
extension for each namespace. A node manager calls the extension while it
builds its address space, for example
Server.Factory.Builder.AddTestData().Commit().
Node managers finish starting before OnNodeManagerStartedAsync runs.
Therefore, all source-generated types are already in server.Factory when
the complex-type pass executes. ComplexTypeSystem finds these types with
TryGetType or TryGetEncodeableType and skips them. It creates stand-ins
only for runtime-loaded DataTypes that remain.
Configuring via dependency injection (recommended)
Complex-type loading is on by default. Use the fluent AddComplexTypeSystem() extension when configuring the hosted server to tune the pass and expose the primed factory as a DI-resolvable schema IDataTypeDefinitionResolver:
using Microsoft.Extensions.DependencyInjection;
builder.Services
.AddOpcUa()
.AddServer(options => { /* ... */ })
.AddNodeManager<MyRuntimeNodeSetNodeManagerFactory>()
.AddComplexTypeSystem(); // build stand-ins for runtime-loaded DataTypes
The pass runs once after the server builds its address space and before it accepts connections. Clients therefore do not encounter custom values that they cannot decode.
The server also exposes the primed IEncodeableFactory as a schema
IDataTypeDefinitionResolver through EncodeableFactoryDefinitionSource.
This lets the server produce schemas directly from the factory without
populating a separate registry or walking the address space. If a
DataTypeDefinitionRegistry is registered, for example through
AddSchemaGeneration() for schema-only types without an encodeable, the
server composes it as a fallback.
Options can be configured:
.AddComplexTypeSystem(options =>
{
options.Enabled = true; // load complex types on startup (default)
options.OnlyEnumTypes = false; // also build structured types (default)
options.ThrowOnError = false; // log and continue on failures (default)
});
Direct usage without dependency injection
For servers that are not hosted through dependency injection, no extra type is required: StandardServer loads complex types by default (LoadComplexTypes), so a plain instance already builds the stand-ins once its address space is available:
var server = new StandardServer(telemetry);
await application.StartAsync(server);
Opt out by setting server.LoadComplexTypes = false before starting. To customize the pass — for example to load only enumerations — override OnNodeManagerStartedAsync in a StandardServer subclass and drive it yourself instead of calling base (which would run the default pass):
protected override async ValueTask OnNodeManagerStartedAsync(
IServerInternal server, CancellationToken cancellationToken)
{
var options = new ServerComplexTypeOptions { OnlyEnumTypes = true };
await server
.LoadComplexTypesAsync(server.Telemetry, options, cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
IServerInternal.LoadComplexTypesAsync(...) can also be invoked directly on a running server to (re)build the stand-ins on demand. It drives the shared ComplexTypeSystem with an AddressSpaceComplexTypeResolver that surfaces the server's DataType nodes and their DataTypeDefinition attributes, and returns an IDataTypeDefinitionResolver backed by the primed factory. Because the runtime stand-ins (and the generated types) expose their definition via IDataTypeDefinitionSource, the encodeable factory itself is the source of truth for data type definitions — the DataTypeDefinitionRegistry is only needed for schema-only types that have no encodeable.
API Reference
ComplexTypeSystem Class
The main class for managing complex types.
Constructors
// The ComplexTypeSystem type is defined in Opc.Ua.Core.Schema (namespace Opc.Ua).
// Create with a complex type resolver and telemetry (uses the default DefaultComplexTypeFactory)
ComplexTypeSystem(IComplexTypeResolver complexTypeResolver, ITelemetryContext telemetry)
// Create with a resolver, a custom type builder factory and telemetry
ComplexTypeSystem(IComplexTypeResolver complexTypeResolver, IComplexTypeFactory complexTypeBuilderFactory, ITelemetryContext telemetry)
// As above; ownsResolver: true makes Dispose() also dispose the resolver. The other
// constructors leave a caller-supplied resolver with the caller.
ComplexTypeSystem(IComplexTypeResolver complexTypeResolver, IComplexTypeFactory complexTypeBuilderFactory, ITelemetryContext telemetry, bool ownsResolver)
// Client factory helpers (Opc.Ua.Client, namespace Opc.Ua.Client.ComplexTypes) bind a
// ComplexTypeSystem to a session through a NodeCacheResolver with its own node cache.
// The returned system owns that resolver, so dispose it when done loading types:
// Uses the default, NativeAOT friendly type builder
static ComplexTypeSystem ComplexTypeSystem.Create(ISession session, ITelemetryContext telemetry)
// Uses a caller-provided type builder, e.g. the Reflection.Emit ComplexTypeBuilderFactory
// (requires the OPCFoundation.NetStandard.Opc.Ua.Client.ComplexTypes package)
static ComplexTypeSystem ComplexTypeSystem.Create(ISession session, IComplexTypeFactory complexTypeBuilderFactory, ITelemetryContext telemetry)
Methods
// Load all custom types from the server
ValueTask<bool> LoadAsync(bool onlyEnumTypes = false, bool throwOnError = false, CancellationToken ct = default)
// Load a specific type with optional subtypes
Task<IType?> LoadTypeAsync(ExpandedNodeId nodeId, bool subTypes = false, bool throwOnError = false, CancellationToken ct = default)
// Load all types from a namespace
Task<bool> LoadNamespaceAsync(string ns, bool throwOnError = false, CancellationToken ct = default)
// Get all dynamically created type names
IReadOnlyList<XmlQualifiedName> GetDefinedTypes()
// Get all loaded data type NodeIds
IEnumerable<ExpandedNodeId> GetDefinedDataTypeIds()
// Get data type definitions for a type
NodeIdDictionary<DataTypeDefinition> GetDataTypeDefinitionsForDataType(ExpandedNodeId dataTypeId)
// Clear the data type cache
void ClearDataTypeCache()
Properties
// Get the loaded data type dictionaries
NodeIdDictionary<DataDictionary> DataTypeSystem { get; }
IStructure Interface
Interface for accessing properties of complex types.
// Access property by zero-based index
Variant this[int index] { get; set; }
// Access property by name
Variant this[string name] { get; set; }
// Get property names
IReadOnlyList<IStructureField> GetFields()
IStructureField Interface
Provides metadata about a property in a complex type.
string Name { get; } // Property name
bool IsOptional { get; } // Whether field is optional
TypeInfo TypeInfo { get; } // Type info of the field
Known Limitations
- OptionSet Support: Concrete Structure-backed sub-types of the abstract
OptionSetDataType (i=12755, e.g.AccessRights,CarExtras) are automatically registered by the defaultComplexTypeSystembuilder asOpc.Ua.Encoders.OptionSetruntime instances, driven by either theEnumDefinitioncarried inDataTypeDefinitionor a fallback synthesized from theOptionSetValuesproperty. The runtime class exposes the two canonicalValue/ValidBitsByteStrings plus bit accessors keyed by field name or bit index. Per Part 3 §8.40 / §3.2.8, the overall ByteString length is fixed by the sub-type's declared bits (exposed asByteLength); setting a bit outside that range throwsArgumentOutOfRangeException. Remaining limitations:- UInteger-backed OptionSet DataTypes (DataTypes deriving from an unsigned integer with
IsOptionSet=true) continue to be represented as their underlying unsigned integer in aVariant— no per-bit metadata is surfaced. - The legacy Reflection.Emit builder in
Opc.Ua.Client.ComplexTypesthrowsNotSupportedExceptionfor OptionSet sub-types; switch to the default builder (ComplexTypeSystem.Create(session, telemetry)) for OptionSet support.
- UInteger-backed OptionSet DataTypes (DataTypes deriving from an unsigned integer with
- Legacy Dictionary Support: Some OPC UA 1.03 structured types that cannot be mapped to OPC UA 1.04 definitions are ignored
- Type Modifications: Once loaded, types cannot be dynamically updated during a session. Reconnect to reload modified types.
Additional Resources
- OPC UA Specification Part 3 - Address Space Model
- OPC UA Specification Part 5 - Information Model
- OPC UA Specification Part 6 - Mappings
- OPC Foundation .NET Standard Samples
- NuGet Package: OPCFoundation.NetStandard.Opc.Ua.Client.ComplexTypes
See Also
- Source-Generated Data Types - Auto-generate IEncodeable implementations from annotated POCO classes
- Developer Guide - Building, testing, platform support, packages, and versioning
- Diagnostics Documentation - Logging, telemetry, audit events, server diagnostics, and packet capture
- Console Reference Client - Example client implementation