### Example: Server and Client with Reverse Connect Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/ConsoleReferenceServer/README.md Start the client with a reverse connect listener and then start the server with reverse connect enabled to establish communication. ```bash dotnet ConsoleReferenceClient.dll --rc=opc.tcp://localhost:65300 opc.tcp://localhost:62541/Quickstarts/ReferenceServer ``` ```bash dotnet ConsoleReferenceServer.dll --rc=opc.tcp://localhost:65300 -a ``` -------------------------------- ### Initialize and Start a Reference Server Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/Quickstarts.Servers/NugetREADME.md Configures and starts an instance of the ReferenceServer using the ApplicationInstance class. ```csharp using Opc.Ua.Configuration; using Quickstarts.ReferenceServer; var application = new ApplicationInstance(telemetry) { ApplicationName = "ReferenceServer", ApplicationType = ApplicationType.Server, }; await application.LoadApplicationConfigurationAsync(silent: false).ConfigureAwait(false); await application.CheckApplicationInstanceCertificatesAsync(true).ConfigureAwait(false); await application.StartAsync(new ReferenceServer(telemetry)).ConfigureAwait(false); ``` -------------------------------- ### Server Startup Output Example Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/RedundantServer/README.md Example output showing the server's redundancy configuration and state. ```text HA sample node 'replica-a' listening at opc.tcp://localhost:62543/RedundantServer; HA_MODE=ap; REDUNDANCY_MODE=Hot; ServiceLevel=255 (Healthy). CurrentServerId: replica-a Redundant peers: (none) NTRS discovery capability and FindServers peer-set provider are enabled. RequestServerStateChange is enabled for administrator-driven Maintenance/NoData failover. ``` -------------------------------- ### Implement fluent state machine configuration Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/plans/StateMachineBuilder.md Example usage of the fluent API to configure an installation state machine with initial state, entry handlers, and timed transitions. ```csharp builder.Node("SoftwareUpdate/Installation") .As() .AsStateMachine() .WithInitialState(StateNumbers.Idle) .OnEnterState(StateNumbers.Installing, (ctx, sm) => StartInstall(packagePath)) .WithTimedTransition( fromStateNumber: StateNumbers.Installing, timeout: TimeSpan.FromMinutes(10), toStateNumber: StateNumbers.InstallationFailed) .OnTransition((ctx, sm, from, to) => m_logger.LogInformation("State {From} → {To}", from, to)); ``` -------------------------------- ### Initialize and Start an OPC UA Server Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Libraries/Opc.Ua.Configuration/NugetREADME.md Configures an application instance, provisions certificates, and starts the server using the fluent builder pattern. ```csharp using Opc.Ua; using Opc.Ua.Configuration; var application = new ApplicationInstance(telemetry) { ApplicationName = "MyServer", ApplicationType = ApplicationType.Server, }; await application.Build("urn:localhost:MyServer", "uri:example.com:MyServer") .AsServer(new[] { "opc.tcp://localhost:62541/MyServer" }) .Create() .ConfigureAwait(false); await application.CheckApplicationInstanceCertificatesAsync(true).ConfigureAwait(false); await application.StartAsync(new MyServer(telemetry)).ConfigureAwait(false); ``` -------------------------------- ### Start Server in Provisioning Mode (Windows) Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/ProvisioningMode.md Use this command to start the ConsoleReferenceServer in provisioning mode on Windows. This mode limits server functionality and enables auto-certificate acceptance. ```cmd ConsoleReferenceServer.exe --provision --console --log ``` -------------------------------- ### Install MCP Server from Local Build Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/McpServer.md Packages the project locally and installs it as a global tool from the build output directory. ```bash dotnet pack Applications/McpServer/Opc.Ua.Mcp.csproj -c Release dotnet tool install --global --add-source Applications/McpServer/bin/Release OPCFoundation.NetStandard.Opc.Ua.Mcp ``` -------------------------------- ### Install SharpFuzz on Windows Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Fuzzing/Fuzzing.md Install the SharpFuzz command line tool globally using the .NET CLI. ```powershell dotnet tool install --global SharpFuzz.CommandLine ``` -------------------------------- ### Initialize a Minimal GDS Server Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/GDS.md Configures storage backends and starts the GDS server using ApplicationInstance. ```csharp // 1. Create storage backends IApplicationsDatabase database = JsonApplicationsDatabase.Load( "gds-applications.json", telemetry); ICertificateGroup certGroup = new CertificateGroup( gdsConfig.AuthoritiesStorePath, gdsConfig.CertificateGroups); IUserDatabase userDb = JsonUserDatabase.Load( "gds-users.json", telemetry); // 2. Create the GDS server // (database implements both IApplicationsDatabase and ICertificateRequest) var gdsServer = new GlobalDiscoverySampleServer( database, database, certGroup, userDb, telemetry, autoApprove: true); // 3. Start via ApplicationInstance var app = new ApplicationInstance(telemetry) { ApplicationName = "My GDS", ApplicationType = ApplicationType.Server, ConfigSectionName = "Opc.Ua.GlobalDiscoveryServer" }; var config = await app.LoadAsync("MyGds.Config.xml"); await app.CheckApplicationInstanceCertificatesAsync(false); await app.StartAsync(gdsServer); ``` -------------------------------- ### Sample Server Console Output Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/PumpDeviceIntegrationServer/README.md Example log output showing the initialization of NodeManagers and the server listening address. ```text info: Opc.Ua.Server.MasterNodeManager MasterNodeManager.Startup - NodeManagers=3 info: Pumps.PumpNodeManager Configuring PumpNodeManager fluent wiring... info: Pumps.PumpNodeManager PumpNodeManager: address space ready (10330 predefined nodes). info: Opc.Ua.Server.StandardServer OPC UA server listening at opc.tcp://localhost:62542/PumpDeviceIntegrationServer. ``` -------------------------------- ### Install OPC UA MCP Server Tool Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/McpServer/McpREADME.md Installs the OPC UA MCP Server as a global .NET tool. This command is used for initial setup. ```bash dotnet tool install --global OPCFoundation.NetStandard.Opc.Ua.Mcp ``` -------------------------------- ### Initialize host with environment-based diagnostics Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/Diagnostics.md Programmatic setup for a host application using environment-based diagnostics. ```csharp // Program.cs HostApplicationBuilder builder = Host.CreateApplicationBuilder(); builder.Services.AddOpcUa().AddClient(options => { }); builder.Services.AddPcapFromEnvironment(); await builder.Build().RunAsync(); ``` -------------------------------- ### Configure OPC UA Server in Program.cs Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/SourceGeneratedNodeManagers.md Demonstrates the minimal setup for an OPC UA server using the .NET Generic Host and the AddOpcUa extension. ```csharp using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; HostApplicationBuilder builder = Host.CreateApplicationBuilder(args); builder.Logging.AddConsole(); builder.Services .AddOpcUa() .AddServer(o => { o.ApplicationName = "MyServer"; o.ApplicationUri = "urn:localhost:MyServer"; o.ProductUri = "uri:opcfoundation.org:MyServer"; o.AutoAcceptUntrustedCertificates = true; o.EndpointUrls.Add("opc.tcp://localhost:51210/MyServer"); }) .AddNodeManager(); await builder.Build().RunAsync(); ``` -------------------------------- ### Publisher Mode Commands Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/ConsoleReferencePubSubClient/README.md Commands to start the application in publisher mode using UDP or MQTT profiles. ```bash ConsoleReferencePubSubClient publisher --profile udp-uadp --interval 1000 ConsoleReferencePubSubClient publisher --profile mqtt-json --endpoint mqtt://localhost:1883 ``` -------------------------------- ### Install Fuzzing Dependencies on Linux Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Fuzzing/Fuzzing.md Commands to prepare the environment and install required fuzzing tools on a Linux system. ```bash cd /Fuzzing sudo apt-get update sudo apt-get install -y build-essential cmake git dotnet-sdk-10.0 # Powershell on Linux (required by the helper scripts): # https://learn.microsoft.com/powershell/scripting/install/install-ubuntu ./Scripts/install.sh # builds afl-fuzz + installs SharpFuzz.CommandLine ``` -------------------------------- ### Create UserIdentity with CertificateProvider Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/migrate/2.0.x/certificates.md Example of wiring the certificate provider into UserIdentity creation. ```csharp UserIdentity userIdentity = await UserIdentity.CreateAsync( certificateIdentifier, passwordProvider, configuration.CertificateManager.CertificateProvider, ct); ``` -------------------------------- ### Enable Provisioning Mode via Console Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/ProvisioningMode.md Use the --provision command line option to start the ConsoleReferenceServer application in provisioning mode. ```bash dotnet ConsoleReferenceServer.dll --provision ``` -------------------------------- ### Install Reflection.Emit Type Builder Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/ComplexTypes.md Commands to add the necessary NuGet package for dynamic type generation support. ```bash dotnet add package OPCFoundation.NetStandard.Opc.Ua.Client.ComplexTypes ``` ```powershell Install-Package OPCFoundation.NetStandard.Opc.Ua.Client.ComplexTypes ``` -------------------------------- ### Configure environment variables for Kubernetes or Docker Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/Diagnostics.md Example environment variable configuration for containerized deployments. ```yaml env: - name: OPCUA_PCAP_FILE value: /var/log/opcua/cap.pcap - name: OPCUA_KEYLOGFILE value: /var/log/opcua/keys.uakeys.json ``` -------------------------------- ### Reverse Connect Client and Server Setup Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/ConsoleReferenceClient/README.md Commands to initiate a reverse connection between the client and server in separate terminal sessions. ```bash dotnet ConsoleReferenceClient.dll --rc=opc.tcp://localhost:65300 opc.tcp://localhost:62541/Quickstarts/ReferenceServer ``` ```bash dotnet ConsoleReferenceServer.dll --rc=opc.tcp://localhost:65300 -a ``` -------------------------------- ### Configure Rate Limits Without Dependency Injection Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/RateLimiting.md Directly assign options or a provider to the server instance before it starts. ```csharp var server = new StandardServer(telemetry); server.RateLimitOptions = new ServerRateLimitOptions { ConnectionsPerSecond = 200 }; // or: server.RateLimiterProvider = new DefaultServerRateLimiterProvider(options); ``` -------------------------------- ### Perform Trust-List Operations Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/CertificateManager.md Examples for registering custom trust-lists, enumerating stores, performing atomic transactions, and handling trust-list blobs. ```csharp // Register a custom trust-list at runtime manager.RegisterTrustList( new TrustListIdentifier("CustomDevices"), trustedStorePath: "/opt/opcua/pki/devices/trusted", issuerStorePath: "/opt/opcua/pki/devices/issuers"); // Open a store directly using ICertificateStore trustedStore = manager.OpenTrustedStore(TrustListIdentifier.Peers); using CertificateCollection certs = await trustedStore.EnumerateAsync(); // Transactional trust-list update (atomic commit/rollback) await using ITrustListTransaction tx = await manager.BeginUpdateAsync(TrustListIdentifier.Peers); await tx.AddTrustedCertificateAsync(newTrustedCert); await tx.RemoveTrustedCertificateAsync(oldThumbprint); await tx.CommitAsync(); // Atomic apply; disposing without commit rolls back // Read/write trust-list as a blob (GDS Push Management) TrustListData data = await manager.ReadTrustListAsync(TrustListIdentifier.Peers); await manager.WriteTrustListAsync(TrustListIdentifier.Peers, data); ``` -------------------------------- ### Provisioning Mode Server Output Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/ProvisioningMode.md These log messages indicate that the server has started in provisioning mode, with auto-acceptance enabled and limited namespaces loaded. ```log [INF] Enabling provisioning mode. [INF] Auto-accept enabled for provisioning mode. [INF] Server is in provisioning mode - limited namespace enabled. [INF] MasterNodeManager.Startup - NodeManagers=2 ``` -------------------------------- ### Capture Inbound Server Traffic Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/Diagnostics.md Install the server binding before starting the server and use a CaptureSessionManager to record traffic. ```csharp using Opc.Ua.Pcap.Bindings; using Opc.Ua.Pcap.Capture; using Opc.Ua.Pcap.Capture.Sources; using Opc.Ua.Pcap.Models; // 1. Install the server listener binding BEFORE starting the server. // (Reuse the returned registry for the capture session below.) IChannelCaptureRegistry registry = PcapBindings.InstallServer(server.Server!.TransportBindings); // ... configure node managers, certificates, etc. ... await server.StartAsync().ConfigureAwait(false); // listeners open now // 2. Start recording. The capture source factory and the binding MUST // share the same registry instance. var manager = new CaptureSessionManager( new DefaultCaptureSourceFactory(registry), baseFolder: @"C:\captures"); await using (manager.ConfigureAwait(false)) { CaptureSession session = await manager.StartAsync(new StartCaptureRequest { Source = CaptureSourceKind.InProcessServer, SessionFolder = @"C:\captures\server-run", }, ct).ConfigureAwait(false); // 3. Every client that connects while the session is running has its // inbound/outbound frames and channel-token key material recorded. await manager.StopAsync(session.SessionId, ct).ConfigureAwait(false); // session.SessionFolder now contains capture.pcap (+ keys.uakeys.json). } ``` -------------------------------- ### Initialize and use WotConnectivityClient Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/WoTConnectivity.md Demonstrates creating a client, managing an asset, uploading a Thing Description, and enumerating properties. ```csharp WotConnectivityClient client = await WotConnectivityClient.ForServerAsync( session, session.MessageContext.Telemetry, ct); WotAssetClient asset = await client.CreateAssetAsync("PressureSensor01", ct); await asset.UploadThingDescriptionAsync(File.ReadAllBytes("sensor.td.jsonld"), ct); await foreach (WotAssetVariableEntry property in asset.EnumeratePropertiesAsync(ct)) { DataValue value = (await session.ReadValueAsync(property.NodeId, ct))!; Console.WriteLine($"{property.BrowseName} = {value.WrappedValue}"); } await client.DeleteAssetAsync(asset.AssetId, ct); ``` -------------------------------- ### Validate Fuzzing Tool Installation Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Fuzzing/Fuzzing.md Verify that the fuzzing tools are correctly installed and accessible in the system path. ```bash afl-fuzz --help sharpfuzz ``` -------------------------------- ### Initialize an OPC UA Client Application Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/nuget/MetaPackageREADME.md Demonstrates the basic setup for an OPC UA client application using the meta-package. Requires the Opc.Ua namespaces and an existing telemetry instance. ```csharp using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Configuration; // Open a session to an opc.tcp server. var application = new ApplicationInstance(telemetry) { ApplicationName = "MyClient", ApplicationType = ApplicationType.Client, }; await application.LoadApplicationConfigurationAsync(silent: false).ConfigureAwait(false); await application.CheckApplicationInstanceCertificatesAsync(true).ConfigureAwait(false); ``` -------------------------------- ### JSONL Key Log Format Examples Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/Diagnostics.md Examples of the .uakeys.json format, showing both encrypted and unencrypted (None) security modes. ```json {"channelId":1001,"tokenId":7,"securityPolicyUri":"http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256","securityMode":"SignAndEncrypt","createdAt":"2026-06-06T11:48:00Z","lifetimeMs":3600000,"clientNonce":"Y2xpZW50","serverNonce":"c2VydmVy","clientSigningKey":"MDEyMw==","clientEncryptingKey":"NDU2Nw==","clientInitializationVector":"ODlhYg==","serverSigningKey":"Y2RlZg==","serverEncryptingKey":"MDEyMw==","serverInitializationVector":"NDU2Nw=="} ``` ```json {"channelId":1002,"tokenId":1,"securityPolicyUri":"http://opcfoundation.org/UA/SecurityPolicy#None","securityMode":"None","createdAt":"2026-06-06T11:49:00Z","lifetimeMs":3600000,"clientNonce":"","serverNonce":""} ``` -------------------------------- ### Enable Provisioning Mode with Logging Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/ProvisioningMode.md Combine the --provision option with --console and --log to enable provisioning mode and console logging. ```bash dotnet ConsoleReferenceServer.dll --provision --console --log ``` -------------------------------- ### Implement KeyCredentialService Lifecycle in C# Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/KeyCredentialService.md Demonstrates server-side store initialization and client-side credential request, completion, and revocation flow. ```csharp // ── Server Side ────────────────────────────────────── // 1. Create the credential store var secretStore = new InMemorySecretStore("KeyCredentials"); var kcStore = new InMemoryKeyCredentialRequestStore(secretStore); // 2. Create the GDS server with credential support var gdsServer = new GlobalDiscoverySampleServer( database, requestStore, certGroup, userDb, telemetry); // 3. After server starts, wire the store // (done automatically by ApplicationsNodeManager when // KeyCredentialRequestStore is set before CreateAddressSpace) // ── Client Side ────────────────────────────────────── // 1. Connect to the GDS var gdsClient = new GlobalDiscoveryServerClient(config); await gdsClient.ConnectAsync(gdsEndpointUrl); // 2. Find the KeyCredentialService node // (browse or use a well-known NodeId) // 3. Create the client proxy var kcClient = new KeyCredentialServiceClient( gdsClient.Session, serviceNodeId); // 4. Request → Finish → Use → Revoke NodeId reqId = await kcClient.StartRequestAsync( "urn:my-mqtt-bridge", default, null, default); var (credId, secret, _, _, _) = await kcClient.FinishRequestAsync(reqId, false); // Use credId/secret to connect to MQTT broker... // When done: await kcClient.RevokeAsync(credId); ``` -------------------------------- ### Ethernet Addressing Examples Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/PubSub.md Examples of valid connection address formats for the Ethernet transport, including multicast, VLAN tagging, and broadcast configurations. ```text opc.eth://01-00-5E-7F-00-01 # multicast, untagged opc.eth://01-00-5E-7F-00-01?vid=5&pcp=6 # multicast, VLAN 5, priority 6 opc.eth://FF-FF-FF-FF-FF-FF # broadcast opc.eth://00-11-22-33-44-55 # unicast ``` -------------------------------- ### Example Model Structure in JSON Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Tools/Opc.Ua.SourceGeneration.Core/Schema/readme.md Represents the same model structure as the XML example, but in JSON format. This is often used for programmatic manipulation or data exchange. ```json { "TargetNamespace": "http://example.com/MyModel", "TargetVersion": "1.0", "TargetXmlNamespace": "http://example.com/MyModel/Types.xsd", "DefaultLocale": "en", "Namespaces": [ { "Name": "MyNamespace", "Prefix": "Example.MyModel", "Content": "http://example.com/MyModel" } ], "ObjectTypes": [ { "SymbolicName": "MyObjectType" } ] } ``` -------------------------------- ### Define IDiPostSetupContext Interface Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/DeviceIntegration.md Provides the context for post-setup configuration, allowing access to the manager and device builders. ```csharp public interface IDiPostSetupContext { DiNodeManager Manager { get; } CancellationToken CancellationToken { get; } T GetRequiredService() where T : notnull; ValueTask> CreateDeviceAsync(...); ValueTask> CreateDeviceAsync(...) where TDevice : ComponentState; IDeviceBuilder Device(NodeId nodeId) where TDevice : ComponentState; IDeviceBuilder DeviceByBrowseName(QualifiedName name, NodeState? parent = null) where TDevice : ComponentState; } ``` -------------------------------- ### OPC UA MCP Tool Usage Examples Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/McpServer.md Examples of using MCP tools to connect to servers, browse nodes, and read values across multiple sessions. ```text Tool: Connect endpointUrl: "opc.tcp://server1:62541/ReferenceServer" name: "refserver" (optional — auto-generated from hostname if omitted) autoAcceptCerts: true Tool: Connect endpointUrl: "opc.tcp://plc1:4840" name: "plc1" Tool: Browse nodeId: "i=85" sessionName: "refserver" (optional — uses the only session if there's just one) Tool: ReadValue nodeId: "ns=2;s=Temperature" sessionName: "plc1" ``` -------------------------------- ### Run Console Reference Client with Different Transport Protocols Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/ConsoleReferenceClient/README.md Examples of launching the client using various URL schemes to specify the underlying transport profile. ```bash # UA-TCP (default) dotnet ConsoleReferenceClient.dll opc.tcp://localhost:62541/Quickstarts/ReferenceServer # WSS+uacp (binary UA SecureChannel over TLS WebSocket) dotnet ConsoleReferenceClient.dll opc.wss://localhost:62543/Quickstarts/ReferenceServer # HTTPS (binary) dotnet ConsoleReferenceClient.dll opc.https://localhost:62543/Quickstarts/ReferenceServer ``` -------------------------------- ### Install PCAP Bindings Manually Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Stack/Opc.Ua.Core.Diagnostics/NugetREADME.md Install capture bindings directly into server or client transport configurations when dependency injection is not used. Ensure a shared IChannelCaptureRegistry is used for session management. ```csharp using Opc.Ua.Pcap.Bindings; // server (inbound): install before the server starts its listeners IChannelCaptureRegistry registry = PcapBindings.InstallServer(server.Server!.TransportBindings); // client (outbound): install into the process-wide client default // PcapBindings.InstallClient(ClientChannelManager.DefaultChannelBindings, registry); ``` -------------------------------- ### MemoryBuffer Quickstart Server Data Types Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/SourceGeneratedDataTypes.md Defines custom data types for the MemoryBuffer quickstart server, including MemoryBufferConfiguration and MemoryBufferInstance. Both classes are partial and have parameterless constructors. StructureHandling.Inline forces exact-type encoding. ```csharp using Opc.Ua; namespace MemoryBuffer { [DataType(Namespace = Namespaces.MemoryBuffer)] public partial class MemoryBufferConfiguration { public MemoryBufferConfiguration() { } [DataTypeField(Order = 1, StructureHandling = StructureHandling.Inline)] public ArrayOf Buffers { get; set; } } [DataType(Namespace = Namespaces.MemoryBuffer)] public partial class MemoryBufferInstance { public MemoryBufferInstance() { } [DataTypeField(Order = 1)] public string Name { get; set; } [DataTypeField(Order = 2)] public int TagCount { get; set; } [DataTypeField(Order = 3)] public string DataType { get; set; } } } ``` -------------------------------- ### Initialize V2 Subscription Engine Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/Sessions.md Demonstrates configuring a ManagedSession with the V2 engine and adding a subscription with monitored items. ```csharp // V2 engine is the default for ManagedSession ManagedSession session = await new ManagedSessionBuilder(configuration, telemetry) .UseEndpoint(endpoint) .ConnectAsync(ct); var handler = new MyNotificationHandler(); // : ISubscriptionNotificationHandler ISubscription subscription = session.AddSubscription(handler, new Opc.Ua.Client.Subscriptions.SubscriptionOptions { PublishingInterval = TimeSpan.FromMilliseconds(500), KeepAliveCount = 10, LifetimeCount = 100 }); subscription.TryAddMonitoredItem( "ServerStatus_CurrentTime", VariableIds.Server_ServerStatus_CurrentTime, o => o with { SamplingInterval = TimeSpan.FromMilliseconds(250), QueueSize = 10 }, out IMonitoredItem _); ``` -------------------------------- ### DiTopologyClient Enumeration Example Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/DeviceIntegration.md Iterates through devices in the topology using the DiTopologyClient. ```csharp DiTopologyClient topology = new(session, telemetry); await foreach (TopologyEntry device in topology.EnumerateDevicesAsync()) { Console.WriteLine($"{device.BrowseName}: {device.DisplayName}"); } ``` -------------------------------- ### ConfigureDevicesFor Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/DeviceIntegration.md Registers a post-setup configuration delegate that executes after the node manager has initialized its address space. ```APIDOC ## ConfigureDevicesFor(Action configure) ### Description Registers a delegate to configure devices for a specific node manager type. The delegate runs after the manager's address space is populated and the type tree is wired. ### Parameters - **configure** (Action or Func) - Required - The configuration logic to execute. ### Generic Constraints - **TNodeManager** - Must be a subclass of `DiNodeManager`. ``` -------------------------------- ### GetRequestEntry caller usage Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/plans/ctt-issues.md Example of how the raw-data cache is retrieved and passed to the helper function. ```javascript var requestEntries = Test.AggregateTestData.RawDataCache.ItemMap.Get( itemName ); // may be null var requestEntry = this.GetRequestEntry( requestEntries, requestDefinition ); ``` -------------------------------- ### Configure a Plain DI Server Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/DeviceIntegration.md Initializes a host builder with OPC UA DI support and defines a device with identification properties. ```csharp using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; HostApplicationBuilder builder = Host.CreateApplicationBuilder(args); builder.Services .AddOpcUa() .AddServer(o => { o.ApplicationName = "MyDiServer"; o.EndpointUrls.Add("opc.tcp://localhost:48010/MyDiServer"); }) .AddOpcUaDi() .ConfigureDevicesFor(async ctx => { var device = await ctx.CreateDeviceAsync( new QualifiedName("Sensor #1", ctx.Manager.DiNamespaceIndex)); device.WithIdentification(id => { id.Manufacturer = new LocalizedText("Acme"); id.SerialNumber = "SN-001"; id.DeviceClass = "Sensor"; }); }); await builder.Build().RunAsync(); ``` -------------------------------- ### Register KeyCredentialRequestStore in GDS Server Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/KeyCredentialService.md Wires the credential store into the ApplicationsNodeManager during server setup. ```csharp // In your INodeManagerFactory or server setup: var appNodeManager = new ApplicationsNodeManager(server, configuration, ...); appNodeManager.KeyCredentialRequestStore = new InMemoryKeyCredentialRequestStore(mySecretStore); ``` -------------------------------- ### Create Directory and Write File Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/FileSystemClient.md Create a directory structure and write binary data to a file. ```csharp UaDirectoryInfo dir = await fs.CreateDirectoryAsync("/Uploads/2024-05/test", createIntermediate: true); await fs.WriteAllBytesAsync($"{dir.FullPath}/payload.bin", payload); ``` -------------------------------- ### Subscriber Mode Command Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/ConsoleReferencePubSubClient/README.md Command to start the application in subscriber mode using the UDP/UADP profile. ```bash ConsoleReferencePubSubClient subscriber --profile udp-uadp ``` -------------------------------- ### Implement INodeCache.InvalidateNode Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/migrate/2.0.x/alarms-model-change.md Example of implementing the new member in a custom INodeCache class by delegating to Clear. ```csharp public sealed class MyNodeCache : INodeCache { public void Clear() { /* ... */ } // Add this: public void InvalidateNode(NodeId nodeId) => Clear(); // ... rest of INodeCache ... } ``` -------------------------------- ### Migrate PubSub Application Initialization Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/migrate/2.0.x/pubsub.md Replaces the legacy UaPubSubApplication.Create method with the asynchronous PubSubApplicationBuilder pattern. ```csharp // Before (1.5.378) var app = UaPubSubApplication.Create("publisher.xml"); app.Start(); // ... app.Stop(); // After (2.0) await using var app = await new PubSubApplicationBuilder() .ConfigureFromXml("publisher.xml") .BuildAsync(); await app.StartAsync(); // ... await app.StopAsync(); ``` -------------------------------- ### Run the PumpDeviceIntegrationServer Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/PumpDeviceIntegrationServer/README.md Commands to navigate to the application directory and execute the server in release mode. ```pwsh cd Applications/PumpDeviceIntegrationServer dotnet run -c Release ``` -------------------------------- ### Initialize FileSystemPackageStore Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/DeviceIntegration.md Configures a FileSystemPackageStore using a physical file system provider. ```csharp IFileSystemProvider fs = new PhysicalFileSystemProvider( rootDirectory: "/var/lib/myserver/packages", mountName: "Packages", isWritable: true); ISoftwarePackageStore store = new FileSystemPackageStore( provider: fs, rootPath: "/SoftwarePackages"); ``` -------------------------------- ### Start HTTP/SSE Transport Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/McpServer.md Command to launch the server using HTTP/SSE transport for remote client connectivity. ```bash opcua-mcp --transport sse --port 5100 ``` -------------------------------- ### Build the OPC UA solution Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/README.md Commands to restore dependencies and build the solution from the repository root. ```bash dotnet restore UA.slnx dotnet build UA.slnx ``` -------------------------------- ### Enable Provisioning Mode Programmatically Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/ProvisioningMode.md Programmatically enable provisioning mode by calling the EnableProvisioningMode utility method on a ReferenceServer instance. ```csharp var server = new ReferenceServer(); Quickstarts.Servers.Utils.EnableProvisioningMode(server); ``` -------------------------------- ### Build and Publish Commands Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/ConsoleReferencePubSubClient/README.md Standard .NET CLI commands to build and publish the application as a single-file executable. ```bash dotnet build Applications/ConsoleReferencePubSubClient/ConsoleReferencePubSubClient.csproj dotnet publish Applications/ConsoleReferencePubSubClient/ConsoleReferencePubSubClient.csproj -r win-x64 ``` -------------------------------- ### Browse the Objects folder Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Applications/McpServer/README.md Tool call to browse the address space starting from the Objects folder (nodeId i=85). ```text Tool: Browse Arguments: nodeId: "i=85" ``` -------------------------------- ### Initialize host for keylog-only diagnostics Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/Diagnostics.md Minimal service registration for scenarios requiring only keylogging. ```csharp builder.Services.AddOpcUa().AddClient(options => { }); builder.Services.AddPcapFromEnvironment(); ``` -------------------------------- ### Enable Provisioning Mode Directly Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/ProvisioningMode.md Directly set the ProvisioningMode property to true on a ReferenceServer instance to enable provisioning mode. ```csharp var server = new ReferenceServer { ProvisioningMode = true }; ``` -------------------------------- ### Guard array access Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/plans/ctt-issues.md Example of the guard pattern used elsewhere in the script to prevent TypeErrors when ArrayItems is undefined. ```js if( isDefined( CUVariables.ArrayItems.length ) && CUVariables.ArrayItems.length > 0 ) { ... } // lines 78, 85, 119 ``` -------------------------------- ### Configure Server Capture via Environment Variables Source: https://github.com/opcfoundation/ua-.netstandard/blob/master/Docs/Diagnostics.md Use environment variables to trigger capture in non-DI hosts by calling TryStartFromEnvironmentAsync before server startup. ```csharp using Opc.Ua.Pcap.Capture; // PcapServerCapture // Before Application.StartAsync(server) / before the listeners open. IAsyncDisposable? capture = await PcapServerCapture.TryStartFromEnvironmentAsync( server.Server!.TransportBindings, telemetry.LoggerFactory).ConfigureAwait(false); // ... run the server ... // On shutdown: if (capture is not null) { await capture.DisposeAsync().ConfigureAwait(false); } ```