/
Reflection.cs
687 lines (620 loc) · 21.6 KB
/
Reflection.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
// * **************************************************************************
// * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C.
// * This source code is subject to terms and conditions of the MIT License.
// * A copy of the license can be found in the License.txt file
// * at the root of this distribution.
// * By using this source code in any fashion, you are agreeing to be bound by
// * the terms of the MIT License.
// * You must not remove this notice from this software.
// * **************************************************************************
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using FastReflection;
using JetBrains.Annotations;
using MvbaCore.CodeQuery;
using MvbaCore.Collections;
namespace MvbaCore
{
public static class Reflection
{
public enum AccessorType
{
Field,
Property
}
// ReSharper disable InconsistentNaming
private static readonly StringDictionary _emptyCustomDestinationPropertyNameToSourcePropertyNameMap = new StringDictionary();
private static readonly LruCache<Type, Dictionary<string, GenericGetter>> _getters = new LruCache<Type, Dictionary<string, GenericGetter>>(50);
private static readonly LruCache<Type, Dictionary<string, GenericSetter>> _setters = new LruCache<Type, Dictionary<string, GenericSetter>>(50);
// ReSharper restore InconsistentNaming
/// <summary>
/// http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method
/// </summary>
[CanBeNull]
public static object CallGenericMethod<TContainer>([NotNull] TContainer container, [NotNull] Type genericType, [NotNull] string methodName, params object[] parameters)
{
MethodInfo method;
if (parameters == null || !parameters.Any())
{
method = typeof(TContainer).GetMethod(methodName);
}
else
{
var parameterTypes = parameters.Select(x => x == null ? typeof(object) : x.GetType()).ToArray();
method = typeof(TContainer).GetMethod(methodName, parameterTypes) ??
GetMethodExt(typeof(TContainer), methodName, BindingFlags.Public | BindingFlags.Instance, parameterTypes);
}
if (method == null)
return null;
var generic = method.MakeGenericMethod(genericType);
var result = generic.Invoke(container, parameters);
return result;
}
[Pure]
public static bool CouldBeNull([NotNull] Type type)
{
if (!type.IsValueType)
{
return true;
}
if (IsNullableValueType(type))
{
// e.g. decimal?
return true;
}
return false;
}
[Pure]
public static List<string> GetArguments<T, TReturn>([NotNull] Expression<Func<T, TReturn>> expression)
{
var methodCallExpression = expression.Body as MethodCallExpression;
if (methodCallExpression == null)
{
throw new ArgumentException("expression must be in the form: (Foo instance) => instance.Method");
}
var arguments = methodCallExpression.Arguments;
return arguments.Select(p => Expression.Lambda(p).Compile().DynamicInvoke().ToString()).ToList();
}
[Pure]
public static T GetAttribute<T>([NotNull] Assembly assembly)
{
return (T)assembly.GetCustomAttributes(typeof(T), false)[0];
}
[Pure]
public static string GetCamelCaseMultiLevelPropertyName(params string[] propertyNames)
{
return GetMultiLevelPropertyName(propertyNames).ToCamelCase();
}
[Pure]
public static string GetCamelCasePropertyName<T, TReturn>([NotNull] Expression<Func<T, TReturn>> expression)
{
return GetPropertyName(expression).ToCamelCase();
}
[Pure]
[NotNull]
public static string GetCamelCasePropertyNameWithPrefix<T, TReturn>([NotNull] Expression<Func<T, TReturn>> expression, [NotNull] string prefix)
{
return (prefix + GetPropertyName(expression)).ToCamelCase();
}
[Pure]
[NotNull]
public static string GetCamelCasePropertyNameWithPrefix<T>([NotNull] Expression<Func<T>> expression, [NotNull] string prefix)
{
return string.Format("{0}.{1}", prefix, GetPropertyName(expression).ToCamelCase()).ToCamelCase();
}
[Pure]
public static string GetClassName<T>()
{
return typeof(T).Name;
}
[Pure]
public static string GetControllerName<TControllerType>()
{
var name = typeof(TControllerType).Name;
return GetControllerName(name);
}
[Pure]
public static string GetControllerName(string name)
{
const string controller = "Controller";
if (name.EndsWith(controller))
{
name = name.Substring(0, name.Length - controller.Length);
}
return name;
}
[Pure]
private static Dictionary<string, GenericSetter> GetDestinationAccessors(Type destinationType)
{
var destinationAccessors = _setters[destinationType];
if (destinationAccessors == null)
{
var destinationFields = destinationType
.GetFields()
.Where(x => !x.IsLiteral)
.Select(x => new GenericSetter
{
Name = x.Name,
StorageType = x.FieldType,
SetValue = (Action<object, object>)x.SetValue,
AccessorType = AccessorType.Field
});
var destinationProperties = destinationType
.GetProperties()
.ThatHaveASetter()
.Select(x =>
{
var fastProperty = new FastProperty(x);
return new GenericSetter
{
Name = x.Name,
StorageType = x.PropertyType,
SetValue = fastProperty.CanWrite ? fastProperty.Set : (Action<object, object>)null,
AccessorType = AccessorType.Property
};
})
.Where(x => x.SetValue != null);
destinationAccessors = new Dictionary<string, GenericSetter>(100);
foreach (var accessor in destinationProperties.Concat(destinationFields))
{
destinationAccessors.Add(accessor.Name.ToLower(), accessor);
}
_setters.Add(destinationType, destinationAccessors);
}
return destinationAccessors;
}
[Pure]
[DebuggerStepThrough]
public static string GetFinalPropertyName<T>(Expression<Func<T>> expression)
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("expression must be in the form: () => instance.Property");
}
var names = GetNames(memberExpression);
return names.Last();
}
[Pure]
[DebuggerStepThrough]
public static string GetFinalPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("expression must be in the form: () => instance.Property");
}
var names = GetNames(memberExpression);
return names.Last();
}
[Pure]
[NotNull]
[ItemNotNull]
public static IEnumerable<PropertyMappingInfo> GetMatchingFieldsAndProperties([NotNull] Type sourceType, [NotNull] Type destinationType)
{
return GetMatchingFieldsAndProperties(sourceType, destinationType, _emptyCustomDestinationPropertyNameToSourcePropertyNameMap);
}
[Pure]
[NotNull]
[ItemNotNull]
public static IEnumerable<PropertyMappingInfo> GetMatchingFieldsAndProperties([NotNull] Type sourceType, [NotNull] Type destinationType, [NotNull] StringDictionary customDestinationPropertyNameToSourcePropertyNameMap)
{
var lowerCustomDictionary = new StringDictionary();
foreach (var item in customDestinationPropertyNameToSourcePropertyNameMap.Keys.Cast<string>())
{
lowerCustomDictionary.Add(item.ToLower(), customDestinationPropertyNameToSourcePropertyNameMap[item].ToLower());
}
var sourceAccessors = GetSourceAccessors(sourceType);
var destinationAccessors = GetDestinationAccessors(destinationType);
return (from entry in destinationAccessors
let key = lowerCustomDictionary[entry.Key] ?? entry.Key
where sourceAccessors.ContainsKey(key)
let sourceAccessor = sourceAccessors[key]
let destinationAccessor = entry.Value
select new PropertyMappingInfo
{
Name = destinationAccessor.Name,
SourcePropertyType = sourceAccessor.StorageType,
DestinationPropertyType = destinationAccessor.StorageType,
GetValueFromSource = sourceAccessor.GetValue,
SetValueToDestination = destinationAccessor.SetValue
}).ToList();
}
[Pure]
[NotNull]
[ItemNotNull]
public static IEnumerable<PropertyMappingInfo> GetMatchingProperties([NotNull] Type sourceType, [NotNull] Type destinationType)
{
return GetMatchingProperties(sourceType, destinationType, _emptyCustomDestinationPropertyNameToSourcePropertyNameMap);
}
[Pure]
[NotNull]
[ItemNotNull]
public static IEnumerable<PropertyMappingInfo> GetMatchingProperties([NotNull] Type sourceType, [NotNull] Type destinationType, [NotNull] StringDictionary customDestinationPropertyNameToSourcePropertyNameMap)
{
var lowerCustomDictionary = new StringDictionary();
foreach (var item in customDestinationPropertyNameToSourcePropertyNameMap.Keys.Cast<string>())
{
lowerCustomDictionary.Add(item.ToLower(), customDestinationPropertyNameToSourcePropertyNameMap[item].ToLower());
}
var sourceAccessors = GetSourceAccessors(sourceType);
var destinationAccessors = GetDestinationAccessors(destinationType);
return (from entry in destinationAccessors
let key = lowerCustomDictionary[entry.Key] ?? entry.Key
where sourceAccessors.ContainsKey(key)
let sourceAccessor = sourceAccessors[key]
let destinationAccessor = entry.Value
where sourceAccessor.AccessorType == AccessorType.Property
where destinationAccessor.AccessorType == AccessorType.Property
select new PropertyMappingInfo
{
Name = destinationAccessor.Name,
SourcePropertyType = sourceAccessor.StorageType,
DestinationPropertyType = destinationAccessor.StorageType,
GetValueFromSource = sourceAccessor.GetValue,
SetValueToDestination = destinationAccessor.SetValue
}).ToList();
}
[Pure]
[NotNull]
public static MethodCallData GetMethodCallData<TClass>([NotNull] Expression<Func<TClass, object>> methodCall) where TClass : class
{
var className = typeof(TClass).Name;
var methodName = GetMethodName(methodCall);
var expression = GetMethodCallExpression(methodCall);
var parameters = expression.Method.GetParameters();
var parameterDictionary = parameters.Select((x, i) => new
{
x.Name,
Value = GetValueAsString(expression.Arguments[i])
}
).ToDictionary(x => x.Name, x => x.Value);
return new MethodCallData
{
MethodName = methodName,
ClassName = className,
ParameterValues = parameterDictionary
};
}
[Pure]
[NotNull]
public static MethodCallExpression GetMethodCallExpression<T, TReturn>([NotNull] Expression<Func<T, TReturn>> expression)
{
var methodCallExpression = expression.Body as MethodCallExpression;
if (methodCallExpression == null)
{
var unaryExpression = expression.Body as UnaryExpression;
if (unaryExpression == null)
{
throw new ArgumentException(
"expression must be in the form: (Foo instance) => instance.Method()");
}
methodCallExpression = unaryExpression.Operand as MethodCallExpression;
if (methodCallExpression == null)
{
throw new ArgumentException(
"expression must be in the form: (Foo instance) => instance.Method()");
}
}
return methodCallExpression;
}
/// <summary>
/// Search for a method by name, parameter types, and binding flags. Unlike GetMethod(), does 'loose' matching on
/// generic
/// parameter types, and searches base interfaces.
/// </summary>
/// <exception cref="AmbiguousMatchException" />
[Pure]
[CanBeNull]
private static MethodInfo GetMethodExt([NotNull] this Type thisType, [NotNull] string name, BindingFlags bindingFlags, params Type[] parameterTypes)
{
// http://stackoverflow.com/questions/4035719/getmethod-for-generic-method
MethodInfo matchingMethod = null;
// Check all methods with the specified name, including in base classes
GetMethodExt(ref matchingMethod, thisType, name, bindingFlags, parameterTypes);
// If we're searching an interface, we have to manually search base interfaces
if (matchingMethod == null && thisType.IsInterface)
{
foreach (var interfaceType in thisType.GetInterfaces())
{
GetMethodExt(ref matchingMethod, interfaceType, name, bindingFlags, parameterTypes);
}
}
return matchingMethod;
}
private static void GetMethodExt([CanBeNull] ref MethodInfo matchingMethod, [NotNull] Type type, [NotNull] string name, BindingFlags bindingFlags, params Type[] parameterTypes)
{
// http://stackoverflow.com/questions/4035719/getmethod-for-generic-method
// Check all methods with the specified name, including in base classes
foreach (var methodInfo in type.GetMember(name, MemberTypes.Method, bindingFlags).Cast<MethodInfo>())
{
// Check that the parameter counts and types match, with 'loose' matching on generic parameters
var parameterInfos = methodInfo.GetParameters();
if (parameterInfos.Length == parameterTypes.Length)
{
var i = 0;
for (; i < parameterInfos.Length; ++i)
{
if (!parameterInfos[i].IsOptional && !parameterInfos[i].ParameterType.IsSimilarType(parameterTypes[i]))
{
break;
}
}
if (i == parameterInfos.Length)
{
if (matchingMethod == null)
{
matchingMethod = methodInfo;
}
else
{
throw new AmbiguousMatchException("More than one matching method found!");
}
}
}
}
}
[Pure]
[DebuggerStepThrough]
public static string GetMethodName<T, TReturn>(Expression<Func<T, TReturn>> expression)
{
var methodCallExpression = GetMethodCallExpression(expression);
return methodCallExpression.Method.Name;
}
[Pure]
public static string GetMultiLevelPropertyName(params string[] propertyNames)
{
return propertyNames.Join(".");
}
[Pure]
private static List<string> GetNames(MemberExpression memberExpression)
{
var names = new List<string>
{
memberExpression.Member.Name
};
while (memberExpression.Expression is MemberExpression)
{
memberExpression = (MemberExpression)memberExpression.Expression;
names.Insert(0, memberExpression.Member.Name);
}
return names;
}
[Pure]
[DebuggerStepThrough]
[NotNull]
public static string GetPropertyName<T, TReturn>([NotNull] Expression<Func<T, TReturn>> expression)
{
var names = GetPropertyName(expression.Body as MemberExpression);
if (names != null)
{
return names;
}
names = GetPropertyName(expression.Body as UnaryExpression);
if (names != null)
{
return names;
}
throw new ArgumentException("expression must be in the form: (Thing instance) => instance.Property[.Optional.Other.Properties.In.Chain]");
}
[Pure]
[ContractAnnotation("memberExpression:null => null; memberExpression: notnull => notnull")]
[CanBeNull]
public static string GetPropertyName([CanBeNull] MemberExpression memberExpression)
{
if (memberExpression == null)
{
return null;
}
var names = GetNames(memberExpression);
var name = names.Join(".");
return name;
}
[Pure]
[ContractAnnotation("unaryExpression:null => null; unaryExpression: notnull => notnull")]
[CanBeNull]
public static string GetPropertyName([CanBeNull] UnaryExpression unaryExpression)
{
if (unaryExpression == null)
{
return null;
}
var memberExpression = unaryExpression.Operand as MemberExpression;
return GetPropertyName(memberExpression);
}
[Pure]
[DebuggerStepThrough]
[NotNull]
public static string GetPropertyName<T>([NotNull] Expression<Func<T>> expression)
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("expression must be in the form: () => instance.Property");
}
var names = GetNames(memberExpression);
var name = names.Count > 1 ? names.Skip(1).Join(".") : names.Join(".");
return name;
}
[Pure]
[NotNull]
private static Dictionary<string, GenericGetter> GetSourceAccessors([NotNull] Type sourceType)
{
var sourceAccessors = _getters[sourceType];
if (sourceAccessors == null)
{
var sourceFields = sourceType
.GetFields()
.Select(x =>
new GenericGetter
{
Name = x.Name,
StorageType = x.FieldType,
GetValue = x.GetValue,
AccessorType = AccessorType.Field
}
);
var sourceProperties = sourceType
.GetProperties()
.ThatHaveAGetter()
.Select(x => new GenericGetter
{
Name = x.Name,
StorageType = x.PropertyType,
GetValue = new FastProperty(x).Get,
AccessorType = AccessorType.Property
});
sourceAccessors = new Dictionary<string, GenericGetter>(100);
foreach (var accessor in sourceProperties.Concat(sourceFields))
{
sourceAccessors.Add(accessor.Name.ToLower(), accessor);
}
_getters.Add(sourceType, sourceAccessors);
}
return sourceAccessors;
}
/// <summary>
/// http://stackoverflow.com/questions/340525/accessing-calling-object-from-methodcallexpression
/// </summary>
[CanBeNull]
private static object GetValue([NotNull] Expression expression)
{
var lambda = Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object)));
var func = lambda.Compile();
return func.Invoke();
}
[CanBeNull]
public static string GetValueAsString([NotNull] Expression expression)
{
switch (expression.NodeType)
{
case ExpressionType.Call:
return GetValueAsString((MethodCallExpression)expression);
case ExpressionType.Constant:
return GetValueAsString((ConstantExpression)expression);
case ExpressionType.MemberAccess:
return GetValueAsString((MemberExpression)expression);
default:
throw new NotImplementedException(expression.GetType() + " with nodeType " + expression.NodeType);
}
}
[CanBeNull]
private static string GetValueAsString([NotNull] ConstantExpression expression)
{
var value = expression.Value;
return value == null ? null : value.ToString();
}
[CanBeNull]
private static string GetValueAsString([NotNull] MemberExpression expression)
{
var result = GetValue(expression);
if (result == null)
{
return null;
}
return result.ToString();
}
[CanBeNull]
private static string GetValueAsString([NotNull] MethodCallExpression expression)
{
var result = GetValue(expression);
if (result == null)
{
return null;
}
return result.ToString();
}
[Pure]
public static bool IsNullableValueType([NotNull] Type type)
{
if (type.IsValueType)
{
if (type.IsGenericType &&
type.DeclaringType == null)
{
// e.g. decimal?
return true;
}
}
return false;
}
/// <summary>
/// Determines if the two types are either identical, or are both generic parameters or generic types
/// with generic parameters in the same locations (generic parameters match any other generic paramter,
/// but NOT concrete types).
/// </summary>
[Pure]
private static bool IsSimilarType([NotNull] this Type thisType, [NotNull] Type type)
{
// from http://stackoverflow.com/questions/4035719/getmethod-for-generic-method
// Ignore any 'ref' types
if (thisType.IsByRef)
{
thisType = thisType.GetElementType();
}
if (type.IsByRef)
{
type = type.GetElementType();
}
// Handle array types
// ReSharper disable PossibleNullReferenceException
if (thisType.IsArray && type.IsArray)
{
// ReSharper disable AssignNullToNotNullAttribute
return thisType.GetElementType().IsSimilarType(type.GetElementType());
// ReSharper restore AssignNullToNotNullAttribute
}
// ReSharper restore PossibleNullReferenceException
// If the types are identical, or they're both generic parameters or the special 'T' type, treat as a match
// ReSharper disable once PossibleNullReferenceException
if (thisType == type || (thisType.IsGenericParameter || thisType == typeof(TMatch)) && (type.IsGenericParameter || type == typeof(TMatch)))
{
return true;
}
// Handle any generic arguments
// ReSharper disable once PossibleNullReferenceException
if (thisType.IsGenericType && type.IsGenericType)
{
var thisArguments = thisType.GetGenericArguments();
var arguments = type.GetGenericArguments();
if (thisArguments.Length == arguments.Length)
{
return !thisArguments.Where((t, i) => !t.IsSimilarType(arguments[i])).Any();
}
}
return false;
}
[Pure]
public static bool IsUserType([NotNull] Type type)
{
var assembly = type.Assembly;
var company = GetAttribute<AssemblyCompanyAttribute>(assembly).Company;
return company != "Microsoft Corporation";
}
private class GenericGetter
{
public AccessorType AccessorType { get; set; }
public Func<object, object> GetValue { get; set; }
public string Name { get; set; }
public Type StorageType { get; set; }
}
private class GenericSetter
{
public AccessorType AccessorType { get; set; }
public string Name { get; set; }
public Action<object, object> SetValue { get; set; }
public Type StorageType { get; set; }
}
/// <summary>
/// Special type used to match any generic parameter type in GetMethodExt().
/// </summary>
public class TMatch
{
}
}
}