/* ======================================================================== * Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * The complete license agreement can be found here: * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ using System; using System.Collections.Generic; using System.IO; using Microsoft.Extensions.Logging; using Opc.Ua.Schema.Model; namespace Opc.Ua.SourceGeneration { /// /// Emits a partial {Namespace}NodeManager deriving from /// AsyncCustomNodeManager plus a matching /// {Namespace}NodeManagerFactory implementing /// IAsyncNodeManagerFactory. Opt-in via /// . /// /// /// The generated manager wires the predefined nodes from the existing /// Add{Namespace}(NodeStateCollection, ISystemContext) extension /// (emitted by ) and exposes a /// partial void Configure(INodeManagerBuilder builder) hook for /// user code-behind. Lifecycle dispatchers (AddPredefinedNode, /// RemovePredefinedNode, OnMonitoredItemCreated) are wired /// to the runtime fluent dispatcher so callbacks registered via the /// builder are invoked at the right times. /// /// When an attribute-driven binding supplies a class name and namespace /// override (via and /// ), the generator /// emits the partial under that user-chosen identity instead of the /// design-derived defaults. Factory emission can be suppressed via /// . /// /// internal sealed class NodeManagerGenerator : IGenerator { /// /// Optional override for the namespace of the generated partial. /// Defaults to the design's TargetNamespace.Prefix. /// public string? OverrideNamespace { get; init; } /// /// Optional override for the class name of the generated partial. /// Defaults to {Prefix}NodeManager. /// public string? OverrideClassName { get; init; } /// /// When false the matching {ClassName}Factory is /// not emitted. Defaults to true. /// public bool EmitFactory { get; init; } = true; /// /// When false the public /// (IServerInternal, ApplicationConfiguration) constructor /// is not emitted; only the protected constructor taking /// the namespace URI array is. Defaults to true. /// public bool EmitDefaultConstructor { get; init; } = true; /// /// Additional namespace URIs (beyond the model namespace) that /// the generated constructor passes to the base node manager and /// the generated factory advertises via NamespacesUris. /// Typically a sample's separate instance namespace. Optional. /// public IReadOnlyList? AdditionalNamespaceUris { get; init; } /// /// Create node manager generator. /// public NodeManagerGenerator(IGeneratorContext context) { m_context = context ?? throw new ArgumentNullException(nameof(context)); m_logger = context.Telemetry.CreateLogger(); } /// public IEnumerable Emit() { string nsPrefix = m_context.ModelDesign.TargetNamespace.Prefix; string typeStem = nsPrefix.Replace(".", string.Empty, StringComparison.Ordinal); string? nsUriSymbol = m_context.ModelDesign.Namespaces .GetConstantSymbolForNamespace(m_context.ModelDesign.TargetNamespace.Value); string targetNamespace = string.IsNullOrEmpty(OverrideNamespace) ? nsPrefix : OverrideNamespace; string targetClass = string.IsNullOrEmpty(OverrideClassName) ? typeStem + "NodeManager" : OverrideClassName; string factoryClass = string.IsNullOrEmpty(OverrideClassName) ? typeStem + "NodeManagerFactory" : OverrideClassName + "Factory"; // The namespace is part of the stem: two bound managers may share a // class name in different namespaces, and the output file system // silently overwrites an existing file of the same name. string fileStem = string.IsNullOrEmpty(OverrideClassName) ? nsPrefix : targetNamespace + "." + OverrideClassName; var resources = new List(2) { EmitNodeManager(nsPrefix, targetNamespace, targetClass, typeStem, nsUriSymbol!, fileStem) }; // The factory body is a call to the public (server, configuration) // constructor. When that constructor is suppressed the manager cannot // be built from those two arguments alone, so a factory would not // compile - skip it and say so rather than emitting broken code. if (EmitFactory && !EmitDefaultConstructor) { m_logger?.LogWarning( "Node manager '{ClassName}' suppresses the public " + "(IServerInternal, ApplicationConfiguration) constructor, so no " + "'{FactoryName}' is generated. Set GenerateFactory=false to " + "silence this, or allow the default constructor.", targetClass, factoryClass); } else if (EmitFactory) { resources.Add(EmitFactoryFile(targetNamespace, targetClass, factoryClass, nsUriSymbol!, fileStem)); } return resources; } private TextFileResource EmitNodeManager( string modelNamespace, string targetNamespace, string targetClass, string typeStem, string nsUriSymbol, string fileStem) { string fileName = Path.Combine( m_context.OutputFolder, CoreUtils.Format("{0}.NodeManager.g.cs", fileStem)); using TextWriter writer = m_context.FileSystem.CreateTextWriter(fileName); using var templateWriter = new TemplateWriter(writer); var template = new Template(templateWriter, NodeManagerTemplates.File); template.AddReplacement(Tokens.NamespacePrefix, targetNamespace); template.AddReplacement(Tokens.Prefix, modelNamespace); template.AddReplacement(Tokens.Namespace, typeStem); template.AddReplacement( Tokens.NodeSetImportFactoryProviderClassName, typeStem + "NodeSetImportFactoryProvider"); template.AddReplacement(Tokens.NodeManagerClassName, targetClass); template.AddReplacement(Tokens.NamespaceUri, nsUriSymbol); template.AddReplacement( Tokens.AdditionalNamespaceUris, FormatAdditionalNamespaceUris()); // An empty target list collapses the block, which is how the // template expresses "omit the default constructor". template.AddReplacement( Tokens.NodeManagerDefaultConstructor, NodeManagerTemplates.DefaultConstructor, EmitDefaultConstructor ? [targetClass] : Array.Empty()); template.Render(); return fileName.AsTextFileResource(); } /// /// Renders the additional namespace URIs as a trailing /// , "uri" argument list, or an empty string when none /// were configured. /// private string FormatAdditionalNamespaceUris() { if (AdditionalNamespaceUris == null || AdditionalNamespaceUris.Count == 0) { return string.Empty; } var buffer = new System.Text.StringBuilder(); foreach (string uri in AdditionalNamespaceUris) { if (string.IsNullOrEmpty(uri)) { continue; } buffer.Append(", ").Append(uri.AsStringLiteral()); } return buffer.ToString(); } private TextFileResource EmitFactoryFile( string targetNamespace, string targetClass, string factoryClass, string nsUriSymbol, string fileStem) { string fileName = Path.Combine( m_context.OutputFolder, CoreUtils.Format("{0}.NodeManagerFactory.g.cs", fileStem)); using TextWriter writer = m_context.FileSystem.CreateTextWriter(fileName); using var templateWriter = new TemplateWriter(writer); var template = new Template(templateWriter, NodeManagerTemplates.FactoryFile); template.AddReplacement(Tokens.NamespacePrefix, targetNamespace); template.AddReplacement(Tokens.NodeManagerClassName, targetClass); template.AddReplacement(Tokens.NodeManagerFactoryClassName, factoryClass); template.AddReplacement(Tokens.NamespaceUri, nsUriSymbol); template.AddReplacement( Tokens.AdditionalNamespaceUris, FormatAdditionalNamespaceUris()); template.Render(); return fileName.AsTextFileResource(); } private readonly IGeneratorContext m_context; private readonly ILogger m_logger; } }