COMException- Unsupported type for field or property setter
I need a custom role based security for our project. It should be based on resources and resources’ permissions. All resources are somehow objects.
Firstly, I’ve implemented custom principal inherited from GenericPrincipal class, custom permission that implements IPermission and IUnrestrictedPermission. And than as it is expected I implement my realization of CodeAccessSecurityAttribute in order to be able to have declarative security. It contains a property for setting/getting the resource type. I also pass all the path to sign my assembly and put it into GAC etc. And then I’ve tried to see how it works and Bum! I got the exception "COMException- Unsupported type for field or property setter" which told me that what is wrong with my security attribute properties. I supposed that the reason is my resource type property and I was right. Here is a bug report about this problem. Actually, it is not a bug but a normal situation when it is a design problem :(.
It is clear that I can use type with an implementation of a custom security attribute based on CodeAccessSecurityAttribute. But what do you think about using an aspect? I chose to use an aspect attribute in order to achieve a declarative security. I used PostSharp to create my aspect attribute.
1: [Serializable]
2: [AttributeUsage(AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true, Inherited = true)]
3: public class PermissionAspectAttribute : OnMethodBoundaryAspect
4: {
5: public Type ResourceType { get; private set; }
6: public Permission NeededPermission { get; private set; }
7:
8: public PermissionAspectAttribute(Type resourceType, Permission neededPermission)
9: {
10: ResourceType = resourceType;
11: NeededPermission = neededPermission;
12: }
13:
14: public override void OnEntry(MethodExecutionEventArgs eventArgs)
15: {
16: ResourcePermission permission = new ResourcePermission(ResourceType, NeededPermission);
17: permission.Demand();
18: }
19: }
You can see that I instantiate my permission and call its Demand() method. Then it was easy to use the attribute in a code. Let’s assume that I have a method Get() as in the snippet below.
1: [PermissionAspect(typeof(User), Permission.View)]
2: public ICollection<User> Get()
3: {
4: ICollection<User> users = DummyMethod();
5: return users;
6: }
PostSharp includes the aspect code into the method decorated during the compilation of the program. This way I have a way to use my custom security declaratively and all people of the team do not need to right each time permission initialization code.
Leave a Reply