-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDynamicSerializer.cs
More file actions
560 lines (525 loc) · 22.4 KB
/
DynamicSerializer.cs
File metadata and controls
560 lines (525 loc) · 22.4 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
// =================================================================================================================================
// Copyright (c) RapidField LLC. Licensed under the MIT License. See LICENSE.txt in the project root for license information.
// =================================================================================================================================
using RapidField.SolidInstruments.Core;
using RapidField.SolidInstruments.Core.ArgumentValidation;
using RapidField.SolidInstruments.Core.Extensions;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
namespace RapidField.SolidInstruments.Serialization
{
/// <summary>
/// Performs serialization and deserialization for a given type.
/// </summary>
/// <typeparam name="T">
/// The type of the serializable object.
/// </typeparam>
public class DynamicSerializer<T> : DynamicSerializer, ISerializer<T>
where T : class
{
/// <summary>
/// Initializes a new instance of the <see cref="DynamicSerializer{T}" /> class.
/// </summary>
public DynamicSerializer()
: base()
{
return;
}
/// <summary>
/// Initializes a new instance of the <see cref="DynamicSerializer{T}" /> class.
/// </summary>
/// <param name="format">
/// The format to use for serialization and deserialization.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="format" /> is equal to <see cref="SerializationFormat.Unspecified" />.
/// </exception>
public DynamicSerializer(SerializationFormat format)
: base(format)
{
LazyJsonSerializer = new Lazy<DataContractJsonSerializer>(InitializeJsonSerializer, LazyThreadSafetyMode.PublicationOnly);
LazyXmlSerializer = new Lazy<DataContractSerializer>(InitializeXmlSerializer, LazyThreadSafetyMode.PublicationOnly);
}
/// <summary>
/// Converts the specified bit field to its typed equivalent.
/// </summary>
/// <param name="serializedObject">
/// A serialized object.
/// </param>
/// <returns>
/// The deserialized object.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializedObject" /> is <see langword="null" />.
/// </exception>
/// <exception cref="SerializationException">
/// <paramref name="serializedObject" /> is invalid or an error occurred during deserialization.
/// </exception>
public T Deserialize(Byte[] serializedObject) => Deserialize(serializedObject.RejectIf().IsNull(nameof(serializedObject)), Format);
/// <summary>
/// Converts the specified object to a serialized bit field.
/// </summary>
/// <param name="target">
/// An object to be serialized.
/// </param>
/// <returns>
/// The serialized bit field.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="target" /> is <see langword="null" />.
/// </exception>
/// <exception cref="SerializationException">
/// <paramref name="target" /> is invalid or an error occurred during serialization.
/// </exception>
public Byte[] Serialize(T target) => Serialize(target.RejectIf().IsNull(nameof(target)), Format);
/// <summary>
/// Converts the value of the current <see cref="DynamicSerializer{T}" /> to its equivalent string representation.
/// </summary>
/// <returns>
/// A string representation of the current <see cref="DynamicSerializer{T}" />.
/// </returns>
public override String ToString() => $"{{ \"{nameof(Format)}\": \"{Format}\", {nameof(ContractType)}\": \"{ContractType.FullName}\" }}";
/// <summary>
/// Converts the specified bit field to its typed equivalent.
/// </summary>
/// <param name="serializedObject">
/// A serialized object.
/// </param>
/// <param name="format">
/// The format to use for deserialization.
/// </param>
/// <returns>
/// The deserialized object.
/// </returns>
/// <exception cref="SerializationException">
/// <paramref name="serializedObject" /> is invalid or an error occurred during deserialization.
/// </exception>
protected virtual T Deserialize(Byte[] serializedObject, SerializationFormat format) => format switch
{
SerializationFormat.Binary => Deserialize(serializedObject, DefaultFormat),
SerializationFormat.CompressedJson => DeserializeFromJson(serializedObject.Decompress()),
SerializationFormat.CompressedXml => DeserializeFromXml(serializedObject.Decompress()),
SerializationFormat.Json => DeserializeFromJson(serializedObject),
SerializationFormat.Xml => DeserializeFromXml(serializedObject),
_ => throw new UnsupportedSpecificationException($"The specified serialization format, {Format}, is not supported.")
};
/// <summary>
/// Converts the specified object to a bit field.
/// </summary>
/// <param name="target">
/// An object to be serialized.
/// </param>
/// <param name="format">
/// The format to use for serialization.
/// </param>
/// <returns>
/// The serialized bit field.
/// </returns>
/// <exception cref="SerializationException">
/// <paramref name="target" /> is invalid or an error occurred during serialization.
/// </exception>
protected virtual Byte[] Serialize(T target, SerializationFormat format) => format switch
{
SerializationFormat.Binary => Serialize(target, DefaultFormat),
SerializationFormat.CompressedJson => SerializeToJson(target).Compress(),
SerializationFormat.CompressedXml => SerializeToXml(target).Compress(),
SerializationFormat.Json => SerializeToJson(target),
SerializationFormat.Xml => SerializeToXml(target),
_ => throw new UnsupportedSpecificationException($"The specified serialization format, {format}, is not supported.")
};
/// <summary>
/// Initializes an XML serializer.
/// </summary>
/// <returns>
/// An XML serializer.
/// </returns>
[DebuggerHidden]
private static DataContractJsonSerializer InitializeJsonSerializer() => new DataContractJsonSerializer(ContractType, JsonSerializerSettings);
/// <summary>
/// Initializes an XML serializer.
/// </summary>
/// <returns>
/// An XML serializer.
/// </returns>
[DebuggerHidden]
private static DataContractSerializer InitializeXmlSerializer() => new DataContractSerializer(ContractType, XmlSerializerSettings);
/// <summary>
/// Converts the specified JSON bit field to its typed equivalent.
/// </summary>
/// <param name="serializedObject">
/// A serialized object.
/// </param>
/// <returns>
/// The deserialized object.
/// </returns>
/// <exception cref="SerializationException">
/// <paramref name="serializedObject" /> is invalid or an error occurred during deserialization.
/// </exception>
[DebuggerHidden]
private T DeserializeFromJson(Byte[] serializedObject)
{
using (var stream = new MemoryStream(serializedObject))
{
try
{
return JsonSerializer.ReadObject(stream) as T ?? throw new SerializationException("The specified bit field is invalid.");
}
catch (SerializationException)
{
throw;
}
catch (Exception exception)
{
throw new SerializationException("An error occurred during deserialization. See inner exception.", exception);
}
}
}
/// <summary>
/// Converts the specified XML bit field to its typed equivalent.
/// </summary>
/// <param name="serializedObject">
/// A serialized object.
/// </param>
/// <returns>
/// The deserialized object.
/// </returns>
/// <exception cref="SerializationException">
/// <paramref name="serializedObject" /> is invalid or an error occurred during deserialization.
/// </exception>
[DebuggerHidden]
private T DeserializeFromXml(Byte[] serializedObject)
{
using (var stream = new MemoryStream(serializedObject))
{
try
{
return XmlSerializer.ReadObject(stream) as T ?? throw new SerializationException("The specified bit field is invalid.");
}
catch (SerializationException)
{
throw;
}
catch (Exception exception)
{
throw new SerializationException("An error occurred during deserialization. See inner exception.", exception);
}
}
}
/// <summary>
/// Converts the specified object to a JSON bit field.
/// </summary>
/// <param name="target">
/// An object to be serialized.
/// </param>
/// <returns>
/// The serialized bit field.
/// </returns>
/// <exception cref="SerializationException">
/// <paramref name="target" /> is invalid or an error occurred during serialization.
/// </exception>
[DebuggerHidden]
private Byte[] SerializeToJson(T target)
{
using (var stream = new MemoryStream())
{
try
{
JsonSerializer.WriteObject(stream, target);
}
catch (SerializationException)
{
throw;
}
catch (Exception exception)
{
throw new SerializationException("An error occurred during serialization. See inner exception.", exception);
}
return stream.ToArray();
}
}
/// <summary>
/// Converts the specified object to an XML bit field.
/// </summary>
/// <param name="target">
/// An object to be serialized.
/// </param>
/// <returns>
/// The serialized bit field.
/// </returns>
/// <exception cref="SerializationException">
/// <paramref name="target" /> is invalid or an error occurred during serialization.
/// </exception>
[DebuggerHidden]
private Byte[] SerializeToXml(T target)
{
using (var stream = new MemoryStream())
{
try
{
XmlSerializer.WriteObject(stream, target);
}
catch (SerializationException)
{
throw;
}
catch (Exception exception)
{
throw new SerializationException("An error occurred during serialization. See inner exception.", exception);
}
return stream.ToArray();
}
}
/// <summary>
/// Gets a JSON serializer.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private DataContractJsonSerializer JsonSerializer => LazyJsonSerializer.Value;
/// <summary>
/// Gets an XML serializer.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private DataContractSerializer XmlSerializer => LazyXmlSerializer.Value;
/// <summary>
/// Represents the type of the serializable object.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
protected static readonly Type ContractType = typeof(T);
/// <summary>
/// Represents the <see cref="DateTime" /> format string that is used for serialization.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private const String DateTimeSerializationFormatString = "o";
/// <summary>
/// Represents settings used by the JSON serializer.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private static readonly DataContractJsonSerializerSettings JsonSerializerSettings = new DataContractJsonSerializerSettings
{
DateTimeFormat = new DateTimeFormat(DateTimeSerializationFormatString),
EmitTypeInformation = EmitTypeInformation.AsNeeded,
SerializeReadOnlyTypes = false
};
/// <summary>
/// Represents settings used by the XML serializer.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private static readonly DataContractSerializerSettings XmlSerializerSettings = new DataContractSerializerSettings
{
PreserveObjectReferences = false,
SerializeReadOnlyTypes = false
};
/// <summary>
/// Represents a lazily-initialized JSON serializer.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Lazy<DataContractJsonSerializer> LazyJsonSerializer;
/// <summary>
/// Represents a lazily-initialized XML serializer.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Lazy<DataContractSerializer> LazyXmlSerializer;
}
/// <summary>
/// Performs serialization and deserialization for a given type.
/// </summary>
public abstract class DynamicSerializer
{
/// <summary>
/// Initializes a new instance of the <see cref="DynamicSerializer" /> class.
/// </summary>
protected DynamicSerializer()
: this(DefaultFormat)
{
return;
}
/// <summary>
/// Initializes a new instance of the <see cref="DynamicSerializer" /> class.
/// </summary>
/// <param name="format">
/// The format to use for serialization and deserialization.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="format" /> is equal to <see cref="SerializationFormat.Unspecified" />.
/// </exception>
protected DynamicSerializer(SerializationFormat format)
{
Format = format.RejectIf().IsEqualToValue(SerializationFormat.Unspecified, nameof(format));
}
/// <summary>
/// Converts the value of the current <see cref="DynamicSerializer" /> to its equivalent string representation.
/// </summary>
/// <returns>
/// A string representation of the current <see cref="DynamicSerializer" />.
/// </returns>
public override String ToString() => $"{{ \"{nameof(Format)}\": \"{Format}\" }}";
/// <summary>
/// Converts the specified bit field to its typed equivalent.
/// </summary>
/// <param name="serializedObject">
/// A serialized object.
/// </param>
/// <param name="targetType">
/// The type of the object to be deserialized.
/// </param>
/// <param name="format">
/// The format to use for deserialization.
/// </param>
/// <returns>
/// The deserialized object.
/// </returns>
/// <exception cref="SerializationException">
/// <paramref name="serializedObject" /> is invalid or an error occurred during deserialization.
/// </exception>
[DebuggerHidden]
internal static Object Deserialize(Byte[] serializedObject, Type targetType, SerializationFormat format)
{
try
{
var serializer = Create(targetType.RejectIf().IsNull(nameof(targetType)), format.RejectIf().IsEqualToValue(SerializationFormat.Unspecified));
var deserializeMethod = serializer.GetType().GetMethod(nameof(ISerializer<Object>.Deserialize));
return deserializeMethod.Invoke(serializer, new Object[] { serializedObject.RejectIf().IsNull(nameof(serializedObject)).TargetArgument });
}
catch (SerializationException)
{
throw;
}
catch (Exception exception)
{
throw new SerializationException("An error occurred during deserialization. See inner exception.", exception);
}
}
/// <summary>
/// Converts the specified object to a bit field.
/// </summary>
/// <param name="target">
/// An object to be serialized.
/// </param>
/// <param name="targetType">
/// The type of the object to be serialized.
/// </param>
/// <param name="format">
/// The format to use for serialization.
/// </param>
/// <returns>
/// The serialized bit field.
/// </returns>
/// <exception cref="SerializationException">
/// <paramref name="target" /> is invalid or an error occurred during serialization.
/// </exception>
[DebuggerHidden]
internal static Byte[] Serialize(Object target, Type targetType, SerializationFormat format)
{
try
{
var serializer = Create(targetType.RejectIf().IsNull(nameof(targetType)), format.RejectIf().IsEqualToValue(SerializationFormat.Unspecified));
var serializeMethod = serializer.GetType().GetMethod(nameof(ISerializer<Object>.Serialize));
return serializeMethod.Invoke(serializer, new Object[] { target.RejectIf().IsNull(nameof(target)).TargetArgument }) as Byte[];
}
catch (SerializationException)
{
throw;
}
catch (Exception exception)
{
throw new SerializationException("An error occurred during serialization. See inner exception.", exception);
}
}
/// <summary>
/// Converts the specified object to an encoded JSON string.
/// </summary>
/// <typeparam name="T">
/// The type of the object to be serialized.
/// </typeparam>
/// <param name="target">
/// An object to be serialized.
/// </param>
/// <returns>
/// An encoded JSON string.
/// </returns>
/// <exception cref="SerializationException">
/// <paramref name="target" /> is invalid or an error occurred during serialization.
/// </exception>
[DebuggerHidden]
internal static String SerializeToJsonString<T>(T target)
where T : class => Encoding.UTF8.GetString(CreateGeneric<T>(SerializationFormat.Json).Serialize(target));
/// <summary>
/// Converts the specified object to an encoded XML string.
/// </summary>
/// <typeparam name="T">
/// The type of the object to be serialized.
/// </typeparam>
/// <param name="target">
/// An object to be serialized.
/// </param>
/// <returns>
/// An encoded XML string.
/// </returns>
/// <exception cref="SerializationException">
/// <paramref name="target" /> is invalid or an error occurred during serialization.
/// </exception>
[DebuggerHidden]
internal static String SerializeToXmlString<T>(T target)
where T : class => Encoding.UTF8.GetString(CreateGeneric<T>(SerializationFormat.Xml).Serialize(target));
/// <summary>
/// Creates a new serializer for the specified contract type and format.
/// </summary>
/// <param name="targetType">
/// The type of the object to be serialized.
/// </param>
/// <param name="format">
/// The format to use for serialization and deserialization.
/// </param>
/// <returns>
/// A new serializer for the specified contract type and format.
/// </returns>
[DebuggerHidden]
private static Object Create(Type targetType, SerializationFormat format)
{
var createMethod = typeof(DynamicSerializer).GetMethod(nameof(CreateGeneric), BindingFlags.NonPublic | BindingFlags.Static);
var genericCreateMethod = createMethod.MakeGenericMethod(targetType);
return genericCreateMethod.Invoke(null, new Object[] { format });
}
/// <summary>
/// Creates a new serializer for the specified contract type and format.
/// </summary>
/// <typeparam name="T">
/// The type of the serializable object.
/// </typeparam>
/// <param name="format">
/// The format to use for serialization and deserialization.
/// </param>
/// <returns>
/// A new serializer for the specified contract type and format.
/// </returns>
[DebuggerHidden]
private static ISerializer<T> CreateGeneric<T>(SerializationFormat format)
where T : class => format switch
{
SerializationFormat.Binary => new Serializer<T>(),
SerializationFormat.CompressedJson => new CompressedJsonSerializer<T>(),
SerializationFormat.CompressedXml => new CompressedXmlSerializer<T>(),
SerializationFormat.Json => new JsonSerializer<T>(),
SerializationFormat.Xml => new XmlSerializer<T>(),
_ => throw new UnsupportedSpecificationException($"The specified serialization format, {format}, is not supported.")
};
/// <summary>
/// Gets the format to use for serialization and deserialization.
/// </summary>
public SerializationFormat Format
{
get;
private set;
}
/// <summary>
/// Represents the default format to use for serialization and deserialization.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal const SerializationFormat DefaultFormat = SerializationFormat.CompressedJson;
}
}