update MEF to preview 9
[mcs.git] / class / System.ComponentModel.Composition / src / ComponentModel / Microsoft / Internal / ReflectionInvoke.cs
blobb91a0c52a30f9c12aa594ce075955f011205c50f
1 #if !SILVERLIGHT && CLR40
3 using System;
4 using System.Reflection;
5 using System.Security;
6 using System.Security.Permissions;
8 namespace Microsoft.Internal
10 internal static class ReflectionInvoke
12 private static readonly ReflectionPermission _memberAccess = new ReflectionPermission(ReflectionPermissionFlag.MemberAccess);
13 private static readonly ReflectionPermission _restrictedMemberAccess = new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess);
15 public static object SafeCreateInstance(this Type type, params object[] arguments)
17 DemandMemberAccessIfNeeded(type);
19 return Activator.CreateInstance(type, arguments);
22 public static object SafeInvoke(this ConstructorInfo constructor, params object[] arguments)
24 DemandMemberAccessIfNeeded(constructor);
26 return constructor.Invoke(arguments);
29 public static object SafeInvoke(this MethodInfo method, object instance, params object[] arguments)
31 DemandMemberAccessIfNeeded(method);
33 return method.Invoke(instance, arguments);
36 public static object SafeGetValue(this FieldInfo field, object instance)
38 DemandMemberAccessIfNeeded(field);
40 return field.GetValue(instance);
43 public static void SafeSetValue(this FieldInfo field, object instance, object value)
45 DemandMemberAccessIfNeeded(field);
47 field.SetValue(instance, value);
50 public static void DemandMemberAccessIfNeeded(MethodInfo method)
52 if (!method.IsVisible())
54 DemandMemberAccess(method);
58 private static void DemandMemberAccessIfNeeded(FieldInfo field)
60 if (!field.IsVisible())
62 DemandMemberAccess(field);
66 public static void DemandMemberAccessIfNeeded(Type type)
68 // Consult UnderlyingSystemType this is the type that Activator.CreateInstance creates
69 if (!type.UnderlyingSystemType.IsVisible)
71 DemandMemberAccess(type);
75 private static void DemandMemberAccessIfNeeded(ConstructorInfo constructor)
77 if (!constructor.IsVisible())
79 DemandMemberAccess(constructor);
83 private static void DemandMemberAccess(MemberInfo target)
85 try
87 _memberAccess.Demand();
89 catch (SecurityException)
90 { // The caller doesn't have member access, but let's see whether they have access to
91 // members of assemblies with less or equal permissions (this mimics Reflection's behavior)
93 DemandRestrictedMemberAccess(target);
97 private static void DemandRestrictedMemberAccess(MemberInfo target)
99 Assembly targetAssembly = target.Assembly();
101 PermissionSet targetGrantSet = UnsafePermissionSet(targetAssembly);
102 targetGrantSet.AddPermission(_restrictedMemberAccess);
103 targetGrantSet.Demand();
106 [SecuritySafeCritical] // PermissionSet is [SecurityCritical]
107 private static PermissionSet UnsafePermissionSet(Assembly assembly)
109 return assembly.PermissionSet;
114 #endif