-
Notifications
You must be signed in to change notification settings - Fork 0
/
ResourceMapper.cs
526 lines (466 loc) · 21.7 KB
/
ResourceMapper.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using Transmute.Exceptions;
using Transmute.Internal;
using Transmute.Internal.Utils;
using Transmute.Maps;
using Transmute.MemberResolver;
using System.IO;
using Transmute.Builders;
namespace Transmute
{
public class ResourceMapper<TContext> : IResourceMapper<TContext>
where TContext : class
{
private readonly object _initializeLock = new object();
private readonly Dictionary<Type, Func<object>> _constructors = new Dictionary<Type, Func<object>>();
private readonly TypeDictionary<MapperAction<TContext>> _mapCache = new TypeDictionary<MapperAction<TContext>>();
private readonly TypeDictionary<IMap<TContext>> _mapInterfaces = new TypeDictionary<IMap<TContext>>();
private readonly TypeDictionary<RequiredMapEntry> _requiredMaps = new TypeDictionary<RequiredMapEntry>();
private readonly List<MapInfoEntry> _mapCreationInfo = new List<MapInfoEntry>();
private readonly List<ITypeMap<TContext>> _defaultMaps = new List<ITypeMap<TContext>>();
private readonly List<ITypeMap<TContext>> _maps = new List<ITypeMap<TContext>>();
private readonly PriorityList<IMemberConsumer> _memberConsumers = new PriorityList<IMemberConsumer>();
private readonly PriorityList<IMemberResolver> _memberResolvers = new PriorityList<IMemberResolver>();
private bool _diagnosticsEnabled = true;
private readonly IMapBuilder<TContext> _builder;
public ResourceMapper(MapBuilder builderType=MapBuilder.Delegate)
{
switch (builderType)
{
case MapBuilder.Delegate:
_builder = new DelegateBuilder<TContext>(this);
break;
case MapBuilder.Emit:
_builder = new EmitBuilder<TContext>(this);
break;
default:
throw new ArgumentOutOfRangeException("builderType");
}
_memberConsumers.Add(new DefaultMemberConsumer());
_memberResolvers.Add(new IgnoreCaseNameMatcher());
_defaultMaps.Add(new MapList<TContext>(this));
_defaultMaps.Add(new MapArray<TContext>(this));
_defaultMaps.Add(new MapEnum<TContext>());
_defaultMaps.Add(new MapByVal<TContext>());
_defaultMaps.Add(new MapNonNullableToNullable<TContext>(this));
_defaultMaps.Add(new MapNullableToNullable<TContext>(this));
}
public bool CanConstruct(Type type)
{
return _constructors.ContainsKey(type);
}
private Func<object> GetConstructor(Type type)
{
Func<object> constructor;
lock (_constructors)
{
if (!_constructors.TryGetValue(type, out constructor))
{
var constructorInfo = type.DefaultConstructor();
constructor = constructorInfo != null ? constructorInfo.CompileConstructor() : null;
_constructors[type] = constructor;
}
}
return constructor;
}
public object ConstructOrThrow(Type type)
{
AssertIsInitialized();
var constructor = GetConstructor(type);
if (constructor == null)
throw new MapperException(string.Format("Unable to construct {0}: No default constructor found", type));
return constructor();
}
public IMapBuilder<TContext> Builder { get { return _builder; } }
public string ExportedMapsDirectory { get; private set; }
public bool DiagnosticsEnabled { get {return _diagnosticsEnabled;} }
public bool IsInitialized { get; private set; }
public IPriorityList<IMemberConsumer> MemberConsumers { get { return _memberConsumers; } }
public IPriorityList<IMemberResolver> MemberResolvers { get { return _memberResolvers; } }
public IList<ITypeMap<TContext>> TypeMaps { get { return _maps; } }
#region ConvertUsing
public void ConvertUsing<TFrom, TTo>(Func<TFrom, TTo> convert)
{
ConvertUsing<TFrom, TTo>((from, to, context) => convert(from));
}
public void ConvertUsing<TFrom, TTo>(Func<TFrom, TTo, TContext, TTo> convert)
{
AssertIsNotInitialized();
AssertNoExistingMaps(typeof(TFrom), typeof(TTo));
MapperAction<TContext> mapperAction = (from, to, context) => convert((TFrom)from, (TTo)to, context);
_mapCache.Add(typeof(TFrom), typeof(TTo), mapperAction);
SetMapper(typeof(TFrom), typeof(TTo), mapperAction);
if(_diagnosticsEnabled)
_mapCreationInfo.Add(new MapInfoEntry(mapperAction));
}
public void ConvertUsing(Type from, Type to, Func<object, object> convert)
{
ConvertUsing(from, to, (ofrom, oto, context) => convert(ofrom));
}
public void ConvertUsing(Type from, Type to, Func<object, object, TContext, object> convert)
{
AssertIsNotInitialized();
AssertNoExistingMaps(from, to);
MapperAction<TContext> mapperAction = (ofrom, oto, context) => convert(ofrom, oto, context);
_mapCache.Add(from, to, mapperAction);
SetMapper(from, to, mapperAction);
if(_diagnosticsEnabled)
_mapCreationInfo.Add(new MapInfoEntry(mapperAction));
}
#endregion
#region RequireOneWayMap
public void RequireOneWayMap(Type fromType, Type toType, Type fromParentType, Type toParentType)
{
RequireOneWayMap(fromType, toType, string.Format("{0} => {1}", fromParentType, toParentType));
}
public void RequireOneWayMap(Type fromType, Type toType, string description)
{
RequiredMapEntry existingEntry;
if (!_requiredMaps.TryGetValue(fromType, toType, out existingEntry))
{
existingEntry = new RequiredMapEntry{Type1 = fromType, Type2 = toType};
_requiredMaps.Add(fromType, toType, existingEntry);
}
if(_diagnosticsEnabled)
{
existingEntry.Messages.Add(description);
}
}
public void RequireOneWayMap<TFrom, TTo, TFromParent, TToParent>()
{
RequireOneWayMap(typeof(TFrom), typeof(TTo), typeof(TFromParent), typeof(TToParent));
}
public void RequireOneWayMap<TFrom, TTo>(string description)
{
RequireOneWayMap(typeof(TFrom), typeof(TTo), description);
}
#endregion
#region RequireTwoWayMap
public void RequireTwoWayMap(Type type1, Type type2, Type parentType1, Type parentType2)
{
RequireOneWayMap(type1, type2, parentType1, parentType2);
RequireOneWayMap(type2, type1, parentType2, parentType1);
}
public void RequireTwoWayMap(Type type1, Type type2, string description)
{
RequireOneWayMap(type1, type2, description);
RequireOneWayMap(type2, type1, description);
}
public void RequireTwoWayMap<TType1, TType2, TParentType1, TParentType2>()
{
RequireTwoWayMap(typeof(TType1), typeof(TType2), typeof(TParentType1), typeof(TParentType2));
}
public void RequireTwoWayMap<TType1, TType2>(string description)
{
RequireTwoWayMap(typeof(TType1), typeof(TType2), description);
}
#endregion
public bool CanMap(Type from, Type to)
{
return _mapCache.ContainsKey(from, to) || _maps.Any(m => m.CanMap(from, to)) || _defaultMaps.Any(m => m.CanMap(from, to));
}
public void RegisterMapping(ITypeMap<TContext> map)
{
AssertIsNotInitialized();
_defaultMaps.Add(map);
if(_diagnosticsEnabled)
_mapCreationInfo.Add(new MapInfoEntry(map));
}
#region RegisterTwoWayMapping
public void RegisterTwoWayMapping<TType1, TType2>(ITwoWayMap<TType1, TType2, TContext> overrides)
{
InternalRegisterOneWayMappingAction<TType1, TType2>(overrides.Type1ToType2.OverrideMapping);
InternalRegisterOneWayMappingAction<TType2, TType1>(overrides.Type2ToType1.OverrideMapping);
}
public void RegisterTwoWayMapping<TFrom, TTo>()
{
InternalRegisterOneWayMappingAction<TFrom, TTo>(null);
InternalRegisterOneWayMappingAction<TTo, TFrom>(null);
}
public void RegisterTwoWayMapping<TFrom, TTo>(Action<IMappingCollection<TFrom, TTo, TContext>> type1Overrides, Action<IMappingCollection<TTo, TFrom, TContext>> type2Overrides)
{
InternalRegisterOneWayMappingAction(type1Overrides);
InternalRegisterOneWayMappingAction(type2Overrides);
}
public void RegisterTwoWayMapping<TMappingConvention>() where TMappingConvention : ITwoWayMap<TContext>, new()
{
var variable = new TMappingConvention();
InternalNonGenericRegisterOneWayMappingInterface(variable.Type1, variable.Type2, variable.Type1ToType2);
InternalNonGenericRegisterOneWayMappingInterface(variable.Type2, variable.Type1, variable.Type2ToType1);
}
#endregion
#region RegisterOneWayMapping
public void RegisterOneWayMapping(Type from, Type to)
{
InternalNonGenericRegisterOneWayMappingAction(from, to, null);
}
public void RegisterOneWayMapping<TFrom, TTo>()
{
InternalRegisterOneWayMappingAction<TFrom, TTo>(null);
}
public void RegisterOneWayMapping<TFrom, TTo>(Action<IMappingCollection<TFrom, TTo, TContext>> overrides)
{
InternalRegisterOneWayMappingAction(overrides);
}
public void RegisterOneWayMapping<TFrom, TTo>(IOneWayMap<TFrom, TTo, TContext> overrides)
{
InternalRegisterOneWayMappingAction<TFrom, TTo>(overrides.OverrideMapping);
}
public void RegisterOneWayMapping<TMappingConvention>() where TMappingConvention : IOneWayMap<TContext>, new()
{
var convention = new TMappingConvention();
InternalNonGenericRegisterOneWayMappingInterface(convention.FromType, convention.ToType, convention);
}
#endregion
private void InternalNonGenericRegisterOneWayMappingAction(Type from, Type to, object overrides)
{
try
{
GetType().GetMethod("InternalRegisterOneWayMappingAction", BindingFlags.Default | BindingFlags.NonPublic | BindingFlags.Instance)
.MakeGenericMethod(from, to)
.Invoke(this, new[] {overrides});
}
catch(TargetInvocationException e)
{
throw e.InnerException;
}
}
private void InternalNonGenericRegisterOneWayMappingInterface(Type from, Type to, object overrides)
{
try
{
GetType().GetMethod("InternalRegisterOneWayMappingInterface", BindingFlags.Default | BindingFlags.NonPublic | BindingFlags.Instance)
.MakeGenericMethod(from, to)
.Invoke(this, new[] { overrides });
}
catch (TargetInvocationException e)
{
throw e.InnerException;
}
}
// ReSharper disable UnusedMember.Local
private void InternalRegisterOneWayMappingInterface<TFrom, TTo>(IOneWayMap<TFrom, TTo, TContext> overrides)
{
InternalRegisterOneWayMappingAction<TFrom, TTo>(overrides.OverrideMapping);
}
// ReSharper restore UnusedMember.Local
private void InternalRegisterOneWayMappingAction<TFrom, TTo>(Action<IMappingCollection<TFrom, TTo, TContext>> overrides)
{
AssertIsNotInitialized();
StackTrace stackTrace = null;
if(_diagnosticsEnabled)
{
stackTrace = CaptureStackTrace();
}
RequireOneWayMap<TFrom, TTo>(stackTrace != null ? stackTrace.ToString() : "unknown");
var map = new MapObject<TFrom, TTo, TContext>(this);
AssertNoExistingMaps(typeof(TFrom), typeof(TTo));
_maps.Add(map);
if(_diagnosticsEnabled)
_mapCreationInfo.Add(new MapInfoEntry(map));
if (overrides != null)
map.AcceptOverrides(overrides);
}
public void RegisterConstructor(Type type, Func<object> constructor)
{
AssertIsNotInitialized();
_constructors.Add(type, constructor);
}
public void RegisterConstructor<TType>(Func<TType> constructor)
{
AssertIsNotInitialized();
_constructors.Add(typeof(TType), () => constructor());
}
public TTo Map<TFrom, TTo>(TFrom from, TTo to, TContext context)
{
return (TTo) Map(typeof (TFrom), typeof (TTo), from, to, context);
}
public TTo Map<TFrom, TTo>(TFrom from, TContext context)
{
return (TTo)Map(typeof(TFrom), typeof(TTo), from, default(TTo), context);
}
public object Map(Type fromType, Type toType, object from, object to, TContext context)
{
AssertIsInitialized();
if (from == null)
{
to = toType.IsValueType ? Activator.CreateInstance(toType) : null;
return to;
}
var setter = GetMapperFor(fromType, toType);
to = setter(from, to, context);
return to;
}
private MapperAction<TContext> GetMapperFor(Type fromType, Type toType)
{
MapperAction<TContext> setter;
if (!_mapCache.TryGetValue(fromType, toType, out setter))
{
var additionalInfo = string.Empty;
if (CanMap(fromType, toType))
{
additionalInfo = " A map creator is available, so it is likely a RequireMap call is missing on the resource mapper setup";
}
throw new MapperException(string.Format("Unable to map from {0} to {1}.{2}", fromType, toType, additionalInfo));
}
return setter;
}
public IMap<TContext> GetMapper(Type from, Type to)
{
IMap<TContext> mapper;
if(!_mapInterfaces.TryGetValue(from, to, out mapper))
{
if(IsInitialized)
{
var additionalInfo = string.Empty;
if (CanMap(from, to))
{
additionalInfo = " A map creator is available, so it is likely a RequireMap call is missing on the resource mapper setup";
}
throw new MapperException(string.Format("Unable to map from {0} to {1}.{2}", from, to, additionalInfo));
}
mapper = (IMap<TContext>)typeof(FuncBasedMap<,,>).MakeGenericType(from, to, typeof(TContext))
.GetConstructor(new Type[0]).Invoke(new object[0]);
_mapInterfaces.Add(from, to, mapper);
}
return (IMap<TContext>)mapper;
}
public IMap<TFrom, TTo, TContext> GetMapper<TFrom, TTo>()
{
return (IMap<TFrom, TTo, TContext>)GetMapper(typeof(TFrom), typeof(TTo));
}
private void InternalSetMapper<TFrom, TTo>(MapperAction<TContext> action)
{
((FuncBasedMap<TFrom, TTo, TContext>)GetMapper<TFrom, TTo>()).ConvertMethod = (from, to, context) => (TTo)action(from, to, context);
}
private void SetMapper(Type from, Type to, MapperAction<TContext> action)
{
GetType().GetMethod("InternalSetMapper", BindingFlags.Default | BindingFlags.NonPublic | BindingFlags.Instance)
.MakeGenericMethod(from, to)
.Invoke(this, new[] { action });
}
public void DeactivateDiagnostics()
{
_diagnosticsEnabled = false;
}
public void ExportMapsTo(string filename)
{
_diagnosticsEnabled = true;
ExportedMapsDirectory = filename;
}
public void InitializeMap()
{
if (IsInitialized)
return;
lock (_initializeLock)
{
if (IsInitialized)
return;
if(_diagnosticsEnabled
&& !string.IsNullOrEmpty(ExportedMapsDirectory)
&& !Directory.Exists(ExportedMapsDirectory))
{
Directory.CreateDirectory(ExportedMapsDirectory);
}
var missingMaps = new List<RequiredMapEntry>();
var uninitialisedMaps = _requiredMaps.Where(e => !_mapCache.ContainsKey(e.Value.Type1, e.Value.Type2)
&& !missingMaps.Contains(e.Value)).ToArray();
while (uninitialisedMaps.Length > 0)
{
foreach (var requiredMap in uninitialisedMaps)
{
var fromType = requiredMap.Value.Type1;
var toType = requiredMap.Value.Type2;
// This will initialize the map cache for these items
var map = _maps.LastOrDefault(m => m.CanMap(fromType, toType))
?? _defaultMaps.LastOrDefault(m => m.CanMap(fromType, toType));
if (map == null)
{
missingMaps.Add(requiredMap.Value);
}
else
{
var initializableMap = map as IInitializableMap;
if (initializableMap != null)
initializableMap.Initialize();
var setter = map.GetMapper(fromType, toType);
_mapCache.Add(fromType, toType, setter);
SetMapper(fromType, toType, setter);
}
}
uninitialisedMaps = _requiredMaps.Where(e => !_mapCache.ContainsKey(e.Value.Type1, e.Value.Type2)
&& !missingMaps.Contains(e.Value)).ToArray();
}
if(missingMaps.Count > 0)
{
var reportString = new StringBuilder();
foreach (var missingMap in missingMaps)
{
reportString.AppendLine(string.Format("{0} to {1}: Required by {2}", missingMap.Type1,
missingMap.Type2, string.Join(", ", missingMap.Messages.ToArray())));
}
throw new MapperException(string.Format("Unable to complete maps. One or more required maps could not be found.\n{0}", reportString));
}
if(_mapInterfaces.Any(m => !m.Value.IsInitialized))
{
throw new MapperException(string.Format("Unable to complete maps. One or more required maps could not be found."));
}
_builder.FinalizeBuilder();
IsInitialized = true;
}
}
private void AssertIsNotInitialized()
{
if(IsInitialized)
throw new MapperInitializedException();
}
private void AssertIsInitialized()
{
if (!IsInitialized)
throw new MapperNotInitializedException();
}
private void AssertNoExistingMaps(Type fromType, Type toType)
{
var existing = _maps.FirstOrDefault(m => m.CanMap(fromType, toType));
if (existing != null)
{
var info = _mapCreationInfo.FirstOrDefault(m => ReferenceEquals(m.Map, existing));
throw new DuplicateMapperException(fromType, toType, info != null ? info.Creator.ToString() : "unknown");
}
MapperAction<TContext> setter;
if (_mapCache.TryGetValue(fromType, toType, out setter))
{
var info = _mapCreationInfo.FirstOrDefault(m => ReferenceEquals(m.Map, setter));
throw new DuplicateMapperException(fromType, toType, info != null ? info.Creator.ToString() : "unknown");
}
}
private static StackTrace CaptureStackTrace()
{
#if SILVERLIGHT
return null;
#else
var stackTrace = new StackTrace();
int skipFrames = stackTrace.GetFrames().TakeWhile(stackFrame => stackFrame.GetMethod().DeclaringType.Assembly == typeof(MapHelpers).Assembly).Count();
skipFrames--;
return new StackTrace(skipFrames, true);
#endif
}
private class MapInfoEntry
{
private readonly object _map;
private readonly StackTrace _creator;
public MapInfoEntry(object map)
{
_map = map;
_creator = CaptureStackTrace();
}
public object Map { get { return _map; } }
public StackTrace Creator { get { return _creator; } }
}
}
}