How do I prevent a C# method from executing using an attribute validator?

Posted by Boydski on Stack Overflow See other posts from Stack Overflow or by Boydski
Published on 2010-03-22T14:42:26Z Indexed on 2010/03/22 15:01 UTC
Read the original article Hit count: 326

Filed under:
|
|

I'd like to create an attribute-based validator that goes a few steps beyond what I've seen in examples. It'll basically prevent methods or other functionality from executing.

Please be aware that I'm having to use AzMan since I have no availability to Active Directory in this scenario.

Here's some pseudo code of what what I'm looking for:

// Attribute validator class AttributeUsage is arbitrary at this point and may include other items
[AttributeUsage( AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true, Inherited = true )]
public class PermissionsValidatorAttribute : Attribute
{
 public PermissionsValidatorAttribute(PermissionEnumeration permission){...}
 public bool UserCanCreateAndEdit(){...}
 public bool UserCanDelete(){...}
 public bool UserCanUpload(){...}
}

Here's a sample of a class/member that'll be decorated. The method will not be executed at all if the PermissionValidator.UserCanDelete() doesn't return true from wherever it's executed:

public class DoStuffNeedingPermissions
{
 [PermissionValidator(PermissionEnumeration.MustHaveDeletePermission)]
 public void DeleteSomething(){...}
}

I know this is a simple, incomplete example. But you should get the gist of what I'm needing. Make the assumption that DeleteSomething() already exists and I'm preferring to NOT modify the code within the method at all.

I'm currently looking at things like the Validation Application Block and am messing with custom attribute POC's. But I'd love to hear opinions with code samples from everyone out there. I'm also certainly not opposed to other methods of accomplishing the same thing such as extension methods or whatever may work to accomplish the same thing. Please remember I'm making the attempt to minimize changes to existing DoStuffNeedingPermissions code. Thanks everyone!

© Stack Overflow or respective owner

Related posts about c#

Related posts about attributes