-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathEncoderCommon.cs
More file actions
1118 lines (1015 loc) · 40.5 KB
/
Copy pathEncoderCommon.cs
File metadata and controls
1118 lines (1015 loc) · 40.5 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/
* ======================================================================*/
// CA2000: test code; many disposables are ownership-transferred to test fixtures or short-lived,
// making CA2000 noisy without a real leak risk. Disabled file-level for the suite.
#pragma warning disable CA2000
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading;
using System.Xml;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using Opc.Ua.Bindings;
using Opc.Ua.Test;
using Opc.Ua.Tests;
namespace Opc.Ua.Core.TestFramework
{
/// <summary>
/// Supported memory stream types.
/// </summary>
public enum MemoryStreamType
{
MemoryStream,
ArraySegmentStream
}
/// <summary>
/// Base class for the encoder tests.
/// </summary>
[TestFixture]
[Category("Encoder")]
[SetCulture("en-us")]
public abstract class EncoderCommon
{
protected const int kArrayRepeats = 3;
protected const int kRandomStart = 4840;
protected const int kRandomRepeats = 100;
protected const int kMaxArrayLength = 1024 * 64;
protected const int kTestBlockSize = 0x1000;
protected const string kApplicationUri = "uri:localhost:opcfoundation.org:EncoderCommon";
private static readonly JsonSerializerOptions s_prettifyOptions = new()
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
AllowTrailingCommas = true
};
/// <summary>
/// Diagnostic output for the test that is currently running. Only written
/// out when the test does not pass.
/// </summary>
/// <remarks>
/// The encoder tests dump the input, the encoded payload and the decoded
/// result of every case, which is what makes a failure diagnosable. There
/// are however thousands of cases, and the NUnit adapter forwards each
/// captured line to the test runner as an individual message over the
/// socket it shares with the test host. Emitting them unconditionally
/// produced roughly 500 MB of output per run of the encoder suite, which
/// throttled the run, made its published results a 164 MB artifact, and
/// eventually wedged that socket: the run then hung with no output at all
/// until the CI job timed out (issue #4213). Buffering the dumps and
/// writing them only when they are actually read - on a failure - keeps
/// the diagnostics without the flood.
/// </remarks>
protected TextWriter TestOutput { get; private set; }
protected RandomSource RandomSource { get; private set; }
protected DataGenerator DataGenerator { get; private set; }
protected IServiceMessageContext Context { get; private set; }
protected NamespaceTable NameSpaceUris { get; private set; }
protected StringTable ServerUris { get; private set; }
protected BufferManager BufferManager { get; private set; }
protected ITelemetryContext Telemetry { get; private set; }
[OneTimeSetUp]
protected void OneTimeSetUp()
{
Telemetry = NUnitTelemetryContext.Create();
Context = new ServiceMessageContext(Telemetry, EncodeableFactory.Create())
{
MaxArrayLength = kMaxArrayLength
};
NameSpaceUris = Context.NamespaceUris;
// namespace index 1 must be the ApplicationUri
NameSpaceUris.GetIndexOrAppend(kApplicationUri);
NameSpaceUris.GetIndexOrAppend(Namespaces.OpcUaGds);
ServerUris = new StringTable();
BufferManager = new BufferManager(nameof(EncoderCommon), kTestBlockSize, Telemetry);
}
[OneTimeTearDown]
protected void OneTimeTearDown()
{
}
[SetUp]
protected void SetUp()
{
// One writer per fixture over the reused buffer; the buffer, not the
// writer, carries the per-test state.
TestOutput ??= new StringWriter(m_testOutput, CultureInfo.CurrentCulture);
m_testOutput.Clear();
// ensure tests are reproducible, reset for every test
RandomSource = new RandomSource(kRandomStart);
DataGenerator = new DataGenerator(RandomSource, Telemetry);
}
[TearDown]
protected void TearDown()
{
FlushTestOutput();
// ensure after every test that the Null NodeId was not modified
Assert.That(NodeId.Null.IsNull, Is.True);
}
/// <summary>
/// Hand the buffered diagnostics to NUnit when the test did not pass, and
/// drop them otherwise. See <see cref="TestOutput"/> for why they are not
/// written as they are produced.
/// </summary>
private void FlushTestOutput()
{
if (m_testOutput.Length != 0 &&
TestContext.CurrentContext.Result.Outcome.Status != TestStatus.Passed)
{
TestContext.Out.Write(m_testOutput.ToString());
}
m_testOutput.Clear();
}
/// <summary>
/// Ensure repeated tests get different seed.
/// </summary>
protected void SetRepeatedRandomSeed()
{
int randomSeed = TestContext.CurrentContext.CurrentRepeatCount + kRandomStart;
RandomSource = new RandomSource(randomSeed);
DataGenerator = new DataGenerator(RandomSource, Telemetry);
}
/// <summary>
/// Ensure tests are reproducible with same seed.
/// </summary>
protected void SetRandomSeed(int randomSeed)
{
RandomSource = new RandomSource(randomSeed + kRandomStart);
DataGenerator = new DataGenerator(RandomSource, Telemetry);
}
[DatapointSource]
public static readonly BuiltInType[] BuiltInTypes =
#if NET8_0_OR_GREATER && !NET_STANDARD_TESTS
[
.. Enum.GetValues<BuiltInType>()
#else
[
.. Enum.GetValues(typeof(BuiltInType))
.Cast<BuiltInType>()
#endif
.Where(b =>
b
is not BuiltInType.Variant
and not BuiltInType.DiagnosticInfo
and not BuiltInType.DataValue
and (< BuiltInType.Number or > BuiltInType.UInteger))
];
[DatapointSource]
public static readonly EncodingType[] EncoderTypes =
#if NET8_0_OR_GREATER && !NET_STANDARD_TESTS
Enum.GetValues<EncodingType>();
#else
(EncodingType[])Enum.GetValues(typeof(EncodingType));
#endif
public static readonly EncodingTypeGroup[] EncodingTypesJson =
[
new EncodingTypeGroup(EncodingType.Json, JsonEncodingType.Compact),
new EncodingTypeGroup(EncodingType.Json, JsonEncodingType.Verbose)
];
public static readonly EncodingTypeGroup[] EncodingTypesJsonVerbose =
[
new EncodingTypeGroup(EncodingType.Json, JsonEncodingType.Verbose)
];
public static readonly EncodingTypeGroup[] EncodingTypesJsonBinaryXmlAndJsonCompact =
[
new EncodingTypeGroup(EncodingType.Binary),
new EncodingTypeGroup(EncodingType.Xml, useXmlParser: false),
new EncodingTypeGroup(EncodingType.Xml, useXmlParser: true),
new EncodingTypeGroup(EncodingType.Json, JsonEncodingType.Compact)
];
public static readonly EncodingTypeGroup[] EncodingTypesAll =
[
new EncodingTypeGroup(EncodingType.Binary),
new EncodingTypeGroup(EncodingType.Xml, useXmlParser: false),
new EncodingTypeGroup(EncodingType.Xml, useXmlParser: true),
new EncodingTypeGroup(EncodingType.Json, JsonEncodingType.Compact),
new EncodingTypeGroup(EncodingType.Json, JsonEncodingType.Verbose)
];
/// <summary>
/// Encode data value and return encoded string.
/// </summary>
protected string EncodeDataValue(
EncodingType encoderType,
BuiltInType builtInType,
MemoryStreamType memoryStreamType,
Variant data,
JsonEncodingType encoding)
{
string encodeInfo = $"Encoder: {encoderType} Type:{builtInType} Encoding:{encoding}";
TestOutput.WriteLine(encodeInfo);
TestOutput.WriteLine(data);
DataValue expected = CreateDataValue(data);
TestOutput.WriteLine("Expected:");
TestOutput.WriteLine(expected);
Assert.That(expected.IsNull, Is.False, "Expected DataValue is Null, " + encodeInfo);
using MemoryStream encoderStream = CreateEncoderMemoryStream(memoryStreamType);
using (IEncoder encoder = CreateEncoder(
encoderType,
Context,
encoderStream,
typeof(DataValue),
encoding))
{
encoder.WriteDataValue("DataValue", expected);
}
byte[] buffer = encoderStream.ToArray();
return Encoding.UTF8.GetString(buffer);
}
/// <summary>
/// Encode and decode a DataValue,
/// validate the result against the input data.
/// </summary>
protected void EncodeDecodeDataValue(
EncodingType encoderType,
JsonEncodingType jsonEncodingType,
bool useXmlParser,
BuiltInType builtInType,
MemoryStreamType memoryStreamType,
Variant data)
{
string encodeInfo = $"Encoder: {encoderType} Type:{builtInType}";
TestOutput.WriteLine(encodeInfo);
TestOutput.WriteLine(data);
DataValue expected = CreateDataValue(data);
Assert.That(expected.IsNull, Is.False, "Expected DataValue is Null, " + encodeInfo);
string formatted = null;
DataValue result = default;
try
{
byte[] buffer;
using (MemoryStream encoderStream = CreateEncoderMemoryStream(memoryStreamType))
{
using (
IEncoder encoder = CreateEncoder(
encoderType,
Context,
encoderStream,
typeof(DataValue),
jsonEncodingType))
{
encoder.WriteDataValue("DataValue", expected);
}
buffer = encoderStream.ToArray();
}
switch (encoderType)
{
case EncodingType.Json:
formatted = PrettifyAndValidateJson(buffer);
break;
case EncodingType.Xml:
formatted = PrettifyAndValidateXml(buffer);
break;
}
using (var decoderStream = new MemoryStream(buffer))
using (IDecoder decoder = CreateDecoder(
encoderType,
useXmlParser,
Context,
decoderStream,
typeof(DataValue)))
{
result = decoder.ReadDataValue("DataValue");
}
Assert.That(result.IsNull, Is.False, "Resulting DataValue is Null, " + encodeInfo);
Assert.That(result, Is.EqualTo(expected), encodeInfo);
Assert.That(
Utils.IsEqual(expected, result),
Is.True,
"Opc.Ua.Utils.IsEqual failed to compare expected and result. " + encodeInfo);
}
catch
{
TestOutput.WriteLine("Expected:");
TestOutput.WriteLine(expected);
if (formatted != null)
{
TestOutput.WriteLine("Encoded:");
TestOutput.WriteLine(formatted);
}
TestOutput.WriteLine("Result:");
if (!result.IsNull)
{
TestOutput.WriteLine(result);
}
}
}
/// <summary>
/// Encode and decode Variant, validate result.
/// </summary>
protected void EncodeDecode(
EncodingType encoderType,
JsonEncodingType jsonEncodingType,
bool useXmlParser,
BuiltInType builtInType,
MemoryStreamType memoryStreamType,
Variant expected)
{
string formatted = null;
Variant result = default;
try
{
string encodeInfo = $"Encoder: {encoderType} Type:{builtInType}";
IBuiltInType type = TypeInfo.GetSystemType(builtInType);
TestOutput.WriteLine(encodeInfo);
byte[] buffer;
using (MemoryStream encoderStream = CreateEncoderMemoryStream(memoryStreamType))
{
using (
IEncoder encoder = CreateEncoder(
encoderType,
Context,
encoderStream,
type?.Type,
jsonEncodingType))
{
encoder.WriteVariantValue(builtInType.ToString(), expected);
}
buffer = encoderStream.ToArray();
}
switch (encoderType)
{
case EncodingType.Json:
formatted = PrettifyAndValidateJson(buffer);
break;
case EncodingType.Xml:
formatted = PrettifyAndValidateXml(buffer);
break;
default:
formatted = Encoding.UTF8.GetString(buffer);
break;
}
using (var decoderStream = new MemoryStream(buffer))
using (IDecoder decoder = CreateDecoder(
encoderType,
useXmlParser,
Context,
decoderStream,
type?.Type))
{
result = decoder.ReadVariantValue(
builtInType.ToString(),
expected.TypeInfo);
}
Assert.That(result, Is.EqualTo(expected), encodeInfo);
}
catch
{
// only print infos if test fails, to reduce log output
TestOutput.WriteLine("Expected:");
TestOutput.WriteLine(expected);
TestOutput.WriteLine("Result:");
TestOutput.WriteLine(result);
if (formatted != null)
{
TestOutput.WriteLine("Encoded:");
TestOutput.WriteLine(formatted);
}
throw;
}
}
/// <summary>
/// Encode Variant as JSON and validate against expected JSON string.
/// </summary>
protected void EncodeJsonVerifyResult(
BuiltInType builtInType,
MemoryStreamType memoryStreamType,
Variant data,
JsonEncodingType jsonEncoding,
string expected)
{
string result = null;
string formattedResult = null;
try
{
string encodeInfo = $"Encoder: Json Type:{builtInType} Encoding: {jsonEncoding}";
TestOutput.WriteLine(encodeInfo);
if (!string.IsNullOrEmpty(expected))
{
expected = $"{{\"{builtInType}\":" + expected + "}";
}
else
{
expected = "{}";
}
byte[] buffer;
using (MemoryStream encoderStream = CreateEncoderMemoryStream(memoryStreamType))
{
using (
IEncoder encoder = CreateEncoder(
EncodingType.Json,
Context,
encoderStream,
typeof(DataValue),
jsonEncoding))
{
if (builtInType == BuiltInType.Variant)
{
encoder.WriteVariant(builtInType.ToString(), data);
}
else
{
encoder.WriteVariantValue(builtInType.ToString(), data);
}
}
buffer = encoderStream.ToArray();
}
TestOutput.WriteLine("Result:");
result = Encoding.UTF8.GetString(buffer);
formattedResult = PrettifyAndValidateJson(result);
var resultParsed = JsonNode.Parse(result,
documentOptions: new JsonDocumentOptions { AllowTrailingCommas = true });
var expectedParsed = JsonNode.Parse(expected,
documentOptions: new JsonDocumentOptions { AllowTrailingCommas = true });
bool areEqual = JsonNode.DeepEquals(expectedParsed, resultParsed);
Assert.That(areEqual, Is.True, encodeInfo);
}
catch
{
TestOutput.WriteLine("Data:");
TestOutput.WriteLine(data);
TestOutput.WriteLine("Expected:");
string formattedExpected = PrettifyAndValidateJson(expected);
TestOutput.WriteLine(formattedExpected);
TestOutput.WriteLine("Result:");
if (!string.IsNullOrEmpty(formattedResult))
{
TestOutput.WriteLine(formattedResult);
}
else
{
TestOutput.WriteLine(result);
}
throw;
}
}
/// <summary>
/// Format and validate a XML document string.
/// </summary>
protected string PrettifyAndValidateXml(byte[] xml, bool outputFormatted = false)
{
try
{
using var reader = new MemoryStream(xml);
using var xmlReader = XmlReader.Create(reader, Utils.DefaultXmlReaderSettings());
var document = new XmlDocument();
document.Load(xmlReader);
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Indent = true,
NewLineOnAttributes = true
};
var stringBuilder = new StringBuilder();
using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
{
document.Save(xmlWriter);
}
string formattedXml = stringBuilder.ToString();
if (outputFormatted)
{
TestContext.Out.WriteLine(formattedXml);
}
return formattedXml;
}
catch (Exception ex)
{
TestContext.Out.WriteLine(xml);
Assert.Fail("Invalid xml data: " + ex.Message);
}
return Encoding.UTF8.GetString(xml);
}
/// <summary>
/// Format binary data
/// </summary>
public static string PrettifyAndValidateBinary(byte[] buffer, bool outputFormatted = false)
{
return CoreUtils.ToHexString(buffer);
}
/// <summary>
/// Format and validate a JSON string.
/// </summary>
public static string PrettifyAndValidateJson(byte[] json, bool outputFormatted = false)
{
return PrettifyAndValidateJson(Encoding.UTF8.GetString(json), outputFormatted);
}
/// <summary>
/// Format and validate a JSON string.
/// </summary>
public static string PrettifyAndValidateJson(string json, bool outputFormatted = false)
{
try
{
var jsonDocument = JsonDocument.Parse(json,
new JsonDocumentOptions { AllowTrailingCommas = true });
string formattedJson = JsonSerializer.Serialize(jsonDocument, s_prettifyOptions);
if (outputFormatted)
{
TestContext.Out.WriteLine(formattedJson);
}
return formattedJson;
}
catch (Exception ex)
{
TestContext.Out.WriteLine(json);
Assert.Fail("Invalid json data: " + ex.Message);
}
return json;
}
/// <summary>
/// Returns various implementations of a memory stream.
/// </summary>
/// <returns>A MemoryStream</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
protected MemoryStream CreateEncoderMemoryStream(MemoryStreamType memoryStreamType)
{
switch (memoryStreamType)
{
case MemoryStreamType.MemoryStream:
return new MemoryStream(kTestBlockSize);
case MemoryStreamType.ArraySegmentStream:
return new ArraySegmentStream(BufferManager);
default:
throw new ArgumentOutOfRangeException(
nameof(memoryStreamType),
memoryStreamType,
"Invalid MemoryStreamType specified.");
}
}
/// <summary>
/// Encoder factory for all encoding types.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
protected IEncoder CreateEncoder(
EncodingType encoderType,
IServiceMessageContext context,
Stream stream,
Type systemType,
JsonEncodingType jsonEncoding = JsonEncodingType.Verbose)
{
switch (encoderType)
{
case EncodingType.Binary:
return new BinaryEncoder(stream, context, true);
case EncodingType.Xml:
var xmlWriter = XmlWriter.Create(stream, Utils.DefaultXmlWriterSettings());
return new XmlEncoder(systemType, xmlWriter, context);
case EncodingType.Json:
return new JsonEncoder(
stream,
context,
jsonEncoding == JsonEncodingType.Verbose ? JsonEncoderOptions.Verbose : JsonEncoderOptions.Compact);
default:
throw new ArgumentOutOfRangeException(
nameof(encoderType),
encoderType,
"Invalid EncoderType specified.");
}
}
/// <summary>
/// Decoder factory for all decoding types.
/// </summary>
protected IDecoder CreateDecoder(
EncodingType decoderType,
bool useXmlParser,
IServiceMessageContext context,
Stream stream,
Type systemType)
{
switch (decoderType)
{
case EncodingType.Binary:
return new BinaryDecoder(stream, context);
case EncodingType.Xml when useXmlParser:
return new XmlParser(systemType, stream, context);
case EncodingType.Xml:
var xmlReader = XmlReader.Create(stream, Utils.DefaultXmlReaderSettings());
return new XmlDecoder(systemType, xmlReader, context);
case EncodingType.Json:
return new JsonDecoder(stream, context);
default:
return null;
}
}
/// <summary>
/// Wrap Variant in a DataValue.
/// </summary>
protected DataValue CreateDataValue(Variant variant)
{
StatusCode statusCode = DataGenerator.GetRandomStatusCode();
DateTimeUtc sourceTimeStamp = DataGenerator.GetRandomDateTime();
return new DataValue(variant, statusCode, sourceTimeStamp, DateTime.UtcNow);
}
/// <summary>
/// Helper to add escaped quotes to a string.
/// </summary>
protected static string Quotes(string json)
{
return "\"" + json + "\"";
}
/// <summary>
/// Return true if system Type is IEncodeable.
/// </summary>
protected static bool IsEncodeableType(Type systemType)
{
if (systemType == null)
{
return false;
}
System.Reflection.TypeInfo systemTypeInfo = systemType.GetTypeInfo();
if (systemTypeInfo.IsAbstract ||
!typeof(IEncodeable).GetTypeInfo().IsAssignableFrom(systemTypeInfo) ||
typeof(Encoders.Structure).IsAssignableFrom(systemType))
{
return false;
}
return Activator.CreateInstance(systemType) is IEncodeable;
}
/// <summary>
/// Calculates the number of elements from a dimension array.
/// </summary>
protected static int ElementsFromDimension(int[] dimensions)
{
int elements = 1;
for (int i = 0; i < dimensions.Length; i++)
{
if (dimensions[i] != 0)
{
elements *= dimensions[i];
}
}
return elements;
}
/// <summary>
/// Sets random array dimensions between 2 and 10.
/// Number of total elements is limited by <see cref="kMaxArrayLength"/>
/// </summary>
protected void SetMatrixDimensions(int[] dimensions)
{
int totalElements = 1;
for (int i = 0; i < dimensions.Length; i++)
{
dimensions[i] = RandomSource.NextInt32(8) + 2;
totalElements *= dimensions[i];
}
while (totalElements > kMaxArrayLength)
{
int random = RandomSource.NextInt32(dimensions.Length - 1);
if (dimensions[random] > 1)
{
dimensions[random]--;
}
totalElements = 1;
for (int i = 0; i < dimensions.Length; i++)
{
totalElements *= dimensions[i];
}
}
}
private readonly StringBuilder m_testOutput = new();
protected enum TestEnumType
{
[EnumMember(Value = "One_1")]
One = 1,
[EnumMember(Value = "Two_2")]
Two = 2,
[EnumMember(Value = "Three_3")]
Three = 3,
[EnumMember(Value = "Ten_10")]
Ten = 10,
[EnumMember(Value = "Hundred_100")]
Hundred = 100
}
protected class FooBarEncodeable : IEncodeable, IDisposable
{
private static int s_count;
public FooBarEncodeable()
{
m_resetCounter = true;
Count = Interlocked.Increment(ref s_count);
Foo = $"bar_{Count}";
FieldName = nameof(Foo);
}
public FooBarEncodeable(int count)
{
Count = count;
Foo = $"bar_{Count}";
FieldName = nameof(Foo);
}
public FooBarEncodeable(string foo)
{
Foo = foo;
FieldName = nameof(Foo);
}
public FooBarEncodeable(string fieldname, string foo)
{
Foo = foo;
FieldName = fieldname;
}
public string Foo { get; set; }
public string FieldName { get; set; }
public int Count { get; set; }
public ExpandedNodeId TypeId { get; }
public ExpandedNodeId BinaryEncodingId { get; }
public ExpandedNodeId XmlEncodingId { get; }
public void Encode(IEncoder encoder)
{
encoder.PushNamespace(kApplicationUri);
encoder.WriteString(FieldName, Foo);
encoder.PopNamespace();
}
public void Decode(IDecoder decoder)
{
decoder.PushNamespace(kApplicationUri);
Foo = decoder.ReadString(FieldName);
decoder.PopNamespace();
}
public bool IsEqual(IEncodeable encodeable)
{
if (encodeable is FooBarEncodeable de)
{
return Foo == de.Foo;
}
return false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && m_resetCounter)
{
s_count = 0;
}
// free unmanaged resources
}
public virtual object Clone()
{
return MemberwiseClone();
}
public new object MemberwiseClone()
{
return new FooBarEncodeable(FieldName, Foo) { Count = Count };
}
private readonly bool m_resetCounter;
}
/// <summary>
/// A simple dynamic encodeable that can handle arbitrary fields of type string
/// </summary>
protected class DynamicEncodeable :
IEncodeable,
IDisposable,
IDynamicComplexTypeInstance
{
private static int s_count;
public DynamicEncodeable()
{
}
public DynamicEncodeable(
string xmlName,
string xmlNamespace,
ExpandedNodeId typeId,
ExpandedNodeId binaryEncodingId,
ExpandedNodeId xmlEncodingId)
: this(
xmlName,
xmlNamespace,
typeId,
binaryEncodingId,
xmlEncodingId,
(Dictionary<string, (int, string)>)null)
{
m_resetCounter = true;
Count = Interlocked.Increment(ref s_count);
m_fields = new Dictionary<string, (int, string)> { { "Foo", (1, $"bar_{Count}") } };
}
public DynamicEncodeable(
string xmlName,
string xmlNamespace,
ExpandedNodeId typeId,
ExpandedNodeId binaryEncodingId,
ExpandedNodeId xmlEncodingId,
int count)
: this(
xmlName,
xmlNamespace,
typeId,
binaryEncodingId,
xmlEncodingId,
new Dictionary<string, (int, string)> { { "Foo", (1, $"bar_{count}") } })
{
Count = count;
}
public DynamicEncodeable(
string xmlName,
string xmlNamespace,
ExpandedNodeId typeId,
ExpandedNodeId binaryEncodingId,
ExpandedNodeId xmlEncodingId,
string foo)
: this(
xmlName,
xmlNamespace,
typeId,
binaryEncodingId,
xmlEncodingId,
new Dictionary<string, (int, string)> { { "Foo", (1, foo) } })
{
}
public DynamicEncodeable(
string xmlName,
string xmlNamespace,
ExpandedNodeId typeId,
ExpandedNodeId binaryEncodingId,
ExpandedNodeId xmlEncodingId,
Dictionary<string, (int, string)> fields)
{
m_xmlName = xmlName;
m_xmlNamespace = xmlNamespace;
TypeId = typeId;
BinaryEncodingId = binaryEncodingId;
XmlEncodingId = xmlEncodingId;
m_fields = fields;
}
public int Count { get; set; }
public ExpandedNodeId TypeId { get; set; }
public ExpandedNodeId BinaryEncodingId { get; set; }
public ExpandedNodeId XmlEncodingId { get; set; }
public void Encode(IEncoder encoder)
{
InitializeFromFactory(encoder.Context?.Factory);
encoder.PushNamespace(m_xmlNamespace);
foreach (
KeyValuePair<string, (int FieldOrder, string Value)> field in m_fields
.OrderBy(kv => kv.Value.FieldOrder)
.ToList())
{
encoder.WriteString(field.Key, field.Value.Value);
}
encoder.PopNamespace();
}
public void Decode(IDecoder decoder)
{
InitializeFromFactory(decoder.Context?.Factory);
decoder.PushNamespace(m_xmlNamespace);
foreach (
KeyValuePair<string, (int FieldOrder, string Value)> fieldKV in m_fields
.OrderBy(kv => kv.Value.FieldOrder)
.ToList())
{
m_fields[fieldKV.Key] = (fieldKV.Value.FieldOrder, decoder.ReadString(
fieldKV.Key));
}
decoder.PopNamespace();
}
private void InitializeFromFactory(IEncodeableFactory factory)
{
if (m_fields == null)
{
// When the dynamic encodeable is instantiated by a encoder/decoder,
// it needs to find it's type information
// Obtain a previously registered instance from the Factory
// Other systems will want to put just type information into the factory,
// or have other means of finding type information given an encoding id
DynamicEncodeable encodeable = factory is DynamicEncodeableFactory df
? df.GetDynamicEncodeableForEncoding(TypeId)
: null;
// Read the type information
TypeId = encodeable?.TypeId ?? default;
XmlEncodingId = encodeable?.XmlEncodingId ?? default;
BinaryEncodingId = encodeable?.BinaryEncodingId ?? default;