Use reflection to deserialize content of game throws MethodAccessException

327 views Asked by At

I have developped a custom XMLDeserializer which uses reflection to deserialize the content of my game (.xml). But I have an error that i don't figure it out when the content pipeline is compiling:

Error 1 Building content threw MethodAccessException: Attempt by security transparent method 'DynamicClass.ReflectionEmitUtils(System.Object)' to access security critical method 'System.Reflection.Assembly.get_PermissionSet()' failed.

Assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.

The error doesn't occur if I comment out this code :

// Add item to the collection
if (typeof(IList).IsAssignableFrom(collectionType))
{
   collectionType.GetMethod("Add").Invoke(collectionObject, new[] { itemObject });
}
else if (typeof(IDictionary).IsAssignableFrom(collectionType))
{
   collectionType.GetMethod("Add").Invoke(collectionObject, new[] { itemType, itemObject });
}

It seems that my assembly does not have the permission to call code in mscorlib assembly. If i call my method in a console application, it works.

Can you help me?

Thanks

1

There are 1 answers

1
Dave Cousineau On

Since IList and IDictionary are generic, maybe you are not locating the correct method, or are trying to pass the wrong types to them? Their Add methods will be strongly typed to their generic type. You might also be finding the wrong Add overload since you did not specify the parameter types. You might wish to do something like:

// Add item to the collection
if (typeof(IList).IsAssignableFrom(collectionType)) {
   var addMethod = collectionType.GetMethod("Add", new[] { itemObject.GetType() });
   if (addMethod == null)
      throw new SerializationException("Failed to find expected IList.Add method.");
   addMethod.Invoke(collectionObject, new[] { itemObject });
} else if (typeof(IDictionary).IsAssignableFrom(collectionType)) {
   var addMethod = collectionType.GetMethod("Add", new[] { typeof(Type), itemObject.GetType()}
   if (addMethod == null)
      throw new SerializationException("Failed to find expected IDictionary.Add method.");
   addMethod.Invoke(collectionObject, new[] { itemType, itemObject });
}