-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
EntityProxyFactory.cs
1694 lines (1490 loc) · 84.2 KB
/
EntityProxyFactory.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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//---------------------------------------------------------------------
// <copyright file="EntityProxyFactory.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner Microsoft
// @backupOwner Microsoft
//---------------------------------------------------------------------
namespace System.Data.Objects.Internal
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common.Utils;
using System.Data.Metadata.Edm;
using System.Data.Objects.DataClasses;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Threading;
/// <summary>
/// Factory for creating proxy classes that can intercept calls to a class' members.
/// </summary>
internal class EntityProxyFactory
{
private const string ProxyTypeNameFormat = "System.Data.Entity.DynamicProxies.{0}_{1}";
internal const string ResetFKSetterFlagFieldName = "_resetFKSetterFlag";
internal const string CompareByteArraysFieldName = "_compareByteArrays";
/// <summary>
/// A hook such that test code can change the AssemblyBuilderAccess of the
/// proxy assembly through reflection into the EntityProxyFactory.
/// </summary>
private static AssemblyBuilderAccess s_ProxyAssemblyBuilderAccess = AssemblyBuilderAccess.Run;
/// <summary>
/// Dictionary of proxy class type information, keyed by the pair of the CLR type and EntityType CSpaceName of the type being proxied.
/// A null value for a particular EntityType name key records the fact that
/// no proxy Type could be created for the specified type.
/// </summary>
private static Dictionary<Tuple<Type, string>, EntityProxyTypeInfo> s_ProxyNameMap = new Dictionary<Tuple<Type, string>, EntityProxyTypeInfo>();
/// <summary>
/// Dictionary of proxy class type information, keyed by the proxy type
/// </summary>
private static Dictionary<Type, EntityProxyTypeInfo> s_ProxyTypeMap = new Dictionary<Type, EntityProxyTypeInfo>();
private static Dictionary<Assembly, ModuleBuilder> s_ModuleBuilders = new Dictionary<Assembly, ModuleBuilder>();
private static ReaderWriterLockSlim s_TypeMapLock = new ReaderWriterLockSlim();
/// <summary>
/// The runtime assembly of the proxy types.
/// This is not the same as the AssemblyBuilder used to create proxy types.
/// </summary>
private static HashSet<Assembly> ProxyRuntimeAssemblies = new HashSet<Assembly>();
private static ModuleBuilder GetDynamicModule(EntityType ospaceEntityType)
{
Assembly assembly = ospaceEntityType.ClrType.Assembly;
ModuleBuilder moduleBuilder;
if (!s_ModuleBuilders.TryGetValue(assembly, out moduleBuilder))
{
AssemblyName assemblyName = new AssemblyName(String.Format(CultureInfo.InvariantCulture, "EntityFrameworkDynamicProxies-{0}", assembly.FullName));
assemblyName.Version = new Version(1, 0, 0, 0);
// Mark assembly as security transparent, meaning it cannot cause an elevation of privilege.
// This also means the assembly cannot satisfy a link demand. Instead link demands become full demands.
ConstructorInfo securityTransparentAttributeConstructor = typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes);
// Mark assembly with [SecurityRules(SecurityRuleSet.Level1)]. In memory, the assembly will inherit
// this automatically from SDE, but when persisted it needs this attribute to be considered Level1.
ConstructorInfo securityRulesAttributeConstructor = typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) });
CustomAttributeBuilder[] attributeBuilders = new CustomAttributeBuilder[] {
new CustomAttributeBuilder(securityTransparentAttributeConstructor, new object[0]),
new CustomAttributeBuilder(securityRulesAttributeConstructor, new object[1] { SecurityRuleSet.Level1 })
};
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, s_ProxyAssemblyBuilderAccess, attributeBuilders);
if (s_ProxyAssemblyBuilderAccess == AssemblyBuilderAccess.RunAndSave)
{
// Make the module persistable if the AssemblyBuilderAccess is changed to be RunAndSave.
moduleBuilder = assemblyBuilder.DefineDynamicModule("EntityProxyModule", "EntityProxyModule.dll");
}
else
{
moduleBuilder = assemblyBuilder.DefineDynamicModule("EntityProxyModule");
}
s_ModuleBuilders.Add(assembly, moduleBuilder);
}
return moduleBuilder;
}
internal static bool TryGetProxyType(Type clrType, string entityTypeName, out EntityProxyTypeInfo proxyTypeInfo)
{
s_TypeMapLock.EnterReadLock();
try
{
return s_ProxyNameMap.TryGetValue(new Tuple<Type, string>(clrType, entityTypeName), out proxyTypeInfo);
}
finally
{
s_TypeMapLock.ExitReadLock();
}
}
internal static bool TryGetProxyType(Type proxyType, out EntityProxyTypeInfo proxyTypeInfo)
{
s_TypeMapLock.EnterReadLock();
try
{
return s_ProxyTypeMap.TryGetValue(proxyType, out proxyTypeInfo);
}
finally
{
s_TypeMapLock.ExitReadLock();
}
}
internal static bool TryGetProxyWrapper(object instance, out IEntityWrapper wrapper)
{
Debug.Assert(instance != null, "the instance should not be null");
wrapper = null;
EntityProxyTypeInfo proxyTypeInfo;
if (IsProxyType(instance.GetType()) &&
TryGetProxyType(instance.GetType(), out proxyTypeInfo))
{
wrapper = proxyTypeInfo.GetEntityWrapper(instance);
}
return wrapper != null;
}
/// <summary>
/// Return proxy type information for the specified O-Space EntityType.
/// </summary>
/// <param name="ospaceEntityType">
/// EntityType in O-Space that represents the CLR type to be proxied.
/// Must not be null.
/// </param>
/// <returns>
/// A non-null EntityProxyTypeInfo instance that contains information about the type of proxy for
/// the specified O-Space EntityType; or null if no proxy can be created for the specified type.
/// </returns>
internal static EntityProxyTypeInfo GetProxyType(ClrEntityType ospaceEntityType)
{
Debug.Assert(ospaceEntityType != null, "ospaceEntityType must be non-null");
Debug.Assert(ospaceEntityType.DataSpace == DataSpace.OSpace, "ospaceEntityType.DataSpace must be OSpace");
EntityProxyTypeInfo proxyTypeInfo = null;
// Check if an entry for the proxy type already exists.
if (TryGetProxyType(ospaceEntityType.ClrType, ospaceEntityType.CSpaceTypeName, out proxyTypeInfo))
{
if (proxyTypeInfo != null)
{
proxyTypeInfo.ValidateType(ospaceEntityType);
}
return proxyTypeInfo;
}
// No entry found, may need to create one.
// Acquire an upgradeable read lock so that:
// 1. Other readers aren't blocked while the second existence check is performed.
// 2. Other threads that may have also detected the absence of an entry block while the first thread handles proxy type creation.
s_TypeMapLock.EnterUpgradeableReadLock();
try
{
return TryCreateProxyType(ospaceEntityType);
}
finally
{
s_TypeMapLock.ExitUpgradeableReadLock();
}
}
/// <summary>
/// A mechanism to lookup AssociationType metadata for proxies for a given entity and association information
/// </summary>
/// <param name="wrappedEntity">The entity instance used to lookup the proxy type</param>
/// <param name="relationshipName">The name of the relationship (FullName or Name)</param>
/// <param name="targetRoleName">Target role of the relationship</param>
/// <param name="associationType">The AssociationType for that property</param>
/// <returns>True if an AssociationType is found in proxy metadata, false otherwise</returns>
internal static bool TryGetAssociationTypeFromProxyInfo(IEntityWrapper wrappedEntity, string relationshipName, string targetRoleName, out AssociationType associationType)
{
EntityProxyTypeInfo proxyInfo = null;
associationType = null;
return (EntityProxyFactory.TryGetProxyType(wrappedEntity.Entity.GetType(), out proxyInfo) && proxyInfo != null &&
proxyInfo.TryGetNavigationPropertyAssociationType(relationshipName, targetRoleName, out associationType));
}
/// <summary>
/// Enumerate list of supplied O-Space EntityTypes,
/// and generate a proxy type for each EntityType (if possible for the particular type).
/// </summary>
/// <param name="ospaceEntityType">
/// Enumeration of O-Space EntityType objects.
/// Must not be null.
/// In addition, the elements of the enumeration must not be null.
/// </param>
internal static void TryCreateProxyTypes(IEnumerable<EntityType> ospaceEntityTypes)
{
Debug.Assert(ospaceEntityTypes != null, "ospaceEntityTypes must be non-null");
// Acquire an upgradeable read lock for the duration of the enumeration so that:
// 1. Other readers aren't blocked while existence checks are performed.
// 2. Other threads that may have detected the absence of an entry block while the first thread handles proxy type creation.
s_TypeMapLock.EnterUpgradeableReadLock();
try
{
foreach (EntityType ospaceEntityType in ospaceEntityTypes)
{
Debug.Assert(ospaceEntityType != null, "Null EntityType element reference present in enumeration.");
TryCreateProxyType(ospaceEntityType);
}
}
finally
{
s_TypeMapLock.ExitUpgradeableReadLock();
}
}
private static EntityProxyTypeInfo TryCreateProxyType(EntityType ospaceEntityType)
{
Debug.Assert(s_TypeMapLock.IsUpgradeableReadLockHeld, "EntityProxyTypeInfo.TryCreateProxyType method was called without first acquiring an upgradeable read lock from s_TypeMapLock.");
EntityProxyTypeInfo proxyTypeInfo;
ClrEntityType clrEntityType = (ClrEntityType)ospaceEntityType;
Tuple<Type, string> proxyIdentiy = new Tuple<Type, string>(clrEntityType.ClrType, clrEntityType.HashedDescription);
if (!s_ProxyNameMap.TryGetValue(proxyIdentiy, out proxyTypeInfo) && CanProxyType(ospaceEntityType))
{
ModuleBuilder moduleBuilder = GetDynamicModule(ospaceEntityType);
proxyTypeInfo = BuildType(moduleBuilder, clrEntityType);
s_TypeMapLock.EnterWriteLock();
try
{
s_ProxyNameMap[proxyIdentiy] = proxyTypeInfo;
if (proxyTypeInfo != null)
{
// If there is a proxy type, create the reverse lookup
s_ProxyTypeMap[proxyTypeInfo.ProxyType] = proxyTypeInfo;
}
}
finally
{
s_TypeMapLock.ExitWriteLock();
}
}
return proxyTypeInfo;
}
/// <summary>
/// Determine if the specified type represents a known proxy type.
/// </summary>
/// <param name="type">
/// The Type to be examined.
/// </param>
/// <returns>
/// True if the type is a known proxy type; otherwise false.
/// </returns>
internal static bool IsProxyType(Type type)
{
Debug.Assert(type != null, "type is null, was this intended?");
return type != null && ProxyRuntimeAssemblies.Contains(type.Assembly);
}
/// <summary>
/// Return an enumerable of the current set of CLR proxy types.
/// </summary>
/// <returns>
/// Enumerable of the current set of CLR proxy types.
/// This value will never be null.
/// </returns>
/// <remarks>
/// The enumerable is based on a shapshot of the current list of types.
/// </remarks>
internal static IEnumerable<Type> GetKnownProxyTypes()
{
s_TypeMapLock.EnterReadLock();
try
{
var proxyTypes = from info in s_ProxyNameMap.Values
where info != null
select info.ProxyType;
return proxyTypes.ToArray();
}
finally
{
s_TypeMapLock.ExitReadLock();
}
}
public Func<object, object> CreateBaseGetter(Type declaringType, PropertyInfo propertyInfo)
{
Debug.Assert(propertyInfo != null, "Null propertyInfo");
ParameterExpression Object_Parameter = Expression.Parameter(typeof(object), "instance");
Func<object, object> nonProxyGetter = Expression.Lambda<Func<object, object>>(
Expression.PropertyOrField(
Expression.Convert(Object_Parameter, declaringType),
propertyInfo.Name),
Object_Parameter).Compile();
string propertyName = propertyInfo.Name;
return (entity) =>
{
Type type = entity.GetType();
if (IsProxyType(type))
{
object value;
if (TryGetBasePropertyValue(type, propertyName, entity, out value))
{
return value;
}
}
return nonProxyGetter(entity);
};
}
private static bool TryGetBasePropertyValue(Type proxyType, string propertyName, object entity, out object value)
{
EntityProxyTypeInfo typeInfo;
value = null;
if (TryGetProxyType(proxyType, out typeInfo) && typeInfo.ContainsBaseGetter(propertyName))
{
value = typeInfo.BaseGetter(entity, propertyName);
return true;
}
return false;
}
public Action<object, object> CreateBaseSetter(Type declaringType, PropertyInfo propertyInfo)
{
Debug.Assert(propertyInfo != null, "Null propertyInfo");
Action<object, object> nonProxySetter = LightweightCodeGenerator.CreateNavigationPropertySetter(declaringType, propertyInfo);
string propertyName = propertyInfo.Name;
return (entity, value) =>
{
Type type = entity.GetType();
if (IsProxyType(type))
{
if (TrySetBasePropertyValue(type, propertyName, entity, value))
{
return;
}
}
nonProxySetter(entity, value);
};
}
private static bool TrySetBasePropertyValue(Type proxyType, string propertyName, object entity, object value)
{
EntityProxyTypeInfo typeInfo;
if (TryGetProxyType(proxyType, out typeInfo) && typeInfo.ContainsBaseSetter(propertyName))
{
typeInfo.BaseSetter(entity, propertyName, value);
return true;
}
return false;
}
/// <summary>
/// Build a CLR proxy type for the supplied EntityType.
/// </summary>
/// <param name="ospaceEntityType">
/// EntityType in O-Space that represents the CLR type to be proxied.
/// </param>
/// <returns>
/// EntityProxyTypeInfo object that contains the constructed proxy type,
/// along with any behaviors associated with that type;
/// or null if a proxy type cannot be constructed for the specified EntityType.
/// </returns>
private static EntityProxyTypeInfo BuildType(ModuleBuilder moduleBuilder, ClrEntityType ospaceEntityType)
{
Debug.Assert(s_TypeMapLock.IsUpgradeableReadLockHeld, "EntityProxyTypeInfo.BuildType method was called without first acquiring an upgradeable read lock from s_TypeMapLock.");
EntityProxyTypeInfo proxyTypeInfo;
ProxyTypeBuilder proxyTypeBuilder = new ProxyTypeBuilder(ospaceEntityType);
Type proxyType = proxyTypeBuilder.CreateType(moduleBuilder);
if (proxyType != null)
{
// Set the runtime assembly of the proxy types if it hasn't already been set.
// This is used by the IsProxyType method.
Assembly typeAssembly = proxyType.Assembly;
if (!ProxyRuntimeAssemblies.Contains(typeAssembly))
{
ProxyRuntimeAssemblies.Add(typeAssembly);
AddAssemblyToResolveList(typeAssembly);
}
proxyTypeInfo = new EntityProxyTypeInfo(proxyType, ospaceEntityType,
proxyTypeBuilder.CreateInitalizeCollectionMethod(proxyType),
proxyTypeBuilder.BaseGetters, proxyTypeBuilder.BaseSetters);
foreach (EdmMember member in proxyTypeBuilder.LazyLoadMembers)
{
InterceptMember(member, proxyType, proxyTypeInfo);
}
SetResetFKSetterFlagDelegate(proxyType, proxyTypeInfo);
SetCompareByteArraysDelegate(proxyType, proxyTypeInfo);
}
else
{
proxyTypeInfo = null;
}
return proxyTypeInfo;
}
/// <summary>
/// In order for deserialization of proxy objects to succeed in this AppDomain,
/// an assembly resolve handler must be added to the AppDomain to resolve the dynamic assembly,
/// since it is not present in a location discoverable by fusion.
/// </summary>
/// <param name="assembly">Proxy assembly to be resolved.</param>
[SecuritySafeCritical]
private static void AddAssemblyToResolveList(Assembly assembly)
{
if (ProxyRuntimeAssemblies.Contains(assembly)) // If the assembly is not a known proxy assembly, ignore it.
{
ResolveEventHandler resolveHandler = new ResolveEventHandler((sender, args) => args.Name == assembly.FullName ? assembly : null);
AppDomain.CurrentDomain.AssemblyResolve += resolveHandler;
}
}
/// <summary>
/// Construct an interception delegate for the specified proxy member.
/// </summary>
/// <param name="member">
/// EdmMember that specifies the member to be intercepted.
/// </param>
/// <param name="proxyType">
/// Type of the proxy.
/// </param>
/// <param name="lazyLoadBehavior">
/// LazyLoadBehavior object that supplies the behavior to load related ends.
/// </param>
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private static void InterceptMember(EdmMember member, Type proxyType, EntityProxyTypeInfo proxyTypeInfo)
{
PropertyInfo property = EntityUtil.GetTopProperty(proxyType, member.Name);
Debug.Assert(property != null, String.Format(CultureInfo.CurrentCulture, "Expected property {0} to be defined on proxy type {1}", member.Name, proxyType.FullName));
FieldInfo interceptorField = proxyType.GetField(LazyLoadImplementor.GetInterceptorFieldName(member.Name), BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic);
Debug.Assert(interceptorField != null, String.Format(CultureInfo.CurrentCulture, "Expected interceptor field for property {0} to be defined on proxy type {1}", member.Name, proxyType.FullName));
Delegate interceptorDelegate = typeof(LazyLoadBehavior).GetMethod("GetInterceptorDelegate", BindingFlags.NonPublic | BindingFlags.Static).
MakeGenericMethod(proxyType, property.PropertyType).
Invoke(null, new object[] { member, proxyTypeInfo.EntityWrapperDelegate }) as Delegate;
AssignInterceptionDelegate(interceptorDelegate, interceptorField);
}
/// <summary>
/// Set the interceptor on a proxy member.
/// </summary>
/// <param name="interceptorDelegate">
/// Delegate to be set
/// </param>
/// <param name="interceptorField">
/// Field define on the proxy type to store the reference to the interception delegate.
/// </param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2128")]
[SecuritySafeCritical]
[ReflectionPermission(SecurityAction.Assert, MemberAccess = true)]
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private static void AssignInterceptionDelegate(Delegate interceptorDelegate, FieldInfo interceptorField)
{
interceptorField.SetValue(null, interceptorDelegate);
}
/// <summary>
/// Sets a delegate onto the _resetFKSetterFlag field such that it can be executed to make
/// a call into the state manager to reset the InFKSetter flag.
/// </summary>
private static void SetResetFKSetterFlagDelegate(Type proxyType, EntityProxyTypeInfo proxyTypeInfo)
{
var resetFKSetterFlagField = proxyType.GetField(ResetFKSetterFlagFieldName, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic);
Debug.Assert(resetFKSetterFlagField != null, "Expected resetFKSetterFlagField to be defined on the proxy type.");
var resetFKSetterFlagDelegate = GetResetFKSetterFlagDelegate(proxyTypeInfo.EntityWrapperDelegate);
AssignInterceptionDelegate(resetFKSetterFlagDelegate, resetFKSetterFlagField);
}
/// <summary>
/// Returns the delegate that takes a proxy instance and uses it to reset the InFKSetter flag maintained
/// by the state manager of the context associated with the proxy instance.
/// </summary>
private static Action<object> GetResetFKSetterFlagDelegate(Func<object, object> getEntityWrapperDelegate)
{
return (proxy) =>
{
Debug.Assert(getEntityWrapperDelegate != null, "entityWrapperDelegate must not be null");
ResetFKSetterFlag(getEntityWrapperDelegate(proxy));
};
}
/// <summary>
/// Called in the finally clause of each overridden property setter to ensure that the flag
/// indicating that we are in an FK setter is cleared. Note that the wrapped entity is passed as
/// an obejct becayse IEntityWrapper is an internal type and is therefore not accessable to
/// the proxy type. Once we're in the framework it is cast back to an IEntityWrapper.
/// </summary>
private static void ResetFKSetterFlag(object wrappedEntityAsObject)
{
Debug.Assert(wrappedEntityAsObject == null || wrappedEntityAsObject is IEntityWrapper, "wrappedEntityAsObject must be an IEntityWrapper");
var wrappedEntity = (IEntityWrapper)wrappedEntityAsObject; // We want an exception if the cast fails.
if (wrappedEntity != null && wrappedEntity.Context != null)
{
wrappedEntity.Context.ObjectStateManager.EntityInvokingFKSetter = null;
}
}
/// <summary>
/// Sets a delegate onto the _compareByteArrays field such that it can be executed to check
/// whether two byte arrays are the same by value comparison.
/// </summary>
private static void SetCompareByteArraysDelegate(Type proxyType, EntityProxyTypeInfo proxyTypeInfo)
{
var compareByteArraysField = proxyType.GetField(CompareByteArraysFieldName, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic);
Debug.Assert(compareByteArraysField != null, "Expected compareByteArraysField to be defined on the proxy type.");
AssignInterceptionDelegate(new Func<object, object, bool>(ByValueEqualityComparer.Default.Equals), compareByteArraysField);
}
/// <summary>
/// Return boolean that specifies if the specified type can be proxied.
/// </summary>
/// <param name="ospaceEntityType">O-space EntityType</param>
/// <returns>
/// True if the class is not abstract or sealed, does not implement IEntityWithRelationships,
/// and has a public or protected default constructor; otherwise false.
/// </returns>
/// <remarks>
/// While it is technically possible to derive from an abstract type
/// in order to create a proxy, we avoid this so that the proxy type
/// has the same "concreteness" of the type being proxied.
/// The check for IEntityWithRelationships ensures that codegen'ed
/// entities that derive from EntityObject as well as properly
/// constructed IPOCO entities will not be proxied.
///
/// </remarks>
private static bool CanProxyType(EntityType ospaceEntityType)
{
TypeAttributes access = ospaceEntityType.ClrType.Attributes & TypeAttributes.VisibilityMask;
ConstructorInfo ctor = ospaceEntityType.ClrType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, Type.EmptyTypes, null);
bool accessableCtor = ctor != null && (((ctor.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) ||
((ctor.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family) ||
((ctor.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem));
return (!(ospaceEntityType.Abstract ||
ospaceEntityType.ClrType.IsSealed ||
typeof(IEntityWithRelationships).IsAssignableFrom(ospaceEntityType.ClrType) ||
!accessableCtor) &&
access == TypeAttributes.Public);
}
private static bool CanProxyMethod(MethodInfo method)
{
bool result = false;
if (method != null)
{
MethodAttributes access = method.Attributes & MethodAttributes.MemberAccessMask;
result = method.IsVirtual &&
!method.IsFinal &&
(access == MethodAttributes.Public ||
access == MethodAttributes.Family ||
access == MethodAttributes.FamORAssem);
}
return result;
}
internal static bool CanProxyGetter(PropertyInfo clrProperty)
{
Debug.Assert(clrProperty != null, "clrProperty should have a value");
return CanProxyMethod(clrProperty.GetGetMethod(true));
}
internal static bool CanProxySetter(PropertyInfo clrProperty)
{
Debug.Assert(clrProperty != null, "clrProperty should have a value");
return CanProxyMethod(clrProperty.GetSetMethod(true));
}
private class ProxyTypeBuilder
{
private TypeBuilder _typeBuilder;
private BaseProxyImplementor _baseImplementor;
private IPOCOImplementor _ipocoImplementor;
private LazyLoadImplementor _lazyLoadImplementor;
private DataContractImplementor _dataContractImplementor;
private ISerializableImplementor _iserializableImplementor;
private ClrEntityType _ospaceEntityType;
private ModuleBuilder _moduleBuilder;
private List<FieldBuilder> _serializedFields = new List<FieldBuilder>(3);
public ProxyTypeBuilder(ClrEntityType ospaceEntityType)
{
_ospaceEntityType = ospaceEntityType;
_baseImplementor = new BaseProxyImplementor();
_ipocoImplementor = new IPOCOImplementor(ospaceEntityType);
_lazyLoadImplementor = new LazyLoadImplementor(ospaceEntityType);
_dataContractImplementor = new DataContractImplementor(ospaceEntityType);
_iserializableImplementor = new ISerializableImplementor(ospaceEntityType);
}
public Type BaseType
{
get { return _ospaceEntityType.ClrType; }
}
public DynamicMethod CreateInitalizeCollectionMethod(Type proxyType)
{
return _ipocoImplementor.CreateInitalizeCollectionMethod(proxyType);
}
public List<PropertyInfo> BaseGetters
{
get
{
return _baseImplementor.BaseGetters;
}
}
public List<PropertyInfo> BaseSetters
{
get
{
return _baseImplementor.BaseSetters;
}
}
public IEnumerable<EdmMember> LazyLoadMembers
{
get { return _lazyLoadImplementor.Members; }
}
public Type CreateType(ModuleBuilder moduleBuilder)
{
_moduleBuilder = moduleBuilder;
bool hadProxyProperties = false;
if (_iserializableImplementor.TypeIsSuitable)
{
foreach (EdmMember member in _ospaceEntityType.Members)
{
if (_ipocoImplementor.CanProxyMember(member) ||
_lazyLoadImplementor.CanProxyMember(member))
{
PropertyInfo baseProperty = EntityUtil.GetTopProperty(BaseType, member.Name);
PropertyBuilder propertyBuilder = TypeBuilder.DefineProperty(member.Name, System.Reflection.PropertyAttributes.None, baseProperty.PropertyType, Type.EmptyTypes);
if (!_ipocoImplementor.EmitMember(TypeBuilder, member, propertyBuilder, baseProperty, _baseImplementor))
{
EmitBaseSetter(TypeBuilder, propertyBuilder, baseProperty);
}
if (!_lazyLoadImplementor.EmitMember(TypeBuilder, member, propertyBuilder, baseProperty, _baseImplementor))
{
EmitBaseGetter(TypeBuilder, propertyBuilder, baseProperty);
}
hadProxyProperties = true;
}
}
if (_typeBuilder != null)
{
_baseImplementor.Implement(TypeBuilder, RegisterInstanceField);
_iserializableImplementor.Implement(TypeBuilder, _serializedFields);
}
}
return hadProxyProperties ? TypeBuilder.CreateType() : null;
}
private TypeBuilder TypeBuilder
{
get
{
if (_typeBuilder == null)
{
TypeAttributes proxyTypeAttributes = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed;
if ((BaseType.Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable)
{
proxyTypeAttributes |= TypeAttributes.Serializable;
}
// If the type as a long name, then use only the first part of it so that there is no chance that the generated
// name will be too long. Note that the full name always gets used to compute the hash.
string baseName = BaseType.Name.Length <= 20 ? BaseType.Name : BaseType.Name.Substring(0, 20);
string proxyTypeName = String.Format(CultureInfo.InvariantCulture, ProxyTypeNameFormat, baseName, _ospaceEntityType.HashedDescription);
_typeBuilder = _moduleBuilder.DefineType(proxyTypeName, proxyTypeAttributes, BaseType, _ipocoImplementor.Interfaces);
_typeBuilder.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName);
Action<FieldBuilder, bool> registerField = RegisterInstanceField;
_ipocoImplementor.Implement(_typeBuilder, registerField);
_lazyLoadImplementor.Implement(_typeBuilder, registerField);
// WCF data contract serialization is not compatible with types that implement ISerializable.
if (!_iserializableImplementor.TypeImplementsISerializable)
{
_dataContractImplementor.Implement(_typeBuilder, registerField);
}
}
return _typeBuilder;
}
}
private void EmitBaseGetter(TypeBuilder typeBuilder, PropertyBuilder propertyBuilder, PropertyInfo baseProperty)
{
if (CanProxyGetter(baseProperty))
{
MethodInfo baseGetter = baseProperty.GetGetMethod(true);
const MethodAttributes getterAttributes = MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Virtual;
MethodAttributes getterAccess = baseGetter.Attributes & MethodAttributes.MemberAccessMask;
// Define a property getter override in the proxy type
MethodBuilder getterBuilder = typeBuilder.DefineMethod("get_" + baseProperty.Name, getterAccess | getterAttributes, baseProperty.PropertyType, Type.EmptyTypes);
ILGenerator gen = getterBuilder.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Call, baseGetter);
gen.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getterBuilder);
}
}
private void EmitBaseSetter(TypeBuilder typeBuilder, PropertyBuilder propertyBuilder, PropertyInfo baseProperty)
{
if (CanProxySetter(baseProperty))
{
MethodInfo baseSetter = baseProperty.GetSetMethod(true); ;
const MethodAttributes methodAttributes = MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Virtual;
MethodAttributes methodAccess = baseSetter.Attributes & MethodAttributes.MemberAccessMask;
MethodBuilder setterBuilder = typeBuilder.DefineMethod("set_" + baseProperty.Name, methodAccess | methodAttributes, null, new Type[] { baseProperty.PropertyType });
ILGenerator generator = setterBuilder.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldarg_1);
generator.Emit(OpCodes.Call, baseSetter);
generator.Emit(OpCodes.Ret);
propertyBuilder.SetSetMethod(setterBuilder);
}
}
private void RegisterInstanceField(FieldBuilder field, bool serializable)
{
if (serializable)
{
_serializedFields.Add(field);
}
else
{
MarkAsNotSerializable(field);
}
}
private static readonly ConstructorInfo s_NonSerializedAttributeConstructor = typeof(NonSerializedAttribute).GetConstructor(Type.EmptyTypes);
private static readonly ConstructorInfo s_IgnoreDataMemberAttributeConstructor = typeof(IgnoreDataMemberAttribute).GetConstructor(Type.EmptyTypes);
private static readonly ConstructorInfo s_XmlIgnoreAttributeConstructor = typeof(System.Xml.Serialization.XmlIgnoreAttribute).GetConstructor(Type.EmptyTypes);
private static readonly ConstructorInfo s_ScriptIgnoreAttributeConstructor = TryGetScriptIgnoreAttributeType().GetConstructor(Type.EmptyTypes);
private static Type TryGetScriptIgnoreAttributeType()
{
try
{
var scriptIgnoreAttributeAssembly = Assembly.Load(AssemblyRef.SystemWebExtensions);
return scriptIgnoreAttributeAssembly.GetType(@"System.Web.Script.Serialization.ScriptIgnoreAttribute");
}
catch
{
}
// We should not assert in EF6, at least when produce a build compatible with .NET 4.0 client SKU
Debug.Assert(false, "Unable to find ScriptIgnoreAttribute type");
return null;
}
private static void MarkAsNotSerializable(FieldBuilder field)
{
object[] emptyArray = new object[0];
field.SetCustomAttribute(new CustomAttributeBuilder(s_NonSerializedAttributeConstructor, emptyArray));
if (field.IsPublic)
{
field.SetCustomAttribute(new CustomAttributeBuilder(s_IgnoreDataMemberAttributeConstructor, emptyArray));
field.SetCustomAttribute(new CustomAttributeBuilder(s_XmlIgnoreAttributeConstructor, emptyArray));
if (s_ScriptIgnoreAttributeConstructor != null)
{
field.SetCustomAttribute(new CustomAttributeBuilder(s_ScriptIgnoreAttributeConstructor, emptyArray));
}
}
}
}
}
internal class LazyLoadImplementor
{
HashSet<EdmMember> _members;
public LazyLoadImplementor(EntityType ospaceEntityType)
{
CheckType(ospaceEntityType);
}
public IEnumerable<EdmMember> Members
{
get { return _members; }
}
private void CheckType(EntityType ospaceEntityType)
{
_members = new HashSet<EdmMember>();
foreach (EdmMember member in ospaceEntityType.Members)
{
PropertyInfo clrProperty = EntityUtil.GetTopProperty(ospaceEntityType.ClrType, member.Name);
if (clrProperty != null &&
EntityProxyFactory.CanProxyGetter(clrProperty) &&
LazyLoadBehavior.IsLazyLoadCandidate(ospaceEntityType, member))
{
_members.Add(member);
}
}
}
public bool CanProxyMember(EdmMember member)
{
return _members.Contains(member);
}
public void Implement(TypeBuilder typeBuilder, Action<FieldBuilder, bool> registerField)
{
// Add instance field to store IEntityWrapper instance
// The field is typed as object, for two reasons:
// 1. The practical one, IEntityWrapper is internal and not accessible from the dynamic assembly.
// 2. We purposely want the wrapper field to be opaque on the proxy type.
FieldBuilder wrapperField = typeBuilder.DefineField(EntityProxyTypeInfo.EntityWrapperFieldName, typeof(object), FieldAttributes.Public);
registerField(wrapperField, false);
}
public bool EmitMember(TypeBuilder typeBuilder, EdmMember member, PropertyBuilder propertyBuilder, PropertyInfo baseProperty, BaseProxyImplementor baseImplementor)
{
if (_members.Contains(member))
{
MethodInfo baseGetter = baseProperty.GetGetMethod(true);
const MethodAttributes getterAttributes = MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Virtual;
MethodAttributes getterAccess = baseGetter.Attributes & MethodAttributes.MemberAccessMask;
// Define field to store interceptor Func
// Signature of interceptor Func delegate is as follows:
//
// bool intercept(ProxyType proxy, PropertyType propertyValue)
//
// where
// PropertyType is the type of the Property, such as ICollection<Customer>,
// ProxyType is the type of the proxy object,
// propertyValue is the value returned from the proxied type's property getter.
Type interceptorType = typeof(Func<,,>).MakeGenericType(typeBuilder, baseProperty.PropertyType, typeof(bool));
MethodInfo interceptorInvoke = TypeBuilder.GetMethod(interceptorType, typeof(Func<,,>).GetMethod("Invoke"));
FieldBuilder interceptorField = typeBuilder.DefineField(GetInterceptorFieldName(baseProperty.Name), interceptorType, FieldAttributes.Private | FieldAttributes.Static);
// Define a property getter override in the proxy type
MethodBuilder getterBuilder = typeBuilder.DefineMethod("get_" + baseProperty.Name, getterAccess | getterAttributes, baseProperty.PropertyType, Type.EmptyTypes);
ILGenerator generator = getterBuilder.GetILGenerator();
// Emit instructions for the following call:
// T value = base.SomeProperty;
// if(this._interceptorForSomeProperty(this, value))
// { return value; }
// return base.SomeProperty;
// where _interceptorForSomeProperty represents the interceptor Func field.
Label lableTrue = generator.DefineLabel();
generator.DeclareLocal(baseProperty.PropertyType); // T value
generator.Emit(OpCodes.Ldarg_0); // call base.SomeProperty
generator.Emit(OpCodes.Call, baseGetter); // call to base property getter
generator.Emit(OpCodes.Stloc_0); // value = result
generator.Emit(OpCodes.Ldarg_0); // load this
generator.Emit(OpCodes.Ldfld, interceptorField); // load this._interceptor
generator.Emit(OpCodes.Ldarg_0); // load this
generator.Emit(OpCodes.Ldloc_0); // load value
generator.Emit(OpCodes.Callvirt, interceptorInvoke); // call to interceptor delegate with (this, value)
generator.Emit(OpCodes.Brtrue_S, lableTrue); // if true, just return
generator.Emit(OpCodes.Ldarg_0); // else, call the base propertty getter again
generator.Emit(OpCodes.Call, baseGetter); // call to base property getter
generator.Emit(OpCodes.Ret);
generator.MarkLabel(lableTrue);
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getterBuilder);
baseImplementor.AddBasePropertyGetter(baseProperty);
return true;
}
return false;
}
internal static string GetInterceptorFieldName(string memberName)
{
return "ef_proxy_interceptorFor" + memberName;
}
}
internal class BaseProxyImplementor
{
private readonly List<PropertyInfo> _baseGetters;
private readonly List<PropertyInfo> _baseSetters;
public BaseProxyImplementor()
{
_baseGetters = new List<PropertyInfo>();
_baseSetters = new List<PropertyInfo>();
}
public List<PropertyInfo> BaseGetters
{
get { return _baseGetters; }
}
public List<PropertyInfo> BaseSetters
{
get { return _baseSetters; }
}
public void AddBasePropertyGetter(PropertyInfo baseProperty)
{
_baseGetters.Add(baseProperty);
}
public void AddBasePropertySetter(PropertyInfo baseProperty)
{
_baseSetters.Add(baseProperty);
}
public void Implement(TypeBuilder typeBuilder, Action<FieldBuilder, bool> registerField)
{
if (_baseGetters.Count > 0)
{
ImplementBaseGetter(typeBuilder);
}
if (_baseSetters.Count > 0)
{
ImplementBaseSetter(typeBuilder);
}
}
static readonly MethodInfo s_StringEquals = typeof(string).GetMethod("op_Equality", new Type[] { typeof(string), typeof(string) });
static readonly ConstructorInfo s_InvalidOperationConstructor = typeof(InvalidOperationException).GetConstructor(Type.EmptyTypes);
private void ImplementBaseGetter(TypeBuilder typeBuilder)
{
// Define a property getter in the proxy type
MethodBuilder getterBuilder = typeBuilder.DefineMethod("GetBasePropertyValue", MethodAttributes.Public | MethodAttributes.HideBySig, typeof(object), new Type[] { typeof(string) });
ILGenerator gen = getterBuilder.GetILGenerator();
Label[] labels = new Label[_baseGetters.Count];
for (int i = 0; i < _baseGetters.Count; i++)
{
labels[i] = gen.DefineLabel();
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Ldstr, _baseGetters[i].Name);
gen.Emit(OpCodes.Call, s_StringEquals);
gen.Emit(OpCodes.Brfalse_S, labels[i]);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Call, _baseGetters[i].GetGetMethod(true));
gen.Emit(OpCodes.Ret);
gen.MarkLabel(labels[i]);
}