-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathDefaultSerialization.cs
More file actions
337 lines (294 loc) · 13.3 KB
/
DefaultSerialization.cs
File metadata and controls
337 lines (294 loc) · 13.3 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
// Copyright (c) 2023, Phoenix Contact GmbH & Co. KG
// Licensed under the Apache License, Version 2.0
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Moryx.Configuration;
using Moryx.Tools;
namespace Moryx.Serialization
{
/// <summary>
/// Default implementation of serialization
/// </summary>
public class DefaultSerialization : ICustomSerialization
{
/// <summary>
/// Constructor to construct a <see cref="DefaultSerialization"/> instance
/// </summary>
public DefaultSerialization()
{
FormatProvider = Thread.CurrentThread.CurrentCulture;
}
/// <inheritdoc />
public IFormatProvider FormatProvider { get; set; }
/// <see cref="ICustomSerialization"/>
public virtual IEnumerable<PropertyInfo> GetProperties(Type sourceType)
{
return sourceType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
}
/// <see cref="ICustomSerialization"/>
public virtual EntryPrototype[] Prototypes(Type memberType, ICustomAttributeProvider attributeProvider)
{
// Check if it is a list, array or dictionary
if (EntryConvert.IsCollection(memberType))
{
memberType = EntryConvert.ElementType(memberType);
}
List<EntryPrototype> prototypes = new List<EntryPrototype>();
if (memberType == typeof(string))
{
prototypes.Add(new EntryPrototype(nameof(String), string.Empty));
}
else if (memberType.IsEnum)
{
foreach (Enum enumValue in Enum.GetValues(memberType))
prototypes.Add(new EntryPrototype(enumValue.ToString("G"), enumValue));
}
else
{
// check if this member is abstract
if (memberType.IsAbstract) return prototypes.ToArray();
var prototype = Activator.CreateInstance(memberType);
if (memberType.IsClass)
ValueProviderExecutor.Execute(prototype, new ValueProviderExecutorSettings().AddDefaultValueProvider());
prototypes.Add(new EntryPrototype(memberType.Name, prototype));
}
return prototypes.ToArray();
}
/// <see cref="ICustomSerialization"/>
public virtual string[] PossibleValues(Type memberType, ICustomAttributeProvider attributeProvider)
{
// Element type for collections
var isCollection = EntryConvert.IsCollection(memberType);
if (isCollection)
memberType = EntryConvert.ElementType(memberType);
// Enum names, member name or null
return memberType.IsEnum
? Enum.GetNames(memberType)
: isCollection ? new[] { memberType.Name } : null;
}
/// <see cref="ICustomSerialization"/>
public virtual string[] PossibleElementValues(Type memberType, ICustomAttributeProvider attributeProvider)
{
var elementType = EntryConvert.ElementType(memberType);
return PossibleValues(elementType, attributeProvider);
}
/// <see cref="ICustomSerialization"/>
public virtual EntryValidation CreateValidation(Type memberType, ICustomAttributeProvider attributeProvider)
{
var validation = new EntryValidation();
var validationAttributes = attributeProvider.GetCustomAttributes<ValidationAttribute>();
if (validationAttributes.Length == 0)
return validation;
// Iterate over attributes reading all validation rules
foreach (var attribute in validationAttributes)
{
if (attribute is MinLengthAttribute minAttribute)
{
validation.Minimum = minAttribute.Length;
}
else if (attribute is MaxLengthAttribute maxAttribute)
{
validation.Maximum = maxAttribute.Length;
}
else if (attribute is RangeAttribute rangeAttribute)
{
validation.Minimum = Convert.ToDouble(rangeAttribute.Minimum);
validation.Maximum = Convert.ToDouble(rangeAttribute.Maximum);
}
else if (attribute is RegularExpressionAttribute regexAttribute)
validation.Regex = regexAttribute.Pattern;
else if (attribute is StringLengthAttribute strLength)
{
validation.Minimum = strLength.MinimumLength;
validation.Maximum = strLength.MaximumLength;
}
else if (attribute is RequiredAttribute)
validation.IsRequired = true;
}
return validation;
}
/// <see cref="ICustomSerialization"/>
public virtual IEnumerable<MethodInfo> GetMethods(Type sourceType)
{
return sourceType.GetMethods().Where(m => !m.IsSpecialName);
}
/// <see cref="ICustomSerialization"/>
public virtual IEnumerable<ConstructorInfo> GetConstructors(Type sourceType)
{
return sourceType.GetConstructors();
}
/// <see cref="ICustomSerialization"/>
public virtual IEnumerable<MappedProperty> WriteFilter(Type sourceType, IEnumerable<Entry> encoded)
{
// Return pairs where available
return from entry in encoded
let property = sourceType.GetProperty(entry.Identifier)
select new MappedProperty
{
Entry = entry,
Property = property
};
}
/// <see cref="ICustomSerialization"/>
public virtual object DefaultValue(PropertyInfo property, object currentValue)
{
// No default is better than the current value
if (currentValue != null)
return currentValue;
// Try to read default from attribute
var defaultAtt = property.GetCustomAttribute<DefaultValueAttribute>();
if (defaultAtt != null)
return defaultAtt.Value;
// For arrays create empty element array
if (property.PropertyType.IsArray)
return Array.CreateInstance(property.PropertyType.GetElementType(), 0);
// In all other cases use the activator
return Activator.CreateInstance(property.PropertyType);
}
/// <see cref="ICustomSerialization"/>
public virtual object ConvertValue(Type memberType, ICustomAttributeProvider attributeProvider, Entry mappedEntry, object currentValue)
{
// Other operations depend on the element type
switch (mappedEntry.Value.Type)
{
case EntryValueType.Stream:
Stream targetStream;
var safeContent = mappedEntry.Value.Current ?? "";
var contentBytes = Convert.FromBase64String(safeContent);
var currentStream = currentValue as Stream;
var createNewMemoryStream = currentStream == null || !currentStream.CanWrite;
if (!createNewMemoryStream &&
currentStream.GetType() == typeof(MemoryStream) &&
currentStream.Length < contentBytes.Length)
{
// MemoryStream is not expandable
createNewMemoryStream = true;
}
if (currentStream != null && !createNewMemoryStream)
{
if (currentStream.CanSeek)
currentStream.Seek(0, SeekOrigin.Begin);
targetStream = currentStream;
targetStream.Write(contentBytes, 0, contentBytes.Length);
targetStream.SetLength(contentBytes.Length);
}
else
{
currentStream?.Dispose();
targetStream = new MemoryStream(contentBytes);
}
return targetStream;
case EntryValueType.Class:
return currentValue ?? Activator.CreateInstance(memberType);
case EntryValueType.Collection:
return CollectionBuilder(memberType, currentValue, mappedEntry);
default:
var value = mappedEntry.Value.Current;
if (value is null)
return null;
try
{
return EntryConvert.ToObject(memberType, value, FormatProvider);
}
catch (Exception e)
{
if (e is FormatException or OverflowException)
throw new ArgumentException($"Invalid value {mappedEntry.Value.Current} for entry {mappedEntry.DisplayName ?? mappedEntry.Identifier}", e);
throw;
}
}
}
/// <see cref="ICustomSerialization"/>
public virtual object CreateInstance(Type memberType, ICustomAttributeProvider attributeProvider, Entry encoded)
{
if (EntryConvert.IsCollection(memberType))
{
memberType = EntryConvert.ElementType(memberType);
}
return CreateInstance(memberType, encoded);
}
/// <inheritdoc />
public EntryUnitType GetUnitTypeByAttributes(ICustomAttributeProvider property)
{
var unitType = EntryUnitType.None;
if (HasFlagsAttribute(property))
unitType = EntryUnitType.Flags;
var passwordAttr = property.GetCustomAttribute<PasswordAttribute>();
if (passwordAttr != null)
unitType = EntryUnitType.Password;
var fileAttr = property.GetCustomAttribute<FileSystemPathAttribute>();
if (fileAttr != null)
{
switch (fileAttr.Type)
{
case FileSystemPathType.File:
unitType = EntryUnitType.File;
break;
case FileSystemPathType.Directory:
unitType = EntryUnitType.Directory;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return unitType;
}
/// <see cref="ICustomSerialization"/>
public virtual object CreateInstance(Type elementType, Entry entry)
{
return Activator.CreateInstance(elementType);
}
/// <summary>
/// Build collection object from entry
/// </summary>
protected static object CollectionBuilder(Type collectionType, object currentValue, Entry collectionEntry)
{
// Arrays must be recreated whenever their size changes
if (collectionType.IsArray)
{
var currentArray = (Array)currentValue;
var size = collectionEntry.SubEntries.Count;
return currentArray != null && currentArray.Length == size
? currentArray : Array.CreateInstance(collectionType.GetElementType(), size);
}
// Create instance for collections of type Dictionary
if (EntryConvert.IsDictionary(collectionType))
{
// Use dictionary when interface where used
if (collectionType.IsInterface)
collectionType = typeof(Dictionary<,>).MakeGenericType(collectionType.GenericTypeArguments);
// Reuse current object if available
return currentValue ?? Activator.CreateInstance(collectionType);
}
// Create instance for collections of type list
if (typeof(IEnumerable).IsAssignableFrom(collectionType))
{
// Use lists when interfaces where used
if (collectionType.IsInterface)
collectionType = typeof(List<>).MakeGenericType(collectionType.GenericTypeArguments);
// Reuse current object if available
return currentValue ?? Activator.CreateInstance(collectionType);
}
// Other collections are not supported
return null;
}
/// <summary>
/// Checks if the given property is an enum and has the <see cref="System.FlagsAttribute"/>.
/// </summary>
/// <param name="property">The property to inspect for attributes.</param>
/// <returns>True if the property has the Flags attribute; otherwise, false.</returns>
private bool HasFlagsAttribute(ICustomAttributeProvider property)
{
return property is PropertyInfo propertyInfo &&
propertyInfo.PropertyType.IsEnum &&
propertyInfo.PropertyType.GetCustomAttributes(typeof(System.FlagsAttribute), false).Any();
}
}
}