-
Notifications
You must be signed in to change notification settings - Fork 28
/
ObjectFactory.cs
374 lines (313 loc) · 13.7 KB
/
ObjectFactory.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
#region Copyright © 2010 Pawel Idzikowski [idzikowski@sharpserializer.com]
// ***********************************************************************
// Project: sharpSerializer
// Web: http://www.sharpserializer.com
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the author(s) be held liable for any damages arising from
// the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
// ***********************************************************************
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using Polenter.Serialization.Core;
namespace Polenter.Serialization.Deserializing
{
/// <summary>
/// Takes Property and converts it to an object
/// </summary>
public sealed class ObjectFactory
{
public ObjectFactory()
: this(new DefaultInstanceCreator())
{
}
public ObjectFactory(IInstanceCreator instanceCreator)
{
this.InstanceCreator = instanceCreator;
}
private readonly object[] _emptyObjectArray = new object[0];
/// <summary>
/// Contains already created objects. Is used for reference resolving.
/// </summary>
private readonly Dictionary<int, object > _objectCache = new Dictionary<int, object>();
/// <summary>
/// Gets or sets the instance creator.
/// </summary>
/// <value>The instance creator.</value>
private IInstanceCreator InstanceCreator { get; set; }
/// <summary>
/// Builds object from property
/// </summary>
/// <param name = "property"></param>
/// <returns></returns>
public object CreateObject(Property property)
{
if (property == null) throw new ArgumentNullException("property");
// Is it NullProperty?
var nullProperty = property as NullProperty;
if (nullProperty != null)
{
return null;
}
if (property.Type == null)
{
// there is no property type and no expected type defined. Give up!
throw new InvalidOperationException(string.Format("Property type is not defined. Property: \"{0}\"",
property.Name));
}
// Is it SimpleProperty?
var simpleProperty = property as SimpleProperty;
if (simpleProperty != null)
{
return createObjectFromSimpleProperty(simpleProperty);
}
var referenceTarget = property as ReferenceTargetProperty;
if (referenceTarget == null)
return null;
if (referenceTarget.Reference != null)
{
if (!referenceTarget.Reference.IsProcessed)
{
// object was created already
// get object from cache
return _objectCache[referenceTarget.Reference.Id];
}
}
object value = createObjectCore(referenceTarget);
if (value != null)
return value;
// No idea what it is
throw new InvalidOperationException(string.Format("Unknown Property type: {0}", property.GetType().Name));
}
private object createObjectCore(ReferenceTargetProperty property)
{
// Is it multidimensional array?
var multiDimensionalArrayProperty = property as MultiDimensionalArrayProperty;
if (multiDimensionalArrayProperty != null)
{
return createObjectFromMultidimensionalArrayProperty(multiDimensionalArrayProperty);
}
// Is it singledimensional array?
var singleDimensionalArrayProperty = property as SingleDimensionalArrayProperty;
if (singleDimensionalArrayProperty != null)
{
return createObjectFromSingleDimensionalArrayProperty(singleDimensionalArrayProperty);
}
// Is it dictionary?
var dictionaryProperty = property as DictionaryProperty;
if (dictionaryProperty != null)
{
return createObjectFromDictionaryProperty(dictionaryProperty);
}
// Is it collection?
var collectionProperty = property as CollectionProperty;
if (collectionProperty != null)
{
return createObjectFromCollectionProperty(collectionProperty);
}
// Is it complex type? Class? Structure?
var complexProperty = property as ComplexProperty;
if (complexProperty != null)
{
return createObjectFromComplexProperty(complexProperty);
}
return null;
}
private static object createObjectFromSimpleProperty(SimpleProperty property)
{
return property.Value;
}
private object createObjectFromComplexProperty(ComplexProperty property)
{
object obj = this.InstanceCreator.CreateInstance(property.Type);
if (property.Reference != null)
{
// property has Reference, only objects referenced multiple times
// have properties with references. Object must be cached to
// resolve its references in the future.
_objectCache.Add(property.Reference.Id, obj);
}
fillProperties(obj, property.Properties);
return obj;
}
private object createObjectFromCollectionProperty(CollectionProperty property)
{
Type type = property.Type;
object collection = this.InstanceCreator.CreateInstance(type);
if (property.Reference != null)
{
// property has Reference, only objects referenced multiple times
// have properties with references. Object must be cached to
// resolve its references in the future.
_objectCache.Add(property.Reference.Id, collection);
}
// fill the properties
fillProperties(collection, property.Properties);
// Fill the items but only if the "Add" method was found, which has only 1 parameter
MethodInfo methodInfo = collection.GetType().GetMethod("Add");
if (methodInfo != null)
{
ParameterInfo[] parameters = methodInfo.GetParameters();
if (parameters.Length == 1)
{
foreach (Property item in property.Items)
{
object value = CreateObject(item);
methodInfo.Invoke(collection, new[] {value});
}
}
}
return collection;
}
/// <summary>
/// Items will be added only if the "Add" method was found, which exactly 2 parameters (key, value) has
/// </summary>
/// <param name = "property"></param>
/// <returns></returns>
private object createObjectFromDictionaryProperty(DictionaryProperty property)
{
object dictionary = this.InstanceCreator.CreateInstance(property.Type);
if (property.Reference != null)
{
// property has Reference, only objects referenced multiple times
// have properties with references. Object must be cached to
// resolve its references in the future.
_objectCache.Add(property.Reference.Id, dictionary);
}
// fill the properties
fillProperties(dictionary, property.Properties);
// fill items, but only if Add(key, value) was found
MethodInfo methodInfo = dictionary.GetType().GetMethod("Add");
if (methodInfo != null)
{
ParameterInfo[] parameters = methodInfo.GetParameters();
if (parameters.Length == 2)
{
foreach (KeyValueItem item in property.Items)
{
object keyValue = CreateObject(item.Key);
object valueValue = CreateObject(item.Value);
methodInfo.Invoke(dictionary, new[] {keyValue, valueValue});
}
}
}
return dictionary;
}
/// <summary>
/// Fill properties of the class or structure
/// </summary>
/// <param name = "obj"></param>
/// <param name = "properties"></param>
private void fillProperties(object obj, IEnumerable<Property> properties)
{
foreach (Property property in properties)
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(property.Name);
if (propertyInfo == null) continue;
if (propertyInfo.CanWrite == false)
{
continue;
}
object value = CreateObject(property);
if (value == null) continue;
propertyInfo.SetValue(obj, value, _emptyObjectArray);
}
}
private object createObjectFromSingleDimensionalArrayProperty(SingleDimensionalArrayProperty property)
{
int itemsCount = property.Items.Count;
Array array = createArrayInstance(property.ElementType, new[] {itemsCount}, new[] {property.LowerBound});
if (property.Reference != null)
{
// property has Reference, only objects referenced multiple times
// have properties with references. Object must be cached to
// resolve its references in the future.
_objectCache.Add(property.Reference.Id, array);
}
// Items
for (int index = property.LowerBound; index < property.LowerBound + itemsCount; index++)
{
Property item = property.Items[index];
object value = CreateObject(item);
if (value != null)
{
array.SetValue(value, index);
}
}
return array;
}
private object createObjectFromMultidimensionalArrayProperty(MultiDimensionalArrayProperty property)
{
// determine array type
MultiDimensionalArrayCreatingInfo creatingInfo =
getMultiDimensionalArrayCreatingInfo(property.DimensionInfos);
// Instantiating the array
Array array = createArrayInstance(property.ElementType, creatingInfo.Lengths, creatingInfo.LowerBounds);
if (property.Reference != null)
{
// property has Reference, only objects referenced multiple times
// have properties with references. Object must be cached to
// resolve its references in the future.
_objectCache.Add(property.Reference.Id, array);
}
// fill the values
foreach (MultiDimensionalArrayItem item in property.Items)
{
object value = CreateObject(item.Value);
if (value != null)
{
array.SetValue(value, item.Indexes);
}
}
return array;
}
private static Array createArrayInstance(Type elementType, int[] lengths, int[] lowerBounds)
{
return Array.CreateInstance(elementType, lengths, lowerBounds);
}
/// <summary>
/// This internal class helps to instantiate the multidimensional array
/// </summary>
/// <param name = "infos"></param>
/// <returns></returns>
private static MultiDimensionalArrayCreatingInfo getMultiDimensionalArrayCreatingInfo(
IEnumerable<DimensionInfo> infos)
{
var lengths = new List<int>();
var lowerBounds = new List<int>();
foreach (DimensionInfo info in infos)
{
lengths.Add(info.Length);
lowerBounds.Add(info.LowerBound);
}
var result = new MultiDimensionalArrayCreatingInfo();
result.Lengths = lengths.ToArray();
result.LowerBounds = lowerBounds.ToArray();
return result;
}
#region Nested type: MultiDimensionalArrayCreatingInfo
private class MultiDimensionalArrayCreatingInfo
{
public int[] Lengths { get; set; }
public int[] LowerBounds { get; set; }
}
#endregion
}
}