views:

136

answers:

2

I realize you can't get the target entity in the Attribute itself, but what about in an associated Permission object when using a CodeAccessSecurityAttribute? The Permission object gets called at runtime so it seems there should be a way but I'm at a loss.

public sealed class MySecurityAttribute : CodeAccessSecurityAttribute
{
 public override IPermission CreatePermission()
 {
  MySecurityPermission permission = new MySecurityPermission();

  //set its properties
  permission.Name = this.Name;
  permission.Unrestricted = this.Unrestricted;
  return permission;
 }

}

public class MySecurityPermission : IPermission, IUnrestrictedPermission
{

 public MySecurityPermission(PermissionState state)
 {
           // what method was the attribute decorating that
           // created this MySecurityPermission?
 }

 public void Demand()
 {
           // Or here?
 }
}
A: 

Well, I guess you could use reflection to scan through all the loaded assemblies, looking for any class/member that has this as an attribute. It'd be quite slow, though, so it's not something you'd want to do often, or in a large project.

Miral
Yup, that's the only solution I could come up with as well but reflection isn't an option given the project size, and frequency it would need to occur. Thanks for the feedback though.
Mike
A: 

What about walking the call stack? At least that would narrow down what you need to reflect over. Grab System.Diagnostics.StackTrace and use GetFrame to get the stack frame one step up from where you are.

It's rather nasty though - CAS attributes really, in my opinion, shouldn't be conditional on what was decorated, rather they should depend on the conditions set in their parameters.

blowdart