-
Notifications
You must be signed in to change notification settings - Fork 287
/
Copy pathSerializer.cs
1141 lines (1067 loc) · 38.5 KB
/
Serializer.cs
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.Collections.Generic;
using System.Linq;
using System.IO;
using System.Reflection;
using Duality.IO;
namespace Duality.Serialization
{
/// <summary>
/// Base class for Dualitys serializers.
/// </summary>
[DontSerialize]
public abstract class Serializer : IDisposable
{
/// <summary>
/// Declares a <see cref="System.Reflection.FieldInfo">field</see> blocker. If a field blocker
/// returns true upon serializing a specific field, a default value is assumed instead.
/// </summary>
/// <param name="field"></param>
/// <param name="obj"></param>
public delegate bool FieldBlocker(FieldInfo field, object obj);
/// <summary>
/// Buffer object for <see cref="Duality.Serialization.ISerializeExplicit">custom de/serialization</see>,
/// providing read and write functionality.
/// </summary>
protected abstract class CustomSerialIOBase<T> : IDataReader, IDataWriter where T : Serializer
{
protected Dictionary<string,object> data;
/// <summary>
/// [GET] Enumerates all available keys.
/// </summary>
public IEnumerable<string> Keys
{
get { return this.data.Keys; }
}
/// <summary>
/// [GET] Enumerates all currently stored <see cref="System.Collections.Generic.KeyValuePair{T,U}">KeyValuePairs</see>.
/// </summary>
public IEnumerable<KeyValuePair<string,object>> Data
{
get { return this.data; }
}
protected CustomSerialIOBase()
{
this.data = new Dictionary<string,object>();
}
/// <summary>
/// Clears all contained data.
/// </summary>
public void Clear()
{
this.data.Clear();
}
/// <summary>
/// Writes the specified name and value.
/// </summary>
/// <param name="name">
/// The name to which the written value is mapped.
/// May, for example, be the name of a <see cref="System.Reflection.FieldInfo">Field</see>
/// to which the written value belongs, but there are no naming restrictions, except that one name can't be used twice.
/// </param>
/// <param name="value">The value to write.</param>
/// <seealso cref="IDataWriter"/>
public void WriteValue(string name, object value)
{
this.data[name] = value;
}
/// <summary>
/// Reads the value that is associated with the specified name.
/// </summary>
/// <param name="name">The name that is used for retrieving the value.</param>
/// <returns>The value that has been read using the given name.</returns>
/// <seealso cref="IDataReader"/>
/// <seealso cref="ReadValue{T}(string)"/>
/// <seealso cref="ReadValue{T}(string, out T)"/>
public object ReadValue(string name)
{
object result;
if (this.data.TryGetValue(name, out result))
return result;
else
return null;
}
/// <summary>
/// Reads the value that is associated with the specified name.
/// </summary>
/// <typeparam name="U">The expected value type.</typeparam>
/// <param name="name">The name that is used for retrieving the value.</param>
/// <returns>The value that has been read and cast using the given name and type.</returns>
/// <seealso cref="IDataReader"/>
/// <seealso cref="ReadValue(string)"/>
/// <seealso cref="ReadValue{U}(string, out U)"/>
public U ReadValue<U>(string name)
{
object read = this.ReadValue(name);
if (read is U)
return (U)read;
else if (read == null)
return default(U);
else
{
try { return (U)Convert.ChangeType(read, typeof(U), System.Globalization.CultureInfo.InvariantCulture); }
catch (Exception) { return default(U); }
}
}
/// <summary>
/// Reads the value that is associated with the specified name.
/// </summary>
/// <typeparam name="U">The expected value type.</typeparam>
/// <param name="name">The name that is used for retrieving the value.</param>
/// <param name="value">The value that has been read and cast using the given name and type.</param>
/// <seealso cref="IDataReader"/>
/// <seealso cref="ReadValue(string)"/>
/// <seealso cref="ReadValue{U}(string)"/>
public void ReadValue<U>(string name, out U value)
{
value = this.ReadValue<U>(name);
}
}
/// <summary>
/// Describes the serialization header of an object that is being de/serialized.
/// </summary>
protected class ObjectHeader
{
private uint objectId;
private DataType dataType;
private SerializeType serializeType;
private string typeString;
/// <summary>
/// [GET] The objects unique ID. May be zero for non-referenced object types.
/// </summary>
public uint ObjectId
{
get { return this.objectId; }
}
/// <summary>
/// [GET] The objects data type.
/// </summary>
public DataType DataType
{
get { return this.dataType; }
}
/// <summary>
/// [GET] The objects resolved serialization type information. May be unavailable / null when loading objects.
/// </summary>
public SerializeType SerializeType
{
get { return this.serializeType; }
}
/// <summary>
/// [GET] The objects resolved type information. May be unavailable / null when loading objects.
/// </summary>
public TypeInfo ObjectType
{
get { return (this.serializeType != null) ? this.serializeType.Type : null; }
}
/// <summary>
/// [GET] The string representing this objects type in the serialized data stream.
/// </summary>
public string TypeString
{
get { return this.typeString; }
}
/// <summary>
/// [GET] Whether or not the object is considered a primitive value according to its <see cref="DataType"/>.
/// </summary>
public bool IsPrimitive
{
get { return this.dataType.IsPrimitiveType(); }
}
/// <summary>
/// [GET] Returns whether this kind of object requires an explicit <see cref="ObjectType"/> to be fully described described during serialization.
/// </summary>
public bool IsObjectTypeRequired
{
get { return this.dataType.HasTypeName(); }
}
/// <summary>
/// [GET] Returns whether this kind of object requires an <see cref="ObjectId"/> to be fully described during serialization.
/// </summary>
public bool IsObjectIdRequired
{
get { return this.dataType.HasObjectId(); }
}
public ObjectHeader(uint id, DataType dataType, SerializeType serializeType)
{
this.objectId = id;
this.dataType = dataType;
this.serializeType = serializeType;
this.typeString = (serializeType != null) ? serializeType.TypeString : null;
}
public ObjectHeader(uint id, DataType dataType, string unresolvedTypeString)
{
this.objectId = id;
this.dataType = dataType;
this.serializeType = null;
this.typeString = unresolvedTypeString;
}
}
/// <summary>
/// The de/serialization <see cref="Duality.Log"/>.
/// </summary>
/// <summary>
/// A list of <see cref="System.Reflection.FieldInfo">field</see> blockers. If any registered field blocker
/// returns true upon serializing a specific field, a default value is assumed instead.
/// </summary>
protected List<FieldBlocker> fieldBlockers = new List<FieldBlocker>();
/// <summary>
/// Manages object IDs during de/serialization.
/// </summary>
protected ObjectIdManager idManager = new ObjectIdManager();
private Stream stream = null;
private bool opInProgress = false;
private bool disposed = false;
private Log log = Logs.Core;
private Dictionary<string, Type> typeResolveCache = new Dictionary<string, Type>();
private Dictionary<string, MemberInfo> memberResolveCache = new Dictionary<string, MemberInfo>();
private HashSet<FieldInfo> fieldTypeMismatchCache = new HashSet<FieldInfo>();
/// <summary>
/// [GET] Can this <see cref="Serializer"/> read data?
/// </summary>
public virtual bool CanRead
{
get { return this.stream != null && this.stream.CanRead; }
}
/// <summary>
/// [GET] Can this <see cref="Serializer"/> write data?
/// </summary>
public virtual bool CanWrite
{
get { return this.stream != null && this.stream.CanWrite; }
}
/// <summary>
/// [GET / SET] The target <see cref="Stream"/> this <see cref="Serializer"/> operates on (i.e. reads from and writes to).
/// </summary>
public Stream TargetStream
{
get { return this.stream; }
set
{
if (this.opInProgress) throw new InvalidOperationException("Can't change the target Stream while an I/O operation is in progress.");
if (this.stream != value)
{
Stream oldValue = this.stream;
this.stream = value;
this.OnTargetStreamChanged(oldValue, this.stream);
}
}
}
/// <summary>
/// [GET / SET] The local de/serialization <see cref="Duality.Log"/>.
/// </summary>
public Log LocalLog
{
get { return this.log; }
set { this.log = value ?? new Log("Serialize", "IO"); }
}
/// <summary>
/// [GET] Enumerates registered <see cref="System.Reflection.FieldInfo">field</see> blockers. If any registered field blocker
/// returns true upon serializing a specific field, a default value is assumed instead.
/// </summary>
public IEnumerable<FieldBlocker> FieldBlockers
{
get { return this.fieldBlockers; }
}
/// <summary>
/// [GET] Whether this formatter has been disposed. A disposed object cannot be used anymore.
/// </summary>
public bool Disposed
{
get { return this.disposed; }
}
protected Serializer() {}
~Serializer()
{
this.Dispose(false);
}
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}
private void Dispose(bool manually)
{
if (!this.disposed)
{
this.disposed = true;
this.OnDisposed(manually);
}
}
protected virtual void OnDisposed(bool manually)
{
this.TargetStream = null;
}
/// <summary>
/// Reads a single object and returns it.
/// </summary>
public object ReadObject()
{
if (!this.CanRead) throw new InvalidOperationException("Can't read object from a write-only serializer!");
try
{
this.BeginReadOperation();
return this.ReadObjectData();
}
finally
{
this.EndReadOperation();
}
}
/// <summary>
/// Reads a single object, casts it to the specified Type and returns it.
/// </summary>
/// <typeparam name="T"></typeparam>
public T ReadObject<T>()
{
object result = this.ReadObject();
return result is T ? (T)result : default(T);
}
/// <summary>
/// Reads a single object, casts it to the specified Type and returns it via output parameter.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
public void ReadObject<T>(out T obj)
{
object result = this.ReadObject();
obj = result is T ? (T)result : default(T);
}
/// <summary>
/// Writes a single object.
/// </summary>
/// <param name="obj"></param>
public void WriteObject(object obj)
{
if (!this.CanWrite) throw new InvalidOperationException("Can't write object to a read-only serializer!");
try
{
this.BeginWriteOperation();
this.WriteObjectData(obj);
}
finally
{
this.EndWriteOperation();
}
}
/// <summary>
/// Writes a single object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
public void WriteObject<T>(T obj)
{
this.WriteObject((object)obj);
}
/// <summary>
/// Unregisters all <see cref="FieldBlockers"/>.
/// </summary>
public void ClearFieldBlockers()
{
this.fieldBlockers.Clear();
}
/// <summary>
/// Registers a new <see cref="FieldBlockers">FieldBlocker</see>.
/// </summary>
/// <param name="blocker"></param>
public void AddFieldBlocker(FieldBlocker blocker)
{
if (this.fieldBlockers.Contains(blocker)) return;
this.fieldBlockers.Add(blocker);
}
/// <summary>
/// Unregisters an existing <see cref="FieldBlockers">FieldBlocker</see>.
/// </summary>
/// <param name="blocker"></param>
public void RemoveFieldBlocker(FieldBlocker blocker)
{
this.fieldBlockers.Remove(blocker);
}
/// <summary>
/// Determines whether a specific <see cref="System.Reflection.FieldInfo">field</see> is blocked.
/// Blocked fields, despite being generally flagged as being serializable, are omitted during de/serialization and retain their default value.
/// </summary>
/// <param name="field">The <see cref="System.Reflection.FieldInfo">field</see> in question.</param>
/// <param name="obj">The object where this field originates from.</param>
/// <returns>True, if the <see cref="System.Reflection.FieldInfo">field</see> is blocked, false if not.</returns>
public bool IsFieldBlocked(FieldInfo field, object obj)
{
return this.fieldBlockers.Any(blocker => blocker(field, obj));
}
/// <summary>
/// Determines whether or not the specified <see cref="Stream"/> matches the required format by
/// this <see cref="Serializer"/>. This is used to determine which <see cref="Serializer"/> can be
/// used for any given input <see cref="Stream"/>.
/// </summary>
/// <param name="stream"></param>
protected abstract bool MatchesStreamFormat(Stream stream);
/// <summary>
/// Writes the specified object including all referenced objects.
/// </summary>
protected abstract object ReadObjectData();
/// <summary>
/// Reads an object including all referenced objects.
/// </summary>
/// <returns>The object that has been read.</returns>
protected abstract void WriteObjectData(object obj);
/// <summary>
/// Called when the target stream this <see cref="Serializer"/> operates on has changed.
/// </summary>
/// <param name="oldStream"></param>
/// <param name="newStream"></param>
protected virtual void OnTargetStreamChanged(Stream oldStream, Stream newStream) { }
/// <summary>
/// Signals the beginning of an atomic ReadObject operation.
/// </summary>
protected virtual void OnBeginReadOperation() { }
/// <summary>
/// Signals the beginning of an atomic WriteObject operation.
/// </summary>
protected virtual void OnBeginWriteOperation() { }
/// <summary>
/// Signals the end of an atomic ReadObject operation.
/// </summary>
protected virtual void OnEndReadOperation() { }
/// <summary>
/// Signals the end of an atomic WriteObject operation.
/// </summary>
protected virtual void OnEndWriteOperation() { }
/// <summary>
/// Prepares an object for serialization and generates its header information.
/// </summary>
/// <param name="obj">The object to write</param>
protected ObjectHeader PrepareWriteObject(object obj)
{
Type objType = obj.GetType();
SerializeType objSerializeType = GetSerializeType(objType);
DataType dataType = objSerializeType.DataType;
uint objId = 0;
// Check whether it's going to be an ObjectRef or not
if (objSerializeType.CanBeReferenced)
{
bool newId;
objId = this.idManager.Request(obj, out newId);
// If its not a new id, write a reference
if (!newId) dataType = DataType.ObjectRef;
}
// Check whether the object is expected to be serialized
if (dataType != DataType.ObjectRef &&
!objSerializeType.IsSerializable &&
!typeof(ISerializeExplicit).GetTypeInfo().IsAssignableFrom(objSerializeType.Type) &&
objSerializeType.Surrogate == null)
{
this.LocalLog.WriteWarning("Ignoring object of Type '{0}' which is flagged with the {1}.",
LogFormat.Type(objSerializeType.Type),
typeof(DontSerializeAttribute).Name);
return null;
}
// Generate object header information
return new ObjectHeader(objId, dataType, objSerializeType);
}
/// <summary>
/// Logs an error that occurred during <see cref="Duality.Serialization.ISerializeExplicit">custom serialization</see>.
/// </summary>
/// <param name="objId">The object id of the affected object.</param>
/// <param name="serializeType">The <see cref="System.Type"/> of the affected object.</param>
/// <param name="e">The <see cref="System.Exception"/> that occurred.</param>
protected void LogCustomSerializationError(uint objId, TypeInfo serializeType, Exception e)
{
this.log.WriteError(
"An error occurred in custom serialization in object Id {0} of type '{1}': {2}",
objId,
LogFormat.Type(serializeType),
LogFormat.Exception(e));
}
/// <summary>
/// Logs an error that occurred during <see cref="Duality.Serialization.ISerializeExplicit">custom deserialization</see>.
/// </summary>
/// <param name="objId">The object id of the affected object.</param>
/// <param name="serializeType">The <see cref="System.Type"/> of the affected object.</param>
/// <param name="e">The <see cref="System.Exception"/> that occurred.</param>
protected void LogCustomDeserializationError(uint objId, TypeInfo serializeType, Exception e)
{
this.log.WriteError(
"An error occurred in custom deserialization in object Id {0} of type '{1}': {2}",
objId,
LogFormat.Type(serializeType),
LogFormat.Exception(e));
}
/// <summary>
/// Assigns the specified value to an objects field.
/// </summary>
/// <param name="objSerializeType"></param>
/// <param name="obj"></param>
/// <param name="fieldName"></param>
/// <param name="fieldValue"></param>
protected void AssignValueToField(SerializeType objSerializeType, object obj, string fieldName, object fieldValue)
{
if (obj == null) return;
// Retrieve field
FieldInfo field = null;
if (objSerializeType != null)
{
field = objSerializeType.GetFieldByName(fieldName);
// If the serializer-specific type does not have a matching field, attempt a global resolve.
// This handles cases where a formerly serialized field is now flagged as non-serialized.
if (field == null)
{
// Note that we don't use the local ResolveType method, since we don't want to log an error
// in case it fails. If there's a custom error handler to pick it up later, fine - if not,
// the field simply has been removed and is no longer relevant.
field = ReflectionHelper.ResolveMember("F:" + objSerializeType.TypeString + ":" + fieldName) as FieldInfo;
// Can't overwrite const values. This can happen when a field was replaced with a const of
// the same name. (We still allow overwriting readonly fields though, as serialization is
// a special case that may require it in some cases.)
if (field != null && field.IsLiteral) field = null;
}
}
if (field == null)
{
this.HandleAssignValueToField(objSerializeType, obj, fieldName, fieldValue);
return;
}
if (field.HasAttributeCached<DontSerializeAttribute>())
{
this.HandleAssignValueToField(objSerializeType, obj, fieldName, fieldValue);
return;
}
TypeInfo fieldTypeInfo = field.FieldType.GetTypeInfo();
if (fieldValue != null && !fieldTypeInfo.IsInstanceOfType(fieldValue))
{
if (!this.HandleAssignValueToField(objSerializeType, obj, fieldName, fieldValue))
{
// If this is the first time we encounter a type mismatch for this field, log a warning
Type serializedFieldType = fieldValue.GetType();
if (this.fieldTypeMismatchCache.Add(field))
{
this.LocalLog.WriteWarning(
"Serialized field value Type '{0}' does not match field Type '{2}' in field '{1}'. Converting values where possible, discarding otherwise.",
LogFormat.Type(serializedFieldType),
LogFormat.FieldInfo(field),
LogFormat.Type(field.FieldType));
}
object castVal;
try
{
if (fieldTypeInfo.IsEnum)
{
castVal = Convert.ChangeType(fieldValue, Enum.GetUnderlyingType(field.FieldType), System.Globalization.CultureInfo.InvariantCulture);
castVal = Enum.ToObject(field.FieldType, castVal);
}
else
{
castVal = Convert.ChangeType(fieldValue, field.FieldType, System.Globalization.CultureInfo.InvariantCulture);
}
field.SetValue(obj, castVal);
}
catch (Exception) { }
}
return;
}
if (fieldValue == null && fieldTypeInfo.IsValueType) fieldValue = fieldTypeInfo.CreateInstanceOf();
field.SetValue(obj, fieldValue);
}
/// <summary>
/// Assigns the specified value to a specific array index.
/// </summary>
protected void AssignValueToArray(SerializeType elementSerializeType, Array array, int index, object value)
{
if (array == null) return;
if (value != null && !elementSerializeType.Type.IsInstanceOfType(value))
{
this.LocalLog.WriteWarning(
"Actual Type '{0}' of array element value at index {1} does not match reflected array element type '{2}'. Skipping item.",
value != null ? LogFormat.Type(value.GetType()) : "unknown",
index,
LogFormat.Type(elementSerializeType.Type));
return;
}
array.SetValue(value, index);
}
/// <summary>
/// Resolves the specified Type.
/// </summary>
/// <param name="typeId"></param>
/// <param name="objId"></param>
protected Type ResolveType(string typeId, uint objId = 0)
{
// Re-use already resolved type IDs from the local cache, if possible
Type result;
if (!this.typeResolveCache.TryGetValue(typeId, out result))
{
// Otherwise, perform a global type resolve and temporarily store the result locally
result = ReflectionHelper.ResolveType(typeId);
this.typeResolveCache[typeId] = result;
// If the resolve failed, log an error. Since we're storing the null result in our
// local cache, this will happen only once per ID and read / write operation.
if (result == null)
{
if (objId != 0)
this.log.WriteError("Can't resolve Type '{0}' in object Id {1}. Type not found.", typeId, objId);
else
this.log.WriteError("Can't resolve Type '{0}'. Type not found.", typeId);
}
}
return result;
}
/// <summary>
/// Resolves the specified Member.
/// </summary>
/// <param name="memberId"></param>
/// <param name="objId"></param>
protected MemberInfo ResolveMember(string memberId, uint objId = 0)
{
// Re-use already resolved member IDs from the local cache, if possible
MemberInfo result;
if (!this.memberResolveCache.TryGetValue(memberId, out result))
{
// Otherwise, perform a global member resolve and temporarily store the result locally
result = ReflectionHelper.ResolveMember(memberId);
this.memberResolveCache[memberId] = result;
// If the resolve failed, log an error. Since we're storing the null result in our
// local cache, this will happen only once per ID and read / write operation.
if (result == null)
{
if (objId != 0)
this.log.WriteError("Can't resolve Member '{0}' in object Id {1}. Member not found.", memberId, objId);
else
this.log.WriteError("Can't resolve Member '{0}'. Member not found.", memberId);
}
}
return result;
}
/// <summary>
/// Resolves the specified Enum value.
/// </summary>
/// <param name="enumType"></param>
/// <param name="enumField"></param>
/// <param name="value"></param>
protected Enum ResolveEnumValue(Type enumType, string enumField, long value)
{
try
{
object result = Enum.Parse(enumType, enumField);
if (result != null) return (Enum)result;
}
catch (Exception) {}
string memberId = "F:" + enumType.GetTypeId() + ":" + enumField;
MemberInfo member = ReflectionHelper.ResolveMember(memberId);
if (member != null)
{
try
{
object result = Enum.Parse(enumType, member.Name);
if (result != null) return (Enum)result;
}
catch (Exception) {}
}
this.log.WriteWarning("Can't parse enum value '{0}' of Type '{1}'. Using numerical value '{2}' instead.", enumField, LogFormat.Type(enumType), value);
return (Enum)Enum.ToObject(enumType, value);
}
private void BeginReadOperation()
{
if (this.opInProgress) throw new InvalidOperationException("Can't begin a new operation before ending the previous one.");
if (this.stream == null) throw new InvalidOperationException("Can't read data, because no target Stream was defined.");
if (!this.CanRead) throw new InvalidOperationException("Can't read data, because the Serializer doesn't support it.");
this.opInProgress = true;
this.OnBeginReadOperation();
}
private void BeginWriteOperation()
{
if (this.opInProgress) throw new InvalidOperationException("Can't begin a new operation before ending the previous one.");
if (this.stream == null) throw new InvalidOperationException("Can't write data, because no target Stream was defined.");
if (!this.CanWrite) throw new InvalidOperationException("Can't write data, because the Serializer doesn't support it.");
this.opInProgress = true;
this.OnBeginWriteOperation();
}
private void EndReadOperation()
{
if (!this.opInProgress) throw new InvalidOperationException("Can't end the current operation, because no operation is in progress.");
this.idManager.Clear();
this.typeResolveCache.Clear();
this.memberResolveCache.Clear();
this.fieldTypeMismatchCache.Clear();
this.opInProgress = false;
this.OnEndReadOperation();
}
private void EndWriteOperation()
{
if (!this.opInProgress) throw new InvalidOperationException("Can't end the current operation, because no operation is in progress.");
this.idManager.Clear();
this.typeResolveCache.Clear();
this.memberResolveCache.Clear();
this.fieldTypeMismatchCache.Clear();
this.opInProgress = false;
this.OnEndWriteOperation();
}
private bool HandleAssignValueToField(SerializeType objSerializeType, object obj, string fieldName, object fieldValue)
{
AssignFieldError error = new AssignFieldError(objSerializeType, obj, fieldName, fieldValue);
return HandleSerializeError(error);
}
private static List<Type> availableSerializerTypes = new List<Type>();
private static List<Serializer> tempCheckSerializers = new List<Serializer>();
private static Dictionary<Type,SerializeType> serializeTypeCache = new Dictionary<Type,SerializeType>();
private static List<SerializeErrorHandler> serializeHandlerCache = new List<SerializeErrorHandler>();
private static List<ISerializeSurrogate> surrogates = null;
private static Type defaultSerializer = null;
/// <summary>
/// [GET / SET] The default <see cref="Serializer"/> type to use, if no other is specified.
/// </summary>
public static Type DefaultType
{
get
{
// If we don't know yet, determine the default serialization method to use
if (defaultSerializer == null)
{
InitDefaultMethod();
}
// If we still don't know, assume XML serialization, because we really need a default.
return defaultSerializer ?? typeof(XmlSerializer);
}
set { defaultSerializer = value; }
}
/// <summary>
/// [GET] Enumerates all available <see cref="Serializer"/> types.
/// </summary>
public static IEnumerable<Type> AvailableTypes
{
get
{
if (availableSerializerTypes.Count == 0)
{
availableSerializerTypes = new List<Type>();
foreach (TypeInfo typeInfo in DualityApp.GetAvailDualityTypes(typeof(Serializer)))
{
if (typeInfo.IsAbstract) continue;
availableSerializerTypes.Add(typeInfo.AsType());
}
}
return availableSerializerTypes;
}
}
/// <summary>
/// [GET] A list of internal, temporary <see cref="Serializer"/> instances to check for Stream compatibility.
/// </summary>
private static IList<Serializer> TempCheckSerializers
{
get
{
if (tempCheckSerializers.Count == 0)
{
tempCheckSerializers = new List<Serializer>();
foreach (TypeInfo typeInfo in DualityApp.GetAvailDualityTypes(typeof(Serializer)))
{
if (typeInfo.IsAbstract) continue;
Serializer instance = typeInfo.CreateInstanceOf() as Serializer;
if (instance == null) continue;
tempCheckSerializers.Add(instance);
}
}
return tempCheckSerializers;
}
}
static Serializer()
{
ReflectionHelper.MemberResolve += new EventHandler<ResolveMemberEventArgs>(ReflectionHelper_MemberResolve);
ReflectionHelper.TypeResolve += new EventHandler<ResolveMemberEventArgs>(ReflectionHelper_TypeResolve);
}
/// <summary>
/// Uses a (seekable, random access) Stream to detect the serializer that can handle it.
/// </summary>
/// <param name="stream"></param>
public static Type Detect(Stream stream)
{
if (!stream.CanRead || !stream.CanSeek) throw new ArgumentException("The specified Stream needs to be readable, seekable and provide random-access functionality.");
if (stream.Length == 0) throw new InvalidOperationException("The specified stream must not be empty.");
IList<Serializer> tempSerializers = TempCheckSerializers;
for (int i = tempSerializers.Count - 1; i >= 0; i--)
{
Serializer serializer = tempSerializers[i];
long oldPos = stream.Position;
try
{
if (serializer.MatchesStreamFormat(stream))
{
return serializer.GetType();
}
}
catch (Exception e)
{
Logs.Core.WriteError(
"An error occurred while asking {0} whether it matched the format of a certain Stream: {1}",
LogFormat.Type(serializer.GetType()),
LogFormat.Exception(e));
}
finally
{
stream.Seek(oldPos, SeekOrigin.Begin);
}
}
return null;
}
/// <summary>
/// Creates a new <see cref="Serializer"/> using the specified stream for I/O.
/// </summary>
/// <param name="stream">The stream to use.</param>
/// <param name="preferredSerializer">
/// The serialization method to prefer. Auto-detection is used when not specified explicitly
/// and the underlying stream supports seeking / random access. Otherwise, the <see cref="DefaultType"/> is used.
/// </param>
/// <returns>A newly created <see cref="Serializer"/> meeting the specified criteria.</returns>
public static Serializer Create(Stream stream, Type preferredSerializer = null)
{
// If no preferred serializer is specified, try to detect which one to use
if (preferredSerializer == null && stream.CanRead && stream.CanSeek && stream.Length > 0 && stream.Position < stream.Length)
preferredSerializer = Detect(stream);
// If detection wasn't possible, assume the default serializer.
if (preferredSerializer == null)
preferredSerializer = DefaultType;
// Do a consistency check on the serializer type we got passed - is it really a Serializer?
TypeInfo baseTypeInfo = typeof(Serializer).GetTypeInfo();
TypeInfo serializerTypeInfo = preferredSerializer.GetTypeInfo();
if (!baseTypeInfo.IsAssignableFrom(serializerTypeInfo))
throw new ArgumentException("Can't use a non-{0} Type as a {0}.", baseTypeInfo.Name);
// Create an instance of the Serializer, configure and return it
Serializer serializer = serializerTypeInfo.CreateInstanceOf() as Serializer;
serializer.TargetStream = stream;
return serializer;
}
/// <summary>
/// Reads an object of the specified Type from an existing data file, expecting that it might fail.
/// This method does not throw an Exception when the file does not exist or another
/// error occurred during the read operation. Instead, it will simply return null in these cases.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="file"></param>
/// <param name="preferredSerializer"></param>
public static T TryReadObject<T>(string file, Type preferredSerializer = null)
{
try
{
if (!FileOp.Exists(file)) return default(T);
using (Stream str = FileOp.Open(file, FileAccessMode.Read))
{
return Serializer.TryReadObject<T>(str, preferredSerializer);
}
}
catch (Exception)
{
return default(T);
}
}
/// <summary>
/// Reads an object of the specified Type from an existing data Stream, expecting that it might fail.
/// This method does not throw an Exception when the file does not exist or an expected
/// error occurred during the read operation. Instead, it will simply return null in these cases.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="stream"></param>
/// <param name="preferredSerializer"></param>
public static T TryReadObject<T>(Stream stream, Type preferredSerializer = null)
{
try
{
using (Serializer formatter = Serializer.Create(stream, preferredSerializer))
{
return formatter.ReadObject<T>();
}
}
catch (Exception)
{
return default(T);
}
}
/// <summary>
/// Reads an object of the specified Type from an existing data file.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="file"></param>
/// <param name="preferredSerializer"></param>
public static T ReadObject<T>(string file, Type preferredSerializer = null)
{
using (Stream str = FileOp.Open(file, FileAccessMode.Read))
{
return Serializer.ReadObject<T>(str, preferredSerializer);
}
}
/// <summary>
/// Reads an object of the specified Type from an existing data Stream.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="stream"></param>
/// <param name="preferredSerializer"></param>
public static T ReadObject<T>(Stream stream, Type preferredSerializer = null)
{
using (Serializer formatter = Serializer.Create(stream, preferredSerializer))
{
return formatter.ReadObject<T>();
}
}
/// <summary>
/// Saves an object to the specified data file. If it already exists, the file will be overwritten.
/// Automatically creates the appropriate directory structure, if it doesn't exist yet.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="file"></param>
/// <param name="preferredSerializer"></param>
public static void WriteObject<T>(T obj, string file, Type preferredSerializer = null)
{
string dirName = PathOp.GetDirectoryName(file);
if (!string.IsNullOrEmpty(dirName) && !DirectoryOp.Exists(dirName)) DirectoryOp.Create(dirName);
using (Stream str = FileOp.Create(file))
{
Serializer.WriteObject<T>(obj, str, preferredSerializer);
}
}
/// <summary>
/// Saves an object to the specified data stream.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="stream"></param>
/// <param name="preferredSerializer"></param>
public static void WriteObject<T>(T obj, Stream stream, Type preferredSerializer = null)
{
using (Serializer formatter = Serializer.Create(stream, preferredSerializer ?? DefaultType))
{
formatter.WriteObject(obj);
}
}