While not strictly required, a new permission should support declarative security in order to enable developers to use the permission as a declaration. The following code implements the attribute for a Boolean permission named SamplePermission.
The AttributeUsage defines how the attribute may be applied. Security attributes for declarations are special in that they must derive from the SecurityAttribute class – in this case (being a code access permission) the attribute class derives from CodeAccessSecurityAttribute, which derives from SecurityAttribute.
The attribute class consists of constructors and properties that allow specification of an instance of the corresponding security permission object. In this instance the object has a single Boolean flag as state: the attribute would be used as illustrated by the following demand declaration.
[SamplePermissionAttribute(SecurityAction.Demand, Flag=true)]
Security attribute classes must implement the CreatePermission method which servers to create an instance of the permission object from the associated attribute class. In this case CreatePermission checks the internal m_flag variable which hold the value set by Flag=true in the example above, and creates a corresponding instance of the SamplePermission object accordingly. (While only the flag=true case is useful, the attribute class should support all possible states of the permission object.)
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] class SamplePermissionAttribute : CodeAccessSecurityAttribute { bool m_flag = false; public SamplePermissionAttribute ( SecurityAction action ) : base( action ) {} public SecurityPermissionFlag Flag { get { return m_flag; } set { m_flag = value; } } public override IPermission CreatePermission() { if (m_flag) return new SamplePermission( PermissionState.Unrestricted ); else return new SamplePermission (PermissionState.None); } }