-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathComplexTypeBuilder.cs
More file actions
218 lines (204 loc) · 9.55 KB
/
Copy pathComplexTypeBuilder.cs
File metadata and controls
218 lines (204 loc) · 9.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/* ========================================================================
* 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.Reflection;
using System.Reflection.Emit;
namespace Opc.Ua.ComplexTypes
{
/// <summary>
/// Build an assembly with custom enum types and
/// complex types based on the BaseComplexType class
/// using System.Reflection.Emit.
/// </summary>
public class ComplexTypeBuilder : IComplexTypeBuilder
{
/// <summary>
/// Initializes the object with default values.
/// </summary>
public ComplexTypeBuilder(
AssemblyModule moduleFactory,
string targetNamespace,
int targetNamespaceIndex,
string? moduleName = null)
{
TargetNamespace = targetNamespace;
TargetNamespaceIndex = targetNamespaceIndex;
m_moduleName = FindModuleName(moduleName, targetNamespace);
m_moduleBuilder = moduleFactory.GetModuleBuilder();
}
/// <summary>
/// The target namespace of the type builder.
/// </summary>
public string TargetNamespace { get; }
/// <summary>
/// The target namespace index of the type builder.
/// </summary>
public int TargetNamespaceIndex { get; }
/// <summary>
/// Create an enum type from an EnumDefinition in an ExtensionObject.
/// Available since OPC UA V1.04 in the DataTypeDefinition attribute.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="enumDefinition"/> is <c>null</c>.</exception>
public IEnumeratedType AddEnumType(
QualifiedName typeName,
EnumDefinition enumDefinition)
{
if (enumDefinition == null)
{
throw new ArgumentNullException(nameof(enumDefinition));
}
if (typeName.IsNull)
{
throw new ArgumentNullException(nameof(typeName));
}
if (string.IsNullOrEmpty(typeName.Name))
{
// The type name should not be null or empty then the type definition
// or xml is broken. For the latter we want to go into the fallback path
// And try to read the data type definition's enum definition.
// TODO: IComplexTypeBuilder.AddEnumType should declare a nullable return
// type to match this fallback behaviour. Callers already null-check the result.
return null!;
}
EnumBuilder enumBuilder = m_moduleBuilder.DefineEnum(
GetFullQualifiedTypeName(typeName),
TypeAttributes.Public,
typeof(int));
enumBuilder.DataContractAttribute(TargetNamespace);
var fieldNames = new HashSet<string>();
foreach (EnumField enumValue in enumDefinition.Fields)
{
// Create a field from the type name and ensure it is not a duplicate
string? fieldName = enumValue.Name;
if (string.IsNullOrEmpty(fieldName))
{
// This is to be super safe, but we should never get here.
fieldName = $"{typeName.Name}_{enumValue.Value}";
}
// After the IsNullOrEmpty branch fieldName is non-null; older TFMs lack
// the [NotNullWhen(false)] annotation on string.IsNullOrEmpty so the
// compiler cannot infer that, hence the suppression.
if (fieldNames.Add(fieldName!))
{
FieldBuilder newEnum = enumBuilder.DefineLiteral(
fieldName!,
(int)enumValue.Value);
newEnum.EnumMemberAttribute(fieldName!, (int)enumValue.Value);
}
}
// The dynamically generated enum is always recognised as IEnumeratedType
// by ReflectionBasedType.From because we just defined an enum type.
return (IEnumeratedType)ReflectionBasedType.From(enumBuilder.CreateTypeInfo())!;
}
/// <summary>
/// Create a complex type from a StructureDefinition.
/// Available since OPC UA V1.04 in the DataTypeDefinition attribute.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="structureDefinition"/> is <c>null</c>.</exception>
/// <exception cref="DataTypeNotSupportedException"></exception>
public IComplexTypeFieldBuilder AddStructuredType(
QualifiedName name,
StructureDefinition structureDefinition)
{
if (structureDefinition == null)
{
throw new ArgumentNullException(nameof(structureDefinition));
}
Type baseType = structureDefinition.StructureType switch
{
StructureType.StructureWithOptionalFields => typeof(OptionalFieldsComplexType),
StructureType.UnionWithSubtypedValues or StructureType.Union => typeof(UnionComplexType),
StructureType.StructureWithSubtypedValues or StructureType.Structure => typeof(BaseComplexType),
_ => throw new DataTypeNotSupportedException("Unsupported structure type")
};
TypeBuilder structureBuilder = m_moduleBuilder.DefineType(
GetFullQualifiedTypeName(name),
TypeAttributes.Public | TypeAttributes.Class,
baseType);
structureBuilder.DataContractAttribute(TargetNamespace);
structureBuilder.StructureDefinitionAttribute(structureDefinition);
return new ComplexTypeFieldBuilder(structureBuilder, structureDefinition.StructureType);
}
/// <summary>
/// OptionSet sub-types are not supported by the Reflection.Emit
/// complex type builder. Use the default (source-generated)
/// complex type builder instead for OptionSet support.
/// </summary>
/// <exception cref="NotSupportedException">Always thrown.</exception>
public IEncodeableType AddOptionSetType(
QualifiedName typeName,
ExpandedNodeId typeId,
ExpandedNodeId binaryEncodingId,
ExpandedNodeId xmlEncodingId,
EnumDefinition enumDefinition)
{
throw new NotSupportedException(
"OptionSet DataTypes are not supported by the Reflection.Emit " +
"complex type builder. Use the default complex type builder.");
}
/// <summary>
/// Create a unique namespace module name for the type.
/// </summary>
private static string FindModuleName(string? moduleName, string targetNamespace)
{
if (string.IsNullOrWhiteSpace(moduleName))
{
// remove space chars in malformed namespace url
string tempNamespace = targetNamespace.Replace(
" ",
string.Empty,
StringComparison.Ordinal);
var uri = new Uri(tempNamespace, UriKind.RelativeOrAbsolute);
string tempName = uri.IsAbsoluteUri ? uri.AbsolutePath : uri.ToString();
tempName = tempName.Replace("/", string.Empty, StringComparison.Ordinal);
string[] splitName = tempName.Split(':');
moduleName = splitName[^1];
}
// moduleName is non-null after the if (either reassigned, or non-whitespace
// already); older TFMs lack [NotNullWhen(false)] on IsNullOrWhiteSpace.
return moduleName!;
}
/// <summary>
/// Creates a unique full qualified type name for the assembly.
/// </summary>
/// <param name="browseName">The browse name of the type.</param>
private string GetFullQualifiedTypeName(QualifiedName browseName)
{
string result = "Opc.Ua.ComplexTypes." + m_moduleName + ".";
if (browseName.NamespaceIndex > 1)
{
result += browseName.NamespaceIndex + ".";
}
return result + browseName.Name;
}
private readonly ModuleBuilder m_moduleBuilder;
private readonly string m_moduleName;
}
}