-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathComplexTypeSystem.cs
More file actions
1752 lines (1639 loc) · 76.8 KB
/
Copy pathComplexTypeSystem.cs
File metadata and controls
1752 lines (1639 loc) · 76.8 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ========================================================================
* 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.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Extensions.Logging;
using Opc.Ua.ComplexTypes;
namespace Opc.Ua.Client.ComplexTypes
{
/// <summary>
/// Manages the custom types of a server for a client session.
/// Loads the custom types into the type factory
/// of a client session, to allow for decoding and encoding
/// of custom enumeration types and structured types.
/// </summary>
/// <remarks>
/// Support for V1.03 dictionaries and all V1.04 data type definitions
/// with the following known restrictions:
/// - Support only for V1.03 structured types which can be mapped to the V1.04
/// structured type definition. Unsupported V1.03 types are ignored.
/// - Concrete Structure-backed sub-types of the abstract <c>OptionSet</c>
/// DataType are supported. UInteger-backed <c>IsOptionSet</c> DataTypes
/// are left opaque (their wire form is the plain unsigned integer).
/// </remarks>
public class ComplexTypeSystem
{
/// <summary>
/// an internal limit to prevent the retry
/// datatype loader mechanism to loop forever
/// </summary>
internal const int MaxLoopCount = 100;
/// <summary>
/// The data type systems that were loaded
/// </summary>
public NodeIdDictionary<DataDictionary> DataTypeSystem
=> m_complexTypeResolver.DataTypeSystem;
/// <summary>
/// Obsolete constructor
/// </summary>
[Obsolete("Use ComplexTypeSystem(IComplexTypeResolver, ITelemetryContext) instead.")]
public ComplexTypeSystem(IComplexTypeResolver complexTypeResolver)
// Telemetry is required by the modern ctor; this obsolete bridge forwards null!
// to preserve the resolver-only instantiation pattern.
: this(complexTypeResolver, (ITelemetryContext)null!)
{
}
/// <summary>
/// Obsolete constructor
/// </summary>
[Obsolete("Use ComplexTypeSystem(IComplexTypeResolver, IComplexTypeFactory, ITelemetryContext) instead.")]
public ComplexTypeSystem(
IComplexTypeResolver complexTypeResolver,
IComplexTypeFactory complexTypeBuilderFactory)
// Telemetry is required by the modern ctor; this obsolete bridge forwards null!.
: this(complexTypeResolver, complexTypeBuilderFactory, null!)
{
}
/// <summary>
/// Initializes the type system with a session to load the custom types.
/// </summary>
public ComplexTypeSystem(ISession session)
: this(session, session.MessageContext.Telemetry)
{
}
/// <summary>
/// Initializes the type system with a session to load the custom types.
/// </summary>
public ComplexTypeSystem(ISession session, ITelemetryContext telemetry)
: this(session, new DefaultComplexTypeFactory(), telemetry)
{
}
/// <summary>
/// Initializes the type system with a complex type resolver to load the custom types.
/// </summary>
public ComplexTypeSystem(
IComplexTypeResolver complexTypeResolver,
ITelemetryContext telemetry)
: this(complexTypeResolver, new DefaultComplexTypeFactory(), telemetry)
{
}
/// <summary>
/// Create complex type system with session and custom type builder factory
/// </summary>
public ComplexTypeSystem(
ISession session,
IComplexTypeFactory complexTypeBuilderFactory)
: this(session, complexTypeBuilderFactory, session.MessageContext.Telemetry)
{
}
/// <summary>
/// Initializes the type system with a session to load the custom types
/// and a customized type builder factory
/// </summary>
public ComplexTypeSystem(
ISession session,
IComplexTypeFactory complexTypeBuilderFactory,
ITelemetryContext telemetry)
: this(new NodeCacheResolver(session, telemetry), complexTypeBuilderFactory, telemetry)
{
}
/// <summary>
/// Initializes the type system with a complex type resolver to load the custom types.
/// </summary>
public ComplexTypeSystem(
IComplexTypeResolver complexTypeResolver,
IComplexTypeFactory complexTypeBuilderFactory,
ITelemetryContext telemetry)
{
m_complexTypeResolver = complexTypeResolver;
m_complexTypeBuilderFactory = complexTypeBuilderFactory;
m_logger = telemetry.CreateLogger<ComplexTypeSystem>();
}
/// <summary>
/// Load a single custom type with subtypes.
/// </summary>
/// <remarks>
/// Uses inverse references on the server to find the super type(s).
/// If the new structure contains a type dependency to a yet
/// unknown type, it loads also the dependent type(s).
/// For servers without DataTypeDefinition support, all
/// custom types are loaded.
/// </remarks>
public async Task<IType?> LoadTypeAsync(
ExpandedNodeId nodeId,
bool subTypes = false,
bool throwOnError = false,
CancellationToken ct = default)
{
try
{
// add fast path, if no subTypes are requested
if (!subTypes)
{
IType? systemType = GetSystemType(nodeId);
if (systemType != null)
{
return systemType;
}
}
// cache the server type system
_ = await m_complexTypeResolver
.LoadDataTypesAsync(DataTypeIds.BaseDataType, true, ct: ct)
.ConfigureAwait(false);
IList<INode> subTypeNodes = (await m_complexTypeResolver
.LoadDataTypesAsync(nodeId, subTypes, true, ct: ct)
.ConfigureAwait(false))
.ToList();
List<INode> subTypeNodesWithoutKnownTypes = RemoveKnownTypes(subTypeNodes);
if (subTypeNodesWithoutKnownTypes.Count > 0)
{
IList<INode> serverEnumTypes = [];
IList<INode> serverStructTypes = [];
foreach (INode node in subTypeNodesWithoutKnownTypes)
{
await AddEnumerationOrStructureTypeAsync(
node,
serverEnumTypes,
serverStructTypes,
ct)
.ConfigureAwait(false);
}
// load server types
if (DisableDataTypeDefinition ||
!await LoadBaseDataTypesAsync(serverEnumTypes, serverStructTypes, ct)
.ConfigureAwait(false))
{
if (!DisableDataTypeDictionary)
{
_ = await LoadDictionaryDataTypesAsync(serverEnumTypes, false, ct)
.ConfigureAwait(false);
}
}
}
// Commit the changes to the factory
m_complexTypeResolver.FactoryBuilder.Commit();
return GetSystemType(nodeId);
}
catch (Exception ex)
{
m_logger.LogError(ex, "Failed to load the custom type {NodeId}.", nodeId);
if (throwOnError)
{
throw;
}
return null;
}
}
/// <summary>
/// Load all custom types of a namespace.
/// </summary>
/// <remarks>
/// If a new type in the namespace contains a type dependency to an
/// unknown type in another namespace, it loads also the dependent type(s).
/// For servers without DataTypeDefinition support all
/// custom types are loaded.
/// </remarks>
/// <exception cref="ServiceResultException"></exception>
public async Task<bool> LoadNamespaceAsync(
string ns,
bool throwOnError = false,
CancellationToken ct = default)
{
try
{
int index = m_complexTypeResolver.NamespaceUris.GetIndex(ns);
if (index < 0)
{
throw new ServiceResultException(
$"Bad argument {ns}. Namespace not found.");
}
ushort nameSpaceIndex = (ushort)index;
_ = await m_complexTypeResolver
.LoadDataTypesAsync(DataTypeIds.BaseDataType, true, ct: ct)
.ConfigureAwait(false);
IList<INode> serverEnumTypes = (await m_complexTypeResolver
.LoadDataTypesAsync(DataTypeIds.Enumeration, ct: ct)
.ConfigureAwait(false)).ToList();
IList<INode> serverStructTypes = (await m_complexTypeResolver
.LoadDataTypesAsync(DataTypeIds.Structure, true, ct: ct)
.ConfigureAwait(false)).ToList();
// filter for namespace
serverEnumTypes = [.. serverEnumTypes.Where(
rd => rd.NodeId.NamespaceIndex == nameSpaceIndex)];
serverStructTypes = [.. serverStructTypes.Where(
rd => rd.NodeId.NamespaceIndex == nameSpaceIndex)];
// load types
bool allTypesLoaded;
if (DisableDataTypeDefinition ||
!await LoadBaseDataTypesAsync(serverEnumTypes, serverStructTypes, ct)
.ConfigureAwait(false))
{
if (DisableDataTypeDictionary)
{
return false;
}
allTypesLoaded = await LoadDictionaryDataTypesAsync(serverEnumTypes, false, ct)
.ConfigureAwait(false);
}
else
{
allTypesLoaded = true;
}
// Commit the changes to the factory
m_complexTypeResolver.FactoryBuilder.Commit();
return allTypesLoaded;
}
catch (Exception ex)
{
m_logger.LogError(ex, "Failed to load the custom type namespace {Namespace}.", ns);
if (throwOnError)
{
throw;
}
return false;
}
}
/// <summary>
/// <see cref="LoadAsync(bool, bool, CancellationToken)"/>
/// </summary>
[Obsolete("Use LoadAsync instead.")]
public Task<bool> Load(
bool onlyEnumTypes = false,
bool throwOnError = false,
CancellationToken ct = default)
{
return LoadAsync(onlyEnumTypes, throwOnError, ct).AsTask();
}
/// <summary>
/// Load all custom types from a server into the session system type factory.
/// </summary>
/// <remarks>
/// The loader follows the following strategy:
/// - Load all DataType nodes of the Enumeration subtypes.
/// - Load all DataType nodes of the Structure subtypes.
/// - Create all enumerated custom types using the DataTypeDefinion attribute, if available.
/// - Create all remaining enumerated custom types using the EnumValues or EnumStrings property, if available.
/// - Create all structured types using the DataTypeDefinion attribute, if available.
/// if there are type definitions remaining
/// - Load the binary schema dictionaries with type definitions.
/// - Create all remaining enumerated custom types using the dictionaries.
/// - Convert all structured types in the dictionaries to the DataTypeDefinion attribute, if possible.
/// - Create all structured types from the dictionaries using the converted DataTypeDefinion attribute.
/// </remarks>
/// <returns>true if all DataTypes were loaded.</returns>
public async ValueTask<bool> LoadAsync(
bool onlyEnumTypes = false,
bool throwOnError = false,
CancellationToken ct = default)
{
try
{
// load server types in cache
_ = await m_complexTypeResolver
.LoadDataTypesAsync(DataTypeIds.BaseDataType, true, ct: ct)
.ConfigureAwait(false);
IList<INode> serverEnumTypes = (await m_complexTypeResolver
.LoadDataTypesAsync(DataTypeIds.Enumeration, ct: ct)
.ConfigureAwait(false)).ToList();
IList<INode> serverStructTypes = onlyEnumTypes
? []
: (await m_complexTypeResolver
.LoadDataTypesAsync(DataTypeIds.Structure, true, ct: ct)
.ConfigureAwait(false)).ToList();
bool allTypesLoaded;
if (DisableDataTypeDefinition ||
!await LoadBaseDataTypesAsync(serverEnumTypes, serverStructTypes, ct)
.ConfigureAwait(false))
{
if (DisableDataTypeDictionary)
{
return false;
}
allTypesLoaded = await LoadDictionaryDataTypesAsync(serverEnumTypes, true, ct)
.ConfigureAwait(false);
}
else
{
allTypesLoaded = true;
}
// Commit the changes to the factory
m_complexTypeResolver.FactoryBuilder.Commit();
return allTypesLoaded;
}
catch (Exception ex)
{
m_logger.LogError(ex, "Failed to load the custom types.");
if (throwOnError)
{
throw;
}
return false;
}
}
/// <summary>
/// Get the types defined in this type system.
/// </summary>
public IReadOnlyList<XmlQualifiedName> GetDefinedTypes()
{
return [.. m_complexTypeBuilderFactory.GetTypes().Select(c => c.XmlName)];
}
/// <summary>
/// Returns data types node ids for everything that was defined.
/// </summary>
public IEnumerable<ExpandedNodeId> GetDefinedDataTypeIds()
{
return m_dataTypeDefinitionCache.Keys.Select(nodeId =>
NodeId.ToExpandedNodeId(nodeId, m_complexTypeResolver.NamespaceUris));
}
/// <summary>
/// Get the data type definition and dependent definitions for a data type node id.
/// Recursive through the cache to find all dependent types for structures fields
/// contained in the cache.
/// </summary>
public NodeIdDictionary<DataTypeDefinition> GetDataTypeDefinitionsForDataType(
ExpandedNodeId dataTypeId)
{
var dataTypeDefinitions = new NodeIdDictionary<DataTypeDefinition>();
var dataTypeNodeId = ExpandedNodeId.ToNodeId(
dataTypeId,
m_complexTypeResolver.NamespaceUris);
if (!dataTypeNodeId.IsNull)
{
CollectAllDataTypeDefinitions(dataTypeNodeId, dataTypeDefinitions);
}
return dataTypeDefinitions;
void CollectAllDataTypeDefinitions(
NodeId nodeId,
NodeIdDictionary<DataTypeDefinition> collect)
{
if (nodeId.IsNull)
{
return;
}
if (m_dataTypeDefinitionCache.TryGetValue(
nodeId,
out DataTypeDefinition? dataTypeDefinition))
{
collect[nodeId] = dataTypeDefinition;
if (dataTypeDefinition is StructureDefinition structureDefinition)
{
foreach (StructureField field in structureDefinition.Fields)
{
if (!IsRecursiveDataType(nodeId, field.DataType) &&
!collect.ContainsKey(field.DataType))
{
CollectAllDataTypeDefinitions(field.DataType, collect);
}
}
}
}
}
}
/// <summary>
/// Clear references in datatype cache.
/// </summary>
public void ClearDataTypeCache()
{
m_dataTypeDefinitionCache.Clear();
}
/// <summary>
/// Disable the use of DataTypeDefinition to create the complex type definition.
/// </summary>
public bool DisableDataTypeDefinition { get; set; }
/// <summary>
/// Disable the use of DataType Dictionaries to create the complex type definition.
/// </summary>
public bool DisableDataTypeDictionary { get; set; }
/// <summary>
/// Load listed custom types from dictionaries
/// into the sessions system type factory.
/// </summary>
/// <remarks>
/// Loads all custom types at this time to avoid
/// complexity when resolving type dependencies.
/// </remarks>
private async Task<bool> LoadDictionaryDataTypesAsync(
IList<INode> serverEnumTypes,
bool fullTypeList,
CancellationToken ct = default)
{
// build a type dictionary with all known new types
IList<INode> allEnumTypes = fullTypeList
? serverEnumTypes
: (await m_complexTypeResolver.LoadDataTypesAsync(DataTypeIds.Enumeration, ct: ct)
.ConfigureAwait(false)).ToList();
var typeDictionary = new Dictionary<XmlQualifiedName, NodeId>();
// strip known types from list
serverEnumTypes = RemoveKnownTypes(allEnumTypes);
// load the binary schema dictionaries from the server
IReadOnlyDictionary<NodeId, DataDictionary> typeSystem = await m_complexTypeResolver
.LoadDataTypeSystem(ct: ct)
.ConfigureAwait(false);
// sort dictionaries with import dependencies to the end of the list
var sortedTypeSystem = typeSystem.OrderBy(t => t.Value.TypeDictionary?.Import?.Length)
.ToList();
bool allTypesLoaded = true;
// create custom types for all dictionaries
foreach (KeyValuePair<NodeId, DataDictionary> dictionaryId in sortedTypeSystem)
{
try
{
DataDictionary dictionary = dictionaryId.Value;
if (dictionary.TypeDictionary == null ||
dictionary.TypeDictionary.Items == null)
{
continue;
}
string? targetDictionaryNamespace = dictionary.TypeDictionary.TargetNamespace;
// TargetNamespace is nullable on the imported XSD type; an OPC UA type
// dictionary always carries one when it reaches this code path.
int targetNamespaceIndex = m_complexTypeResolver.NamespaceUris
.GetIndex(targetDictionaryNamespace!);
var structureList = new List<Schema.Binary.TypeDescription>();
var enumList = new List<Schema.Binary.TypeDescription>();
// split into enumeration and structure types and sort
// types with dependencies to the end of the list.
SplitAndSortDictionary(dictionary, structureList, enumList);
// create assembly for all types in the same module
// See note above: targetDictionaryNamespace is required here.
IComplexTypeBuilder complexTypeBuilder = m_complexTypeBuilderFactory.Create(
targetDictionaryNamespace!,
targetNamespaceIndex,
dictionary.Name);
// Add all unknown enumeration types in dictionary
await AddEnumTypesAsync(
complexTypeBuilder,
typeDictionary,
enumList,
allEnumTypes,
serverEnumTypes,
ct)
.ConfigureAwait(false);
// handle structures
int loopCounter = 0;
int lastStructureCount = 0;
while (
structureList.Count > 0 &&
structureList.Count != lastStructureCount &&
loopCounter < MaxLoopCount)
{
loopCounter++;
lastStructureCount = structureList.Count;
var retryStructureList = new List<Schema.Binary.TypeDescription>();
// build structured types
foreach (Schema.Binary.TypeDescription item in structureList)
{
if (item is Schema.Binary.StructuredType structuredObject)
{
NodeId nodeId = dictionary.DataTypes
.FirstOrDefault(d => d.Value.Name == item.Name)
.Key;
if (nodeId.IsNull)
{
m_logger.LogError(
Utils.TraceMasks.Error,
"Skip the type definition of {DataType} because the data type node was not found.",
item.Name);
continue;
}
// find the data type node and the binary encoding id
(ExpandedNodeId typeId, ExpandedNodeId binaryEncodingId, DataTypeNode? dataTypeNode) =
await m_complexTypeResolver
.BrowseTypeIdsForDictionaryComponentAsync(nodeId, ct)
.ConfigureAwait(false);
if (dataTypeNode == null)
{
m_logger.LogError(
Utils.TraceMasks.Error,
"Skip the type definition of {DataType} because the data type node was not found.",
item.Name);
continue;
}
if (GetSystemType(typeId) != null)
{
XmlQualifiedName qName =
structuredObject.QName
?? new XmlQualifiedName(
structuredObject.Name,
targetDictionaryNamespace);
typeDictionary[qName] = ExpandedNodeId.ToNodeId(
typeId,
m_complexTypeResolver.NamespaceUris);
m_logger.LogInformation(
"Skip the type definition of {DataType} because the type already exists.",
item.Name);
continue;
}
// Use DataTypeDefinition attribute, if available (>=V1.04)
StructureDefinition? structureDefinition = null;
if (!DisableDataTypeDefinition)
{
structureDefinition = GetStructureDefinition(dataTypeNode);
}
if (structureDefinition == null)
{
try
{
// convert the binary schema description to a StructureDefinition
structureDefinition = structuredObject
.ToStructureDefinition(
binaryEncodingId,
typeDictionary,
m_complexTypeResolver.NamespaceUris,
dataTypeNode.NodeId);
}
catch (DataTypeNotSupportedException)
{
m_logger.LogError(
"Skipped the type definition of {DataType} because it is not supported.",
item.Name);
continue;
}
catch (ServiceResultException sre)
{
m_logger.LogError(
sre,
"Skip the type definition of {DataType}.",
item.Name);
continue;
}
}
List<ExpandedNodeId>? missingTypeIds = null;
IEncodeableType? complexType = null;
if (structureDefinition != null)
{
ArrayOf<NodeId> encodingIds;
ExpandedNodeId xmlEncodingId;
(encodingIds, binaryEncodingId, xmlEncodingId)
= await m_complexTypeResolver
.BrowseForEncodingsAsync(typeId, s_supportedEncodings, ct)
.ConfigureAwait(false);
try
{
// build the actual .NET structured type in assembly
(complexType, missingTypeIds)
= await AddStructuredTypeAsync(
complexTypeBuilder,
structureDefinition,
dataTypeNode.BrowseName,
typeId,
binaryEncodingId,
xmlEncodingId,
ct)
.ConfigureAwait(false);
}
catch (DataTypeNotSupportedException typeNotSupportedException)
{
m_logger.LogInformation(
typeNotSupportedException,
"Skipped the type definition of {DataType} because it is not supported.",
item.Name);
continue;
}
// Add new type to factory
if (complexType != null)
{
// match namespace and add new type to type factory
foreach (NodeId encodingId in encodingIds)
{
AddEncodeableType(encodingId, complexType);
}
AddEncodeableType(typeId, complexType);
XmlQualifiedName qName =
structuredObject.QName
?? new XmlQualifiedName(
structuredObject.Name,
targetDictionaryNamespace);
typeDictionary[qName] = ExpandedNodeId.ToNodeId(
typeId,
m_complexTypeResolver.NamespaceUris);
}
}
if (complexType == null)
{
retryStructureList.Add(item);
m_logger.LogTrace(
"Skipped the type definition of {DataType}, missing {MissingTypeIds}. Retry in next round.",
item.Name,
missingTypeIds == null ?
string.Empty :
string.Join(",", [.. missingTypeIds.Select(id => id.ToString())]));
}
}
}
structureList = retryStructureList;
}
allTypesLoaded = allTypesLoaded && structureList.Count == 0;
}
catch (ServiceResultException sre)
{
m_logger.LogError(
sre,
"Unexpected error processing ditionary {DictionaryName}.",
dictionaryId.Value.Name);
}
}
return allTypesLoaded;
}
/// <summary>
/// Load all custom types with DataTypeDefinition into the type factory.
/// </summary>
/// <returns>true if all types were loaded, false otherwise</returns>
private async Task<bool> LoadBaseDataTypesAsync(
IList<INode> serverEnumTypes,
IList<INode> serverStructTypes,
CancellationToken ct = default)
{
IList<INode> enumTypesToDoList = [];
IList<INode> structTypesToDoList = [];
bool repeatDataTypeLoad;
do
{
// strip known types
serverEnumTypes = RemoveKnownTypes(serverEnumTypes);
serverStructTypes = RemoveKnownTypes(serverStructTypes);
repeatDataTypeLoad = false;
try
{
enumTypesToDoList = await LoadBaseEnumDataTypesAsync(serverEnumTypes, ct)
.ConfigureAwait(false);
structTypesToDoList = await LoadBaseStructureDataTypesAsync(
serverStructTypes,
ct)
.ConfigureAwait(false);
}
catch (DataTypeNotFoundException dtnfex)
{
m_logger.LogWarning("Data type not found: {Message}", dtnfex.Message);
foreach (ExpandedNodeId nodeId in dtnfex.NodeIds.ToList())
{
// add missing types to list
INode? dataTypeNode = await m_complexTypeResolver.FindAsync(nodeId, ct)
.ConfigureAwait(false);
if (dataTypeNode != null)
{
await AddEnumerationOrStructureTypeAsync(
dataTypeNode,
serverEnumTypes,
serverStructTypes,
ct)
.ConfigureAwait(false);
repeatDataTypeLoad = true;
}
else
{
m_logger.LogWarning("Datatype {NodeId} was not found.", nodeId);
}
}
}
} while (repeatDataTypeLoad);
// all types loaded
if (enumTypesToDoList.Count == 0 && structTypesToDoList.Count == 0)
{
return true;
}
// Provide some diagnostics so users understand why types could not be serialized.
if (enumTypesToDoList.Count > 0)
{
m_logger.LogWarning(
"{TodoCount} enum types could not be loaded from the server.",
enumTypesToDoList.Count);
if (enumTypesToDoList.Count < 10)
{
m_logger.LogInformation(
"Missing enum types: {MissingEnumTypes}",
string.Join(", ", enumTypesToDoList.Select(e => e.BrowseName)));
}
}
if (structTypesToDoList.Count > 0)
{
m_logger.LogWarning(
"{TodoCount} structure types could not be loaded from the server.",
structTypesToDoList.Count);
if (structTypesToDoList.Count < 10)
{
m_logger.LogInformation(
"Missing structure types: {MissingStructureTypes}",
string.Join(", ", structTypesToDoList.Select(e => e.BrowseName)));
}
}
return false;
}
/// <summary>
/// Load all custom types with DataTypeDefinition into the type factory.
/// </summary>
/// <returns>true if all types were loaded, false otherwise</returns>
private async Task<IList<INode>> LoadBaseEnumDataTypesAsync(
IList<INode> serverEnumTypes,
CancellationToken ct = default)
{
// strip known types
serverEnumTypes = RemoveKnownTypes(serverEnumTypes);
// add new enum Types for all namespaces
var enumTypesToDoList = new List<INode>();
int namespaceCount = m_complexTypeResolver.NamespaceUris.Count;
// create enumeration types for all namespaces
for (uint i = 0; i < namespaceCount; i++)
{
IComplexTypeBuilder? complexTypeBuilder = null;
var enumTypes = serverEnumTypes.Where(node => node.NodeId.NamespaceIndex == i)
.ToList();
if (enumTypes.Count != 0)
{
if (complexTypeBuilder == null)
{
string? targetNamespace = m_complexTypeResolver.NamespaceUris.GetString(i);
// GetString returns null only for unknown indexes; namespace index i
// is iterated over the live NamespaceUris collection so a registered
// namespace always exists at this index.
complexTypeBuilder = m_complexTypeBuilderFactory.Create(
targetNamespace!,
(int)i);
}
foreach (INode enumType in enumTypes)
{
IEnumeratedType? newType = await AddEnumTypeAsync(
complexTypeBuilder,
enumType as DataTypeNode,
ct)
.ConfigureAwait(false);
if (newType != null)
{
// match namespace and add to type factory
AddEncodeableType(enumType.NodeId, newType);
}
else
{
enumTypesToDoList.Add(enumType);
}
}
}
}
// all types loaded, return remaining
return enumTypesToDoList;
}
/// <summary>
/// Load all structure custom types with DataTypeDefinition into the type factory.
/// </summary>
/// <returns>true if all types were loaded, false otherwise</returns>
private async Task<IList<INode>> LoadBaseStructureDataTypesAsync(
IList<INode> serverStructTypes,
CancellationToken ct = default)
{
// strip known types
serverStructTypes = RemoveKnownTypes(serverStructTypes);
// add new enum Types for all namespaces
int namespaceCount = m_complexTypeResolver.NamespaceUris.Count;
bool retryAddStructType;
var structTypesToDoList = new List<INode>();
IList<INode> structTypesWorkList = serverStructTypes;
// allow the loader to cache the encodings
ArrayOf<ExpandedNodeId> nodeIds = [.. serverStructTypes.Select(n => n.NodeId)];
_ = await m_complexTypeResolver
.BrowseForEncodingsAsync(nodeIds, s_supportedEncodings, ct)
.ConfigureAwait(false);
// create structured types for all namespaces
int loopCounter = 0;
do
{
loopCounter++;
retryAddStructType = false;
for (uint i = 0; i < namespaceCount; i++)
{
IComplexTypeBuilder? complexTypeBuilder = null;
var structTypes = structTypesWorkList.Where(
node => node.NodeId.NamespaceIndex == i).ToList();
if (structTypes.Count != 0)
{
if (complexTypeBuilder == null)
{
string? targetNamespace = m_complexTypeResolver.NamespaceUris
.GetString(i);
// GetString returns null only for unknown indexes; namespace index i
// iterates over the live NamespaceUris collection so a registered
// namespace always exists at this index.
complexTypeBuilder = m_complexTypeBuilderFactory.Create(
targetNamespace!,
(int)i);
}
foreach (INode? structType in structTypes)
{
IType? newType = null;
if (structType is not DataTypeNode dataTypeNode ||
dataTypeNode.IsAbstract)
{
continue;
}
StructureDefinition? structureDefinition = GetStructureDefinition(
dataTypeNode);
if (structureDefinition != null)
{
(
ArrayOf<NodeId> encodingIds,
ExpandedNodeId binaryEncodingId,
ExpandedNodeId xmlEncodingId
) = await m_complexTypeResolver
.BrowseForEncodingsAsync(
structType.NodeId,
s_supportedEncodings,
ct)
.ConfigureAwait(false);
try
{
ExpandedNodeId typeId = NormalizeExpandedNodeId(
structType.NodeId);
List<ExpandedNodeId>? missingTypeIds;
(newType, missingTypeIds) = await AddStructuredTypeAsync(
complexTypeBuilder,
structureDefinition,
dataTypeNode.BrowseName,
typeId,
binaryEncodingId,
xmlEncodingId,
ct)
.ConfigureAwait(false);
if (missingTypeIds?.Count > 0)
{
var missingTypeIdsFromWorkList
= new List<ExpandedNodeId>();
foreach (ExpandedNodeId missingTypeId in missingTypeIds)
{
INode? typeMatch = structTypesWorkList
.FirstOrDefault(n =>
n.NodeId == missingTypeId);
if (typeMatch == null)
{
missingTypeIdsFromWorkList.Add(missingTypeId);
}
}
foreach (ExpandedNodeId id in missingTypeIdsFromWorkList)
{
if (!structTypesToDoList.Any(n => n.NodeId == id))
{
INode? todo = await m_complexTypeResolver.FindAsync(id, ct)
.ConfigureAwait(false);
if (todo != null)
{
structTypesToDoList.Add(todo);
retryAddStructType = true;
}
}
else
{
retryAddStructType = true;
}
}
}
}
catch (DataTypeNotSupportedException)
{
m_logger.LogError(
"Skipped the type definition of {DataType} because it is not supported.",
dataTypeNode.BrowseName.Name);
}
catch
{
// creating the new type failed, likely a missing dependency, retry later
retryAddStructType = true;
}
if (newType != null)
{
foreach (NodeId encodingId in encodingIds)
{
AddEncodeableType(encodingId, newType);
}
AddEncodeableType(structType.NodeId, newType);
}