Files
UA-.NETStandard/docs/ComplexTypes.md
T
5899354441 Clarify documentation, migration guidance, and SDK selection (#4823)
# Description

Remove stock phrasing and correct misleading or inconsistent technical
documentation. The initial two passes covered 367 Markdown files,
followed by an interactive review of 169 editorial flags. The U5
interpretation originally deferred in that review has since received the
upstream Mantis answer recorded by #4843; remaining server/spec
follow-ups stay explicit in the CTT log.

- Correct package responsibilities, migration steps, API names,
ownership, protocol descriptions and links. Keep bundled migration
guides synchronized. Preserve historical conclusions as historical
records with separate re-check notes.
- Provide at least two rendered TOC levels throughout `docs/`. Convert
appropriate architecture figures to Mermaid without changing code
examples, transcripts or historical quotations.
- Address the October 19 feedback with concrete setup/migration
instructions, corrected certificate paths and PubSub names, shorter
repeated caveats, consistent XML comments, and a full review of the
Concepts guide. Retain #4839's API corrections.
- Integrate #4841's runtime/performance guidance and review
incoming/recent prose. Preserve dated measurements rather than claiming
new benchmark runs; clarify allocation ratios, startup-only processor
settings, JIT warm-up and the benchmark commit's scope. Missing raw
measurement artifacts and repeat ranges remain tracked by #4842.
- Merge master through `e8c5d800a` in `32c6394b7`. Resolve the CTT log
conflict using the updated Mantis states and OPC answers, retaining
historical framing and re-checks for C28/C32/C43.
- Address the latest naming/index feedback in `adb5bf693`: rename the
guides to `docs/WotCon.md` and `docs/WotNodeSetConversion.md`; move the
provider and DataType-declaration contracts into the conversion guide
and remove `docs/WoT.md`. Rename `samples/DI` to `samples/Di` and
`samples/Isa95` to `samples/ISA95`. Add content-index READMEs to Di,
FluentApi, ISA95, Lds and PubSub; update solution entries, project
references, Docker/CI paths, test fixture paths and documentation links
with exact casing.

**WoT guide scope.** This branch retains the detailed conversion guide
that #4758 had replaced with an anchor stub. Conversion limits, verified
document sets, preservation rules and provider ownership now live
together in `WotNodeSetConversion.md`; binding/runtime guidance remains
in `WotBindings.md` and `WotCon.md`. The design-rationale/test-ledger
prose was shortened, the oversized argument-table cell moved into its
section, and existing anchors preserved.

**SDK policy is a separate, explicit user-directed change.**
`global.json` sets a stable minimum of `10.0.400`, `rollForward:
latestMajor`, and `allowPrerelease: false`. Newer major SDKs are
permitted; CI's explicit SDK pins are unchanged. README, GettingStarted,
DeveloperGuide and Recycling instructions reflect the possible analyzer
differences. The image-contract regression fix accepts compatible stable
SDK images instead of requiring exact equality with the floor.

The latest four rename/index threads are resolved after publication.
Three older threads remain open: universal obsolete-removal timing,
unconditional nonce-strength wording, and a blanket Vision NativeAOT
claim. Existing implementation/evidence constraints are explained in
their inline replies. The two-level TOCs remain as requested.

## Validation

- `git diff --check` and staged diff checks: passed. The untouched
upstream AutoID NodeSet retains its provenance bytes, including two
existing license-header trailing spaces.
- `.\.azurepipelines\validate-migration-plugin.ps1`: passed; 15 bundled
migration documents and manifests synchronized.
- Documentation/path validation: **101** documents retain two rendered
TOC levels (**2,228** entries), with idempotent formatting. **52** new
relative links and their anchors passed exact-case checks. No tracked
references to the old guide/sample paths remain. Both relocated
provider-contract sections are preserved in the destination.
- `dotnet sln UA.slnx list`: passed; shows the renamed Di/ISA95 projects
and the existing FluentApi/Lds/PubSub projects. Updated solution and
pump ProjectReference paths also passed exact-case existence checks.
- Latest focused commands, run from the repository root:

```powershell
# Passed: 61 channel send-order and reconnect tests.
dotnet test tests\Opc.Ua.Core.Tests\Opc.Ua.Core.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~UaSCBinaryChannelSendOrderTests|FullyQualifiedName~TcpReconnectKeyAgreementTests' --verbosity minimal

# Passed: 5 pump datasheet tests; builds the renamed pump sample.
dotnet test tests\Opc.Ua.Di.Tests\Opc.Ua.Di.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~PumpDatasheetConformanceTests' --verbosity minimal

# Passed: 4 repository NodeSet path/round-trip tests, including the moved pump models.
dotnet test tests\Opc.Ua.Types.Tests\Opc.Ua.Types.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~RepositorySourceSurvivesSerializedLinkedPartitionsAsync' --verbosity minimal

# Passed: build, zero warnings/errors.
dotnet build samples\ISA95\MinimalIsa95Server\MinimalIsa95Server.csproj -p:CustomTestTarget=net10.0 -f net10.0 --verbosity minimal

# Passed: dependent sample-test project build, zero warnings/errors.
dotnet build tests\Opc.Ua.WotCon.Samples.Tests\Opc.Ua.WotCon.Samples.Tests.csproj -p:CustomTestTarget=net10.0 -f net10.0 --verbosity minimal
```

Earlier focused integration checks passed 2,620 tests across AutoID,
event queues/scheduling, source generation, MCP/package profiles and
WoT. Both reviewed Mermaid diagrams rendered locally without network
access. These checks are not a full solution run.

The full solution has **not** been rerun for this review. Earlier
`dotnet test UA.slnx -p:CustomTestTarget=net10.0 --verbosity quiet` did
not pass: three AOT projects rejected VSTest and 20 Vision tests failed
during graphics initialization with `OutOfMemoryException`. Remaining
long-running tests were stopped at the user's request. A focused Vision
rerun passed 558 tests and reproduced those 20 failures. The earlier
`dotnet test UA.slnx -p:CustomTestTarget=net48 --verbosity quiet` was
blocked by the former SDK pin and was not retried after the policy
change. The user approved proceeding with those limitations documented;
current remote CI is not claimed green.

## Related Issues

- Follow-up #4842 tracks the requested 2.0.2+ benchmark/tuning and
diagnostic-tool documentation refresh. #4841 supplies documentation and
earlier results, not all newly requested measurements.
- #4758 explains the conversion guide's earlier consolidation; the
current provider contracts are now consolidated into
`WotNodeSetConversion.md`.
- #4839 supplies the reviewed API corrections; #4843 supplies the
updated CTT issue record.
- The original prose cleanup and SDK policy were user-requested without
a source issue. No new runtime architecture is introduced by these
documentation edits.

## Checklist

_Put an `x` in the boxes that apply. You can complete these step by step
after opening the PR._

- [ ] 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.
- [ ] 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.

---------

Co-authored-by: Roman Ettlinger <romanett98@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:10:55 +02:00

38 KiB
Raw Blame History

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

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:

  1. Browses the server's type system to discover custom types
  2. Loads type definitions (using DataTypeDefinition attribute or binary/XML dictionaries)
  3. 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
    }
};

