-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathObjectSerializer.cs
More file actions
5923 lines (5169 loc) · 181 KB
/
ObjectSerializer.cs
File metadata and controls
5923 lines (5169 loc) · 181 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
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
#if COMPILED
using System.Runtime.Loader;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
#endif
using Waher.Events;
using Waher.Persistence.Attributes;
using Waher.Persistence.Exceptions;
using Waher.Persistence.Serialization.Model;
using Waher.Runtime.Inventory;
using Waher.Runtime.Threading;
using Waher.Script.Abstraction.Elements;
using Waher.Runtime.Collections;
namespace Waher.Persistence.Serialization
{
/// <summary>
/// Serializes a class, taking into account attributes defined in <see cref="Attributes"/>.
/// </summary>
public class ObjectSerializer : IObjectSerializer
{
/// <summary>
/// Represents a <see cref="Boolean"/>
/// </summary>
public const uint TYPE_BOOLEAN = 0;
/// <summary>
/// Represents a <see cref="Byte"/>
/// </summary>
public const uint TYPE_BYTE = 1;
/// <summary>
/// Represents a <see cref="Int16"/>
/// </summary>
public const uint TYPE_INT16 = 2;
/// <summary>
/// Represents a <see cref="Int32"/>
/// </summary>
public const uint TYPE_INT32 = 3;
/// <summary>
/// Represents a <see cref="Int64"/>
/// </summary>
public const uint TYPE_INT64 = 4;
/// <summary>
/// Represents a <see cref="SByte"/>
/// </summary>
public const uint TYPE_SBYTE = 5;
/// <summary>
/// Represents a <see cref="UInt16"/>
/// </summary>
public const uint TYPE_UINT16 = 6;
/// <summary>
/// Represents a <see cref="UInt32"/>
/// </summary>
public const uint TYPE_UINT32 = 7;
/// <summary>
/// Represents a <see cref="UInt64"/>
/// </summary>
public const uint TYPE_UINT64 = 8;
/// <summary>
/// Represents a <see cref="Decimal"/>
/// </summary>
public const uint TYPE_DECIMAL = 9;
/// <summary>
/// Represents a <see cref="Double"/>
/// </summary>
public const uint TYPE_DOUBLE = 10;
/// <summary>
/// Represents a <see cref="Single"/>
/// </summary>
public const uint TYPE_SINGLE = 11;
/// <summary>
/// Represents a <see cref="DateTime"/>
/// </summary>
public const uint TYPE_DATETIME = 12;
/// <summary>
/// Represents a <see cref="TimeSpan"/>
/// </summary>
public const uint TYPE_TIMESPAN = 13;
/// <summary>
/// Represents a <see cref="Char"/>
/// </summary>
public const uint TYPE_CHAR = 14;
/// <summary>
/// Represents a <see cref="String"/>
/// </summary>
public const uint TYPE_STRING = 15;
/// <summary>
/// Represents an enumerated value.
/// </summary>
public const uint TYPE_ENUM = 16;
/// <summary>
/// Represents a byte array.
/// </summary>
public const uint TYPE_BYTEARRAY = 17;
/// <summary>
/// Represents a <see cref="Guid"/>
/// </summary>
public const uint TYPE_GUID = 18;
/// <summary>
/// Represents a <see cref="DateTimeOffset"/>
/// </summary>
public const uint TYPE_DATETIMEOFFSET = 19;
/// <summary>
/// Represents a <see cref="CaseInsensitiveString"/>
/// </summary>
public const uint TYPE_CI_STRING = 20;
/// <summary>
/// Variable length INT16
/// </summary>
public const uint TYPE_VARINT16 = 21;
/// <summary>
/// Variable length INT32
/// </summary>
public const uint TYPE_VARINT32 = 22;
/// <summary>
/// Variable length INT64
/// </summary>
public const uint TYPE_VARINT64 = 23;
/// <summary>
/// Variable length UINT16
/// </summary>
public const uint TYPE_VARUINT16 = 24;
/// <summary>
/// Variable length UINT32
/// </summary>
public const uint TYPE_VARUINT32 = 25;
/// <summary>
/// Variable length UINT64
/// </summary>
public const uint TYPE_VARUINT64 = 26;
/// <summary>
/// Represents the smallest possible value for the field type being searched or filtered.
/// </summary>
public const uint TYPE_MIN = 27;
/// <summary>
/// Represents the largest possible value for the field type being searched or filtered.
/// </summary>
public const uint TYPE_MAX = 28;
/// <summary>
/// Represents a null value.
/// </summary>
public const uint TYPE_NULL = 29;
/// <summary>
/// Represents an arary.
/// </summary>
public const uint TYPE_ARRAY = 30;
/// <summary>
/// Represents an object.
/// </summary>
public const uint TYPE_OBJECT = 31;
private static readonly Type[] obsoleteMethodTypes = new Type[] { typeof(Dictionary<string, object>) };
/// <summary>
/// Serialization context.
/// </summary>
private ISerializerContext context;
private Type type;
private System.Reflection.TypeInfo typeInfo;
private string collectionName;
private string[][] indices;
private TypeNameSerialization typeNameSerialization;
#if COMPILED
private FieldInfo objectIdFieldInfo = null;
private PropertyInfo objectIdPropertyInfo = null;
private MemberInfo objectIdMemberInfo = null;
private Type objectIdMemberType = null;
private readonly Dictionary<string, object> defaultValues = new Dictionary<string, object>();
private readonly Dictionary<string, Type> memberTypes = new Dictionary<string, Type>();
private readonly Dictionary<string, MemberInfo> members = new Dictionary<string, MemberInfo>();
private IObjectSerializer customSerializer = null;
private bool compiled;
#endif
private Member objectIdMember = null;
private readonly Dictionary<string, Member> membersByName = new Dictionary<string, Member>();
private readonly Dictionary<ulong, Member> membersByFieldCode = new Dictionary<ulong, Member>();
private readonly ChunkedList<Member> membersOrdered = new ChunkedList<Member>();
private PropertyInfo archiveProperty = null;
private FieldInfo archiveField = null;
private MethodInfo obsoleteMethod = null;
private object tag = null;
private int archiveDays = 0;
private bool archive = false;
private bool archiveDynamic = false;
private bool isNullable;
private bool normalized;
private bool hasByRef = false;
private bool backupCollection = true;
private bool prepared = false;
private bool hasEncrypted = false;
private string noBackupReason = null;
internal ObjectSerializer(ISerializerContext Context, Type Type) // Note order.
{
this.type = Type;
this.typeInfo = Type.GetTypeInfo();
this.context = Context;
this.normalized = Context.NormalizedNames;
#if COMPILED
this.compiled = false;
#endif
this.isNullable = true;
this.collectionName = null;
this.typeNameSerialization = TypeNameSerialization.FullName;
this.indices = Array.Empty<string[]>();
}
internal ObjectSerializer()
{
}
/// <summary>
/// Serialization context.
/// </summary>
public ISerializerContext Context => this.context;
#if COMPILED
/// <summary>
/// Initializes a serializer that serializes a class, taking into account attributes defined in <see cref="Waher.Persistence.Attributes"/>.
/// </summary>
/// <param name="Type">Type to serialize.</param>
/// <param name="Context">Serialization context.</param>
/// <param name="Compiled">If object serializers should be compiled or not.</param>
public static async Task<ObjectSerializer> Create(Type Type, ISerializerContext Context, bool Compiled)
{
ObjectSerializer Result = new ObjectSerializer();
await Result.Prepare(Type, Context, Compiled);
return Result;
}
#else
/// <summary>
/// Initializes a serializer that serializes a class, taking into account attributes defined in <see cref="Waher.Persistence.Attributes"/>.
/// </summary>
/// <param name="Type">Type to serialize.</param>
/// <param name="Context">Serialization context.</param>
public static async Task<ObjectSerializer> Create(Type Type, ISerializerContext Context)
{
ObjectSerializer Result = new ObjectSerializer();
await Result.Prepare(Type, Context);
return Result;
}
#endif
#if COMPILED
/// <summary>
/// Prepares a serializer that serializes a class, taking into account attributes defined in <see cref="Waher.Persistence.Attributes"/>.
/// </summary>
/// <param name="Type">Type to serialize.</param>
/// <param name="Context">Serialization context.</param>
/// <param name="Compiled">If object serializers should be compiled or not.</param>
internal async Task Prepare(Type Type, ISerializerContext Context, bool Compiled)
#else
/// <summary>
/// Prepares a serializer that serializes a class, taking into account attributes defined in <see cref="Waher.Persistence.Attributes"/>.
/// </summary>
/// <param name="Type">Type to serialize.</param>
/// <param name="Context">Serialization context.</param>
internal async Task Prepare(Type Type, ISerializerContext Context)
#endif
{
string TypeName = Type.Name.Replace("`", "_GT_");
this.type = Type;
this.typeInfo = Type.GetTypeInfo();
this.context = Context;
this.normalized = Context.NormalizedNames;
#if COMPILED
this.compiled = Compiled;
#endif
if (Type.IsClass && !Type.IsAbstract && Types.GetDefaultConstructor(Type) is null)
throw new SerializationException("Objects of type " + Type.FullName + " cannot be serialized: The class must have a default constructor.", Type);
if (this.type == typeof(bool) ||
this.type == typeof(byte) ||
this.type == typeof(char) ||
this.type == typeof(DateTime) ||
this.type == typeof(decimal) ||
this.type == typeof(double) ||
this.type == typeof(short) ||
this.type == typeof(int) ||
this.type == typeof(long) ||
this.type == typeof(sbyte) ||
this.type == typeof(float) ||
this.type == typeof(ushort) ||
this.type == typeof(uint) ||
this.type == typeof(ulong))
{
this.isNullable = false;
}
else if (this.type == typeof(void) || this.type == typeof(string))
this.isNullable = true;
else
this.isNullable = !this.typeInfo.IsValueType;
CollectionNameAttribute CollectionNameAttribute = this.typeInfo.GetCustomAttribute<CollectionNameAttribute>(true);
if (CollectionNameAttribute is null)
this.collectionName = null;
else
this.collectionName = CollectionNameAttribute.Name;
NoBackupAttribute NoBackupAttribute = this.typeInfo.GetCustomAttribute<NoBackupAttribute>(true);
if (NoBackupAttribute is null)
{
this.backupCollection = true;
this.noBackupReason = null;
}
else
{
this.backupCollection = false;
this.noBackupReason = NoBackupAttribute.Reason;
}
TypeNameAttribute TypeNameAttribute = this.typeInfo.GetCustomAttribute<TypeNameAttribute>(true);
if (TypeNameAttribute is null)
this.typeNameSerialization = TypeNameSerialization.FullName;
else
this.typeNameSerialization = TypeNameAttribute.TypeNameSerialization;
ObsoleteMethodAttribute ObsoleteMethodAttribute = this.typeInfo.GetCustomAttribute<ObsoleteMethodAttribute>(true);
if (!(ObsoleteMethodAttribute is null))
{
this.obsoleteMethod = this.type.GetRuntimeMethod(ObsoleteMethodAttribute.MethodName, obsoleteMethodTypes);
if (this.obsoleteMethod is null)
{
StringBuilder sb = new StringBuilder();
sb.Append("Obsolete method ");
sb.Append(ObsoleteMethodAttribute.MethodName);
sb.Append(" does not exist on ");
AppendType(this.type, sb);
throw new SerializationException(sb.ToString(), this.type);
}
ParameterInfo[] Parameters = this.obsoleteMethod.GetParameters();
if (Parameters.Length != 1 || Parameters[0].ParameterType != typeof(Dictionary<string, object>))
{
StringBuilder sb = new StringBuilder();
sb.Append("Obsolete method ");
sb.Append(ObsoleteMethodAttribute.MethodName);
sb.Append(" on ");
AppendType(this.type, sb);
sb.Append(" has invalid arguments.");
throw new SerializationException(sb.ToString(), this.type);
}
}
ArchivingTimeAttribute ArchivingTimeAttribute = this.typeInfo.GetCustomAttribute<ArchivingTimeAttribute>(true);
if (ArchivingTimeAttribute is null)
this.archive = false;
else
{
this.archive = true;
if (!string.IsNullOrEmpty(ArchivingTimeAttribute.PropertyName))
{
this.archiveProperty = this.type.GetRuntimeProperty(ArchivingTimeAttribute.PropertyName);
if (this.archiveProperty is null)
{
this.archiveField = this.type.GetRuntimeField(ArchivingTimeAttribute.PropertyName);
this.archiveProperty = null;
if (this.archiveField is null)
throw new SerializationException("Archiving time property or field not found: " + ArchivingTimeAttribute.PropertyName, this.type);
else if (this.archiveField.FieldType != typeof(int))
throw new SerializationException("Invalid field type for the archiving time: " + this.archiveField.Name, this.type);
}
else if (this.archiveProperty.PropertyType != typeof(int))
throw new SerializationException("Invalid property type for the archiving time: " + this.archiveProperty.Name, this.type);
else
this.archiveField = null;
this.archiveDynamic = !(this.archiveProperty is null && this.archiveField is null);
}
else
this.archiveDays = ArchivingTimeAttribute.Days;
}
if (this.typeInfo.IsAbstract && this.typeNameSerialization == TypeNameSerialization.None)
throw new SerializationException("Serializers for abstract classes require type names to be serialized.", this.type);
ChunkedList<string[]> Indices = new ChunkedList<string[]>();
Dictionary<string, bool> IndexFields = new Dictionary<string, bool>();
foreach (IndexAttribute IndexAttribute in this.typeInfo.GetCustomAttributes<IndexAttribute>(true))
{
Indices.Add(IndexAttribute.FieldNames);
foreach (string FieldName in IndexAttribute.FieldNames)
IndexFields[FieldName] = true;
}
this.indices = Indices.ToArray();
#if COMPILED
if (this.compiled)
{
StringBuilder CSharp = new StringBuilder();
StringBuilder sb = new StringBuilder();
ChunkedList<MemberInfo> Members = GetMembers(this.typeInfo);
Dictionary<string, string> ShortNames = new Dictionary<string, string>();
Dictionary<Type, bool> MemberTypes = new Dictionary<Type, bool>();
Type MemberType;
System.Reflection.TypeInfo MemberTypeInfo;
FieldInfo FI;
PropertyInfo PI;
MethodInfo MI;
object DefaultValue;
string ShortName;
string Indent, Indent2;
string s;
int NrDefault = 0;
int DecryptedMinLength;
bool HasDefaultValue;
bool Ignore;
bool ObjectIdField;
bool ByReference;
bool Nullable;
bool HasEncrypted = false;
bool Encrypted;
bool IsObjectId;
bool HasObjectId = false;
CSharp.AppendLine("using System;");
CSharp.AppendLine("using System.Collections.Generic;");
CSharp.AppendLine("using System.Reflection;");
CSharp.AppendLine("using System.Text;");
CSharp.AppendLine("using System.Threading.Tasks;");
CSharp.AppendLine("using Waher.Persistence;");
CSharp.AppendLine("using Waher.Persistence.Exceptions;");
CSharp.AppendLine("using Waher.Persistence.Filters;");
CSharp.AppendLine("using Waher.Persistence.Serialization;");
CSharp.AppendLine("using Waher.Runtime.Inventory;");
CSharp.AppendLine();
CSharp.Append("namespace ");
CSharp.Append(Type.Namespace);
CSharp.AppendLine(".Binary");
CSharp.AppendLine("{");
CSharp.Append("\tpublic class Serializer");
CSharp.Append(TypeName);
CSharp.Append(this.context.Id);
CSharp.AppendLine(" : GeneratedObjectSerializerBase");
CSharp.AppendLine("\t{");
CSharp.AppendLine("\t\tprivate ISerializerContext context;");
foreach (MemberInfo Member in Members)
{
if (!((FI = Member as FieldInfo) is null))
{
if (!FI.IsPublic || FI.IsStatic)
continue;
PI = null;
MemberType = FI.FieldType;
}
else if (!((PI = Member as PropertyInfo) is null))
{
if ((MI = PI.GetMethod) is null || !MI.IsPublic || MI.IsStatic)
continue;
if ((MI = PI.SetMethod) is null || !MI.IsPublic || MI.IsStatic)
continue;
if (PI.GetIndexParameters().Length > 0)
continue;
MemberType = PI.PropertyType;
}
else
continue;
this.memberTypes[Member.Name] = MemberType;
this.members[Member.Name] = Member;
IsObjectId = false;
Ignore = false;
ShortName = null;
ByReference = false;
Nullable = false;
Encrypted = false;
MemberTypeInfo = MemberType.GetTypeInfo();
if (MemberTypeInfo.IsGenericType)
{
Type GT = MemberType.GetGenericTypeDefinition();
if (GT == typeof(Nullable<>))
{
Nullable = true;
MemberType = MemberType.GenericTypeArguments[0];
MemberTypeInfo = MemberType.GetTypeInfo();
}
}
MemberTypes[MemberType] = true;
foreach (object Attr in Member.GetCustomAttributes(true))
{
if (Attr is IgnoreMemberAttribute)
{
Ignore = true;
break;
}
else if (Attr is DefaultValueAttribute DefaultValueAttribute)
{
if (IndexFields.ContainsKey(Member.Name))
{
sb.Clear();
sb.Append("Default value for ");
AppendType(Type, sb);
sb.Append('.');
sb.Append(Member.Name);
sb.Append(" ignored, as field is used to index objects.");
Log.Notice(sb.ToString());
}
else
{
DefaultValue = DefaultValueAttribute.Value;
NrDefault++;
this.defaultValues[Member.Name] = DefaultValue;
CSharp.Append("\t\tprivate static readonly ");
if (DefaultValue is null)
CSharp.Append("object");
else
AppendType(MemberType, CSharp);
CSharp.Append(" default");
CSharp.Append(Member.Name);
CSharp.Append(" = ");
if (DefaultValue is null)
CSharp.Append("null");
else
{
if (DefaultValue.GetType() != MemberType)
{
CSharp.Append('(');
AppendType(MemberType, CSharp);
CSharp.Append(')');
}
if (DefaultValue is string s2)
{
if (string.IsNullOrEmpty(s2))
{
if (MemberType == typeof(CaseInsensitiveString))
CSharp.Append("CaseInsensitiveString.Empty");
else
CSharp.Append("string.Empty");
}
else
{
CSharp.Append("\"");
CSharp.Append(Escape(DefaultValue.ToString()));
CSharp.Append("\"");
}
}
else if (DefaultValue is DateTime TP)
{
if (TP == DateTime.MinValue)
CSharp.Append("DateTime.MinValue");
else if (TP == DateTime.MaxValue)
CSharp.Append("DateTime.MaxValue");
else
{
CSharp.Append("new DateTime(");
CSharp.Append(TP.Ticks.ToString());
CSharp.Append(", DateTimeKind.");
CSharp.Append(TP.Kind.ToString());
CSharp.Append(")");
}
}
else if (DefaultValue is TimeSpan TS)
{
if (TS == TimeSpan.MinValue)
CSharp.Append("TimeSpan.MinValue");
else if (TS == TimeSpan.MaxValue)
CSharp.Append("TimeSpan.MaxValue");
else
{
CSharp.Append("new TimeSpan(");
CSharp.Append(TS.Ticks.ToString());
CSharp.Append(")");
}
}
else if (DefaultValue is Guid Guid)
{
if (Guid.Equals(Guid.Empty))
CSharp.Append("Guid.Empty");
else
{
CSharp.Append("new Guid(\"");
CSharp.Append(Guid.ToString());
CSharp.Append("\")");
}
}
else if (DefaultValue is Enum e)
{
Type DefaultValueType = DefaultValue.GetType();
if (DefaultValueType.IsDefined(typeof(FlagsAttribute), false))
{
bool First = true;
foreach (object Value in Enum.GetValues(DefaultValueType))
{
if (!e.HasFlag((Enum)Value))
continue;
if (First)
First = false;
else
CSharp.Append(" | ");
AppendType(DefaultValueType, CSharp);
CSharp.Append('.');
CSharp.Append(Value.ToString());
}
if (First)
CSharp.Append('0');
}
else
{
AppendType(DefaultValue.GetType(), CSharp);
CSharp.Append('.');
CSharp.Append(DefaultValue.ToString());
}
}
else if (DefaultValue is bool b)
{
if (b)
CSharp.Append("true");
else
CSharp.Append("false");
}
else if (DefaultValue is long)
{
CSharp.Append(DefaultValue.ToString());
CSharp.Append("L");
}
else if (DefaultValue is char ch)
{
CSharp.Append('\'');
if (ch == '\'')
CSharp.Append('\\');
CSharp.Append(ch);
CSharp.Append('\'');
}
else
CSharp.Append(DefaultValue.ToString());
}
CSharp.AppendLine(";");
}
}
else if (Attr is ByReferenceAttribute)
{
ByReference = true;
this.hasByRef = true;
}
else if (Attr is ObjectIdAttribute)
{
this.objectIdFieldInfo = FI;
this.objectIdPropertyInfo = PI;
this.objectIdMemberInfo = Member;
this.objectIdMemberType = MemberType;
HasObjectId = true;
IsObjectId = true;
}
else if (Attr is EncryptedAttribute)
{
Encrypted = true;
HasEncrypted = true;
}
}
if (IsObjectId && Encrypted)
throw new SerializationException("Object ID cannot be encrypted.", this.type);
if (Ignore || IsObjectId)
continue;
if (GetFieldDataTypeCode(MemberType) == TYPE_OBJECT)
{
CSharp.Append("\t\tprivate IObjectSerializer serializer");
CSharp.Append(Member.Name);
CSharp.AppendLine(";");
}
}
if (HasEncrypted && !HasObjectId)
throw new SerializationException("Encrypting properties requires an Object ID defined.", this.type);
if (NrDefault > 0)
CSharp.AppendLine();
CSharp.AppendLine();
CSharp.Append("\t\tpublic Serializer");
CSharp.Append(TypeName);
CSharp.Append(this.context.Id);
CSharp.AppendLine("(ISerializerContext Context)");
CSharp.AppendLine("\t\t{");
CSharp.AppendLine("\t\t\tthis.context = Context;");
CSharp.AppendLine("\t\t}");
CSharp.AppendLine();
bool InitWritten = false;
foreach (MemberInfo Member in Members)
{
if (!((FI = Member as FieldInfo) is null))
{
if (!FI.IsPublic || FI.IsStatic)
continue;
PI = null;
MemberType = FI.FieldType;
}
else if (!((PI = Member as PropertyInfo) is null))
{
if ((MI = PI.GetMethod) is null || !MI.IsPublic || MI.IsStatic)
continue;
if ((MI = PI.SetMethod) is null || !MI.IsPublic || MI.IsStatic)
continue;
if (PI.GetIndexParameters().Length > 0)
continue;
MemberType = PI.PropertyType;
}
else
continue;
Ignore = false;
MemberTypeInfo = MemberType.GetTypeInfo();
if (MemberTypeInfo.IsGenericType)
{
Type GT = MemberType.GetGenericTypeDefinition();
if (GT == typeof(Nullable<>))
{
MemberType = MemberType.GenericTypeArguments[0];
MemberTypeInfo = MemberType.GetTypeInfo();
}
}
foreach (object Attr in Member.GetCustomAttributes(true))
{
if (Attr is IgnoreMemberAttribute || Attr is ObjectIdAttribute)
{
Ignore = true;
break;
}
}
if (Ignore)
continue;
if (GetFieldDataTypeCode(MemberType) == TYPE_OBJECT)
{
if (!InitWritten)
{
CSharp.AppendLine("\t\tpublic override async Task Init()");
CSharp.AppendLine("\t\t{");
InitWritten = true;
}
CSharp.Append("\t\t\tthis.serializer");
CSharp.Append(Member.Name);
CSharp.Append(" = await this.context.GetObjectSerializer(typeof(");
AppendType(MemberType, CSharp);
CSharp.AppendLine("));");
}
}
if (!InitWritten)
{
CSharp.AppendLine("\t\tpublic override Task Init()");
CSharp.AppendLine("\t\t{");
CSharp.AppendLine("\t\t\treturn Task.CompletedTask;");
}
CSharp.AppendLine("\t\t}");
CSharp.AppendLine();
CSharp.Append("\t\tpublic override System.Type ValueType { get { return typeof(");
AppendType(Type, CSharp);
CSharp.AppendLine("); } }");
CSharp.AppendLine();
CSharp.Append("\t\tpublic override bool IsNullable { get { return ");
CSharp.Append((this.isNullable ? "true" : "false"));
CSharp.AppendLine("; } }");
CSharp.AppendLine();
CSharp.AppendLine("\t\tpublic override async Task<object> Deserialize(IDeserializer Reader, uint? DataType, bool Embedded)");
CSharp.AppendLine("\t\t{");
CSharp.AppendLine("\t\t\tuint FieldDataType;");
if (this.normalized)
CSharp.AppendLine("\t\t\tulong FieldCode;");
else
CSharp.AppendLine("\t\t\tstring FieldName;");
CSharp.Append("\t\t\t");
AppendType(Type, CSharp);
CSharp.AppendLine(" Result;");
CSharp.AppendLine("\t\t\tStreamBookmark Bookmark = Reader.GetBookmark();");
CSharp.AppendLine("\t\t\tuint? DataTypeBak = DataType;");
CSharp.AppendLine("\t\t\tGuid ObjectId = Embedded ? Guid.Empty : Reader.ReadGuid();");
CSharp.AppendLine("\t\t\tulong ContentLen = Embedded ? 0 : Reader.ReadVariableLengthUInt64();");
CSharp.AppendLine("\t\t\tDictionary<string, object> Obsolete = null;");
if (HasEncrypted)
{
CSharp.AppendLine("\t\t\tbyte[] Encrypted;");
CSharp.AppendLine("\t\t\tbyte[] Decrypted;");
CSharp.AppendLine("\t\t\tIDeserializer ReaderBak;");
}
CSharp.AppendLine();
CSharp.AppendLine("\t\t\tif (!DataType.HasValue)");
CSharp.AppendLine("\t\t\t{");
CSharp.AppendLine("\t\t\t\tDataType = Reader.ReadBits(6);");
CSharp.Append("\t\t\t\tif (DataType.Value == ");
CSharp.Append(TYPE_NULL);
CSharp.AppendLine(")\t// TYPE_NULL");
CSharp.AppendLine("\t\t\t\t\treturn null;");
CSharp.AppendLine("\t\t\t}");
CSharp.AppendLine();
CSharp.AppendLine("\t\t\tif (Embedded && Reader.BitOffset > 0 && Reader.ReadBit())");
CSharp.AppendLine("\t\t\t\tObjectId = Reader.ReadGuid();");
CSharp.AppendLine();
if (this.normalized)
CSharp.AppendLine("\t\t\tFieldCode = Reader.ReadVariableLengthUInt64();");
else
CSharp.AppendLine("\t\t\tFieldName = Reader.ReadString();");
if (this.typeNameSerialization != TypeNameSerialization.None)
{
if (this.normalized)
{
CSharp.Append("\t\t\tstring TypeName = await this.context.GetFieldName(\"");
CSharp.Append(Escape(this.collectionName));
CSharp.AppendLine("\", FieldCode);");
}
else
CSharp.AppendLine("\t\t\tstring TypeName = FieldName;");
if (this.typeNameSerialization == TypeNameSerialization.LocalName)
{
CSharp.AppendLine("\t\t\tif (TypeName.IndexOf('.') < 0)");
CSharp.Append("\t\t\t\tTypeName = \"");
CSharp.Append(Type.Namespace);
CSharp.AppendLine(".\" + TypeName;");
}
CSharp.AppendLine();
CSharp.AppendLine("\t\t\tSystem.Type DesiredType = Waher.Runtime.Inventory.Types.GetType(TypeName);");
CSharp.AppendLine("\t\t\tif (DesiredType is null)");
CSharp.AppendLine("\t\t\t\tDesiredType = typeof(GenericObject);");
CSharp.AppendLine();
CSharp.Append("\t\t\tif (DesiredType != typeof(");
AppendType(Type, CSharp);
CSharp.AppendLine("))");
CSharp.AppendLine("\t\t\t{");
CSharp.AppendLine("\t\t\t\tIObjectSerializer Serializer2 = await this.context.GetObjectSerializer(DesiredType);");
CSharp.AppendLine("\t\t\t\tReader.SetBookmark(Bookmark);");
CSharp.AppendLine("\t\t\t\treturn await Serializer2.Deserialize(Reader, DataTypeBak, Embedded);");
CSharp.AppendLine("\t\t\t}");
}
if (this.typeInfo.IsAbstract)
{
CSharp.AppendLine();
CSharp.Append("\t\t\tthrow new SerializationException(\"Unable to create an instance of the abstract class ");
AppendType(this.type, CSharp);
CSharp.AppendLine(".\", this.ValueType);");
}
else
{
CSharp.AppendLine();
CSharp.AppendLine("\t\t\tif (Embedded)");
if (this.normalized)
CSharp.AppendLine("\t\t\t\tReader.SkipVariableLengthInteger(); // Collection name");
else
CSharp.AppendLine("\t\t\t\tReader.SkipString();");
CSharp.AppendLine();
CSharp.Append("\t\t\tif (DataType.Value != ");
CSharp.Append(TYPE_OBJECT);
CSharp.AppendLine(")\t// TYPE_OBJECT");
CSharp.AppendLine("\t\t\t\tthrow new SerializationException(\"Object expected.\", this.ValueType);");
CSharp.AppendLine();
CSharp.Append("\t\t\tResult = new ");
AppendType(Type, CSharp);
CSharp.AppendLine("();");
CSharp.AppendLine();
if (HasObjectId)
{
if (this.objectIdMemberType == typeof(Guid))
{
CSharp.Append("\t\t\tResult.");
CSharp.Append(this.objectIdMemberInfo.Name);
CSharp.AppendLine(" = ObjectId;");
}
else if (this.objectIdMemberType == typeof(string))
{
CSharp.Append("\t\t\tResult.");
CSharp.Append(this.objectIdMemberInfo.Name);
CSharp.AppendLine(" = ObjectId.ToString();");
}
else if (this.objectIdMemberType == typeof(byte[]))
{
CSharp.Append("\t\t\tResult.");
CSharp.Append(this.objectIdMemberInfo.Name);
CSharp.AppendLine(" = ObjectId.ToByteArray();");
}
else
{
sb.Clear();
sb.Append("Type not supported for Object ID fields: ");
AppendType(this.objectIdMemberType, sb);
throw new SerializationException(sb.ToString(), this.type);
}
CSharp.AppendLine();
}
if (this.normalized)
CSharp.AppendLine("\t\t\twhile ((FieldCode = Reader.ReadVariableLengthUInt64()) != 0)");
else
CSharp.AppendLine("\t\t\twhile (!string.IsNullOrEmpty(FieldName = Reader.ReadString()))");
CSharp.AppendLine("\t\t\t{");
CSharp.AppendLine("\t\t\t\tFieldDataType = Reader.ReadBits(6);");
CSharp.AppendLine();
if (this.normalized)
CSharp.AppendLine("\t\t\t\tswitch (FieldCode)");
else
CSharp.AppendLine("\t\t\t\tswitch (FieldName)");
CSharp.AppendLine("\t\t\t\t{");
foreach (MemberInfo Member in Members)