Sometimes there is the need or desire to resort to Aspect-Oriented frameworks (AOP) in order to add some validations or cross-cutting concerns. In several situations, it is indeed necessary, but .NET already offers some hooks that we can use to achieve parts of this functionality. One of those is CodeAccessSecurityAttribute. In a nutshell, it allows the application of security checks whenever some code – method, property – is called. A somewhat well known example is PrincipalPermissionAttribute.
Let’s see an example of how we can restrict a method so that it can only be called on a specific day of the week:
The Intersect, Union and IsSubsetOf methods really don’t apply in this simple case, but the Demand method does: this is where the actual logic goes. The example should be pretty straightforward. One thing to keep in mind, though: classes inheriting from CodeAccessSecurityAttribute should expose a public constructor with a single SecurityAction parameter, otherwise, it won’t be called.
The attribute can be applied as:
But this technique can be used for things other than permission checks. Let’s see logging applied to a class:
Yes, I know… it really has no access to method parameters, and it really doesn’t anything really productive, it’s just an example, remember!
An example of its usage:
If you have other usages, please send them to me, I’ll make sure to refer where they came from!