ArrayOf<WriteValue> writeValues = [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 object Clone() => MemberwiseClone();
}

Important

: BinaryEncodingId must match the Binary Encoding NodeId returned by the server (visible in the OPC UA address space as the DataTypeEncodingType child node named "Default Binary"). The decoder uses this NodeId 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 call LoadAsync() after registering your own types, the ComplexTypeSystem will skip types that are already registered in the factory.

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 ComplexTypeSystem loads 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: ensure LoadAsync() was called before reading the value, verify the type is actually loaded with complexTypeSystem.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 with session.Factory.Builder.AddEncodeableType(typeof(YourType)).Commit() before reading. The BinaryEncodingId on 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 on session.Factory.Builder before 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.

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

  1. OptionSet Support: Concrete Structure-backed sub-types of the abstract OptionSet DataType (i=12755, e.g. AccessRights, CarExtras) are automatically registered by the default ComplexTypeSystem builder as Opc.Ua.Encoders.OptionSet runtime instances, driven by either the EnumDefinition carried in DataTypeDefinition or a fallback synthesized from the OptionSetValues property. The runtime class exposes the two canonical Value / ValidBits ByteStrings 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 as ByteLength); setting a bit outside that range throws ArgumentOutOfRangeException. 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 a Variant — no per-bit metadata is surfaced.
    • The legacy Reflection.Emit builder in Opc.Ua.Client.ComplexTypes throws NotSupportedException for OptionSet sub-types; switch to the default builder (ComplexTypeSystem.Create(session, telemetry)) for OptionSet support.
  2. Legacy Dictionary Support: Some OPC UA 1.03 structured types that cannot be mapped to OPC UA 1.04 definitions are ignored
  3. Type Modifications: Once loaded, types cannot be dynamically updated during a session. Reconnect to reload modified types.

Additional Resources

See Also