Contents tagged with AOP

  • Applying Code Access Restrictions in .NET

    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:

       1: [Serializable]
       2: public sealed class DayOfWeekPermission : IPermission
       3: {
       4:     public DayOfWeek AllowedDayOfWeek { get; private set; }
       5:  
       6:     public DayOfWeekPermission(DayOfWeek allowedDayOfWeek)
       7:     {
       8:         this.AllowedDayOfWeek = allowedDayOfWeek;
       9:     }
      10:  
      11:     #region IPermission Members
      12:  
      13:     public IPermission Copy()
      14:     {
      15:         return(new DayOfWeekPermission(this.AllowedDayOfWeek));
      16:     }
      17:  
      18:     public void Demand()
      19:     {
      20:         new SecurityPermission(SecurityPermissionFlag.ControlPrincipal).Assert();
      21:  
      22:         if (this.AllowedDayOfWeek != DateTime.Today.DayOfWeek)
      23:         {
      24:             throw (new SecurityException("Cannot run on the current day of week") { Action = SecurityAction.Demand, FirstPermissionThatFailed = this, DenySetInstance = this });
      25:         }
      26:     }
      27:  
      28:     public IPermission Intersect(IPermission target)
      29:     {
      30:         return (null);
      31:     }
      32:  
      33:     public Boolean IsSubsetOf(IPermission target)
      34:     {
      35:         return (false);
      36:     }
      37:  
      38:     public IPermission Union(IPermission target)
      39:     {
      40:         return (this);
      41:     }
      42:  
      43:     #endregion
      44:  
      45:     #region ISecurityEncodable Members
      46:  
      47:     public void FromXml(SecurityElement e)
      48:     {
      49:         if (e.Tag == "AllowedDayOfWeek")
      50:         {
      51:             this.AllowedDayOfWeek = (DayOfWeek) Enum.Parse(typeof(DayOfWeek), e.Text, true);
      52:         }
      53:     }
      54:  
      55:     public SecurityElement ToXml()
      56:     {
      57:         return (new SecurityElement("AllowedDayOfWeek", this.AllowedDayOfWeek.ToString()));
      58:     }
      59:  
      60:     #endregion
      61: }
      62:  
      63: [Serializable]
      64: [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
      65: public sealed class DayOfWeekPermissionAttribute : CodeAccessSecurityAttribute
      66: {
      67:     public DayOfWeek AllowedDayOfWeek { get; set; }
      68:  
      69:     public DayOfWeekPermissionAttribute(SecurityAction action) : base(action)
      70:     {
      71:     }
      72:  
      73:     public override IPermission CreatePermission()
      74:     {
      75:         return (new DayOfWeekPermission((this.AllowedDayOfWeek)));
      76:     }
      77:  
      78:     public override Boolean Equals(Object obj)
      79:     {
      80:         var dowp = obj as DayOfWeekPermissionAttribute;
      81:  
      82:         if (dowp == null)
      83:         {
      84:             return (false);
      85:         }
      86:  
      87:         return (dowp.AllowedDayOfWeek == this.AllowedDayOfWeek);
      88:     }
      89:  
      90:     public override Int32 GetHashCode()
      91:     {
      92:         return (this.AllowedDayOfWeek.GetHashCode());
      93:     }
      94: }

    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:

       1: [DayOfWeekPermission(SecurityAction.Demand, AllowedDayOfWeek = DayOfWeek.Monday)]
       2: public void MethodToRunOnMondays()
       3: {
       4:     //if today is not Monday, an exception is thrown
       5: }

    But this technique can be used for things other than permission checks. Let’s see logging applied to a class:

       1: [Serializable]
       2: [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
       3: public sealed class LogPermissionAttribute : CodeAccessSecurityAttribute
       4: {
       5:     public LogPermissionAttribute(SecurityAction action) : base(action)
       6:     {
       7:     }
       8:  
       9:     public override IPermission CreatePermission()
      10:     {
      11:         return (new LogPermission());
      12:     }
      13:  
      14:     public override Boolean Equals(Object obj)
      15:     {
      16:         return (obj is LogPermissionAttribute);
      17:     }
      18:  
      19:     public override Int32 GetHashCode()
      20:     {
      21:         return (base.GetHashCode());
      22:     }
      23: }
      24:  
      25: [Serializable]
      26: public sealed class LogPermission : IPermission
      27: {
      28:  
      29:     #region IPermission Members
      30:  
      31:     public IPermission Copy()
      32:     {
      33:         return (new LogPermission());
      34:     }
      35:  
      36:     public void Demand()
      37:     {
      38:         var stackTrace = new StackTrace();
      39:         var frames = stackTrace.GetFrames().Skip(2);
      40:         var callingMethod = frames.First().GetMethod();
      41:         System.Console.WriteLine("Calling method {0}", callingMethod);
      42:     }
      43:  
      44:     public IPermission Intersect(IPermission target)
      45:     {
      46:         return (null);
      47:     }
      48:  
      49:     public Boolean IsSubsetOf(IPermission target)
      50:     {
      51:         return (false);
      52:     }
      53:  
      54:     public IPermission Union(IPermission target)
      55:     {
      56:         return (this);
      57:     }
      58:  
      59:     #endregion
      60:  
      61:     #region ISecurityEncodable Members
      62:  
      63:     public void FromXml(SecurityElement e)
      64:     {
      65:     }
      66:  
      67:     public SecurityElement ToXml()
      68:     {
      69:         return (new SecurityElement("LogPermission", String.Empty));
      70:     }
      71:  
      72:     #endregion
      73: }

    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! Winking smile

    An example of its usage:

       1: [LogPermission(SecurityAction.Demand)]
       2: public class MyClass
       3: {
       4:     //all method calls will be logged
       5: }

    If you have other usages, please send them to me, I’ll make sure to refer where they came from! Smile

    Read more...

  • Unity – Part 6: Registration by Convention

    Introduction

    OK, sixth post on this series, long overdue. You will find the fifth (Injecting Values) here, the fourth (Extensions) here, the third (Aspect-Oriented Programming) here, the second (Dependency Injection) here and the first one (Introduction) here.

    This time I’m going to talk about something that came out in Unity 3, automatic (or convention-based) registration of components.

    Automatic Registration

    Normally, you register your components by using one of the Register* methods declared in IUnityContainer. The problem is that this has to be done explicitly for each component. Well, since Unity 3, we now have an automatic, convention-based mechanism.

    The automatic configuration has two options:

    1. Using the RegisterTypes method overload that takes several parameters: one for each type to map, a delegate for choosing the registration keys, a delegate for choosing the name of the registration and finally another one for selecting the lifetime manager;
    2. Using the RegisterTypes overload that takes a single instance of a RegistrationConvention-derived class.

    So, here’s an example of the first approach:

       1: unity.RegisterTypes(AllClasses.FromAssemblies(new Assembly[] { Assembly.GetExecutingAssembly() }), WithMappings.FromAllInterfacesInSameAssembly, WithName.TypeName, WithLifetime.ContainerControlled);

    This will map all of the types that implement interfaces in the current assembly from their interfaces, provided they belong to the same assembly of their implementation, with a name equal to the implementation type and with a lifetime of singleton.

    A more sensible approach, however, might be instead:

       1: unity.RegisterTypes(AllClasses.FromAssemblies(new Assembly[] { Assembly.GetExecutingAssembly() }).Where(x => (x.IsPublic == true) && (x.GetInterfaces().Any() == true) && (x.IsAbstract == false) && (x.IsClass == true)), WithMappings.FromAllInterfacesInSameAssembly, type => (unity.Registrations.Select(x => x.RegisteredType).Any(r => type.GetInterfaces().Contains(r) == true) == true) ? WithName.TypeName(type) : WithName.Default(type), WithLifetime.ContainerControlled);

    This has the following advantage: maps the first found implementation with an empty name, and the others with a name equal to the implementation type.

    A RegistrationConvention class could be like this:

       1: public class InterfaceToTypeConvention : RegistrationConvention
       2: {
       3:     private readonly IUnityContainer unity;
       4:     private readonly IEnumerable<Type> types;
       5:  
       6:     public InterfaceToTypeConvention(IUnityContainer unity, params Assembly [] assemblies) : this(unity, assemblies.SelectMany(a => a.GetExportedTypes()).ToArray())
       7:     {
       8:         this.unity = unity;
       9:     }
      10:  
      11:     public InterfaceToTypeConvention(IUnityContainer unity, params Type[] types)
      12:     {
      13:         this.unity = unity;
      14:         this.types = types ?? Enumerable.Empty<Type>();
      15:     }
      16:  
      17:     public override Func<Type, IEnumerable<Type>> GetFromTypes()
      18:     {
      19:         return (WithMappings.FromAllInterfacesInSameAssembly);
      20:     }
      21:  
      22:     public override Func<Type, IEnumerable<InjectionMember>> GetInjectionMembers()
      23:     {
      24:         return (x => Enumerable.Empty<InjectionMember>());
      25:     }
      26:  
      27:     public override Func<Type, LifetimeManager> GetLifetimeManager()
      28:     {
      29:         return (WithLifetime.ContainerControlled);
      30:     }
      31:  
      32:     public override Func<Type, String> GetName()
      33:     {
      34:         return (type => (this.unity.Registrations.Select(x => x.RegisteredType).Any(r => type.GetInterfaces().Contains(r) == true) == true) ? WithName.TypeName(type) : WithName.Default(type));
      35:     }
      36:  
      37:     public override IEnumerable<Type> GetTypes()
      38:     {
      39:         return (this.types.Where(x => (x.IsPublic == true) && (x.GetInterfaces().Any() == true) && (x.IsAbstract == false) && (x.IsClass == true)));
      40:     }
      41: }

    And its registration:

       1: unity.RegisterTypes(new InterfaceToTypeConvention(unity, Assembly.GetExecutingAssembly()));

    Obviously, this approach is more reusable, the same convention class can be carried over to different projects.

    One thing worth mentioning: if you specify a lifetime manager, anyone other than null, each registered type will be mapped to itself, besides to its interfaces. For example, a class MyService that implements IMyService will be mapped both as IMyService –> MyService and MyService –> MyService. This is by design.

    Conclusion

    And that’s it for automatic configurations. Now it’s up to you to customize how you want things to be registered: name of the registration, lifetime, etc.

    Stay tuned for more on Unity soon!

    Read more...

  • Unity – Part 3: Aspect Oriented Programming

    AOP

    This is my third post on Unity. See the first here for an introduction and the second here for how to apply dependency injection.

    Aspect Oriented Programming (AOP) is a technique for applying cross-cutting concerns to existing implementations, without modifying them. Some examples of it are:

    • Wrapping method calls that go to the database in transactions automatically;
    • Logging all calls to some method, including the input parameters and return value;
    • Catching exceptions thrown in a method automatically and doing something with them.

    AOP is supported in the Enterprise Library (of which Unity is part) by the Policy Injection application block, and it can be integrated with Unity. You must install this application block, perhaps by using NuGet:

    image

    We need to add the interception behavior – which is the one that actually applies aspects – to Unity, either by code:

       1: unity.AddNewExtension<Interception>();

    Or by XML configuration:

       1: <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
       2:     <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>
       3: </unity>

    Having said that, the first concept we need to know is that of an interceptor. An interceptor in the Policy Injection block is an implementation of Microsoft.Practices.Unity.InterceptionExtension.IInterceptor interface, and there are three implementations:

    It is required that, when you are going to apply an aspect to a registration, you choose an interceptor suitable for that registration, based on what type we are registering.

    An aspect itself is an implementation of Microsoft.Practices.Unity.InterceptionExtension.ICallHandler, Unity includes five out of the box such handlers:

    The ICallHandler interface only defines a single method, Invoke, which wraps a method’s arguments and allows having code run before, after or even instead of the target method, and an Order property, for specifying the order by which the aspect should be applied, in case there are many.

    A simple call handler, for outputting some string before or after a method call, might be:

       1: public class OutputCallHandler : ICallHandler
       2: {
       3:     public Boolean Before
       4:     {
       5:         get;
       6:         set;
       7:     }
       8:  
       9:     public Boolean After
      10:     {
      11:         get;
      12:         set;
      13:     }
      14:  
      15:     public String Message
      16:     {
      17:         get;
      18:         set;
      19:     }
      20:  
      21:     Int32 ICallHandler.Order
      22:     {
      23:         get;
      24:         set;
      25:     }
      26:  
      27:     IMethodReturn ICallHandler.Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
      28:     {
      29:         if (this.Before == true)
      30:         {
      31:             Console.WriteLine(this.Message);
      32:         }
      33:  
      34:         IMethodReturn result = getNext()(input, getNext);
      35:  
      36:         if (result.Exception != null)
      37:         {
      38:             Console.Error.WriteLine(result.Exception.Message);
      39:         }
      40:         else
      41:         {
      42:             if (this.After == true)
      43:             {
      44:                 Console.WriteLine(this.Message);
      45:             }
      46:         }
      47:  
      48:         return (result);
      49:     }
      50: }

    Another option is to have interception for all methods of the target registration, which can be achieved by implementing Microsoft.Practices.Unity.InterceptionExtension.IInterceptionBehavior in a concrete class, such as this:

       1: public class MyInterceptionBehavior : IInterceptionBehavior
       2: {
       3:     IEnumerable<Type> IInterceptionBehavior.GetRequiredInterfaces()
       4:     {
       5:         return (Type.EmptyTypes);
       6:     }
       7:  
       8:     IMethodReturn IInterceptionBehavior.Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
       9:     {
      10:         //before target method call
      11:  
      12:         if (input.MethodBase == typeof(MyService).GetMethod("DoSomething"))
      13:         {
      14:             //do something
      15:         }
      16:  
      17:         IMethodReturn methodReturn = getNext().Invoke(input, getNext);
      18:  
      19:         //after target method call
      20:  
      21:         return (methodReturn);
      22:     }
      23:  
      24:     Boolean IInterceptionBehavior.WillExecute
      25:     {
      26:         get
      27:         {
      28:             return (true);
      29:         }
      30:     }
      31: }

    If we want to cancel the default method call, if it is non void, we must return an appropriate value:

       1: IMethodReturn methodReturn = input.CreateMethodReturn(someValue, input.Arguments);

    Or if we want to return an exception:

       1: IMethodReturn methodReturn = input.CreateExceptionMethodReturn(new SomeException());

    There are three ways by which we can apply an aspect to a registration:

    • By applying an attribute to a method on the declaring or target type;
    • By code configuration;
    • By XML configuration.

    Interception By Attributes

    We need to create an attribute that derives from Microsoft.Practices.Unity.InterceptionExtension.HandlerAttribute and which instantiates our call handler:

       1: [Serializable]
       2: [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
       3: public sealed class OutputCallHandlerAttribute : HandlerAttribute
       4: {
       5:     public Boolean Before
       6:     {
       7:         get;
       8:         set;
       9:     }
      10:  
      11:     public Boolean After
      12:     {
      13:         get;
      14:         set;
      15:     }
      16:  
      17:     public String Message
      18:     {
      19:         get;
      20:         private set;
      21:     }
      22:  
      23:     public OutputCallHandlerAttribute(String message)
      24:     {
      25:         this.Message = message;
      26:     }
      27:  
      28:     public override ICallHandler CreateHandler(IUnityContainer container)
      29:     {
      30:         return (new OutputCallHandler() { After = this.After, Before = this.Before, Message = this.Message });
      31:     }        
      32: }

    And we apply it to any method declaration:

       1: public interface IMyService
       2: {
       3:     [OutputCallHandler("Before", Before = true)]
       4:     [OutputCallHandler("After", After = true)]
       5:     void DoSomething();
       6: }

    But before this works, we need to tell Unity to use interface interception for our type:

       1: unity.Configure<Interception>().SetDefaultInterceptorFor<IMyService>(new InterfaceInterceptor());

    Interception By Code

    For intercepting by code, whenever we register something with Unity, we also tell it to use interface interception and to include a behavior instance – it is not possible to specify a call handler for a specific method:

       1: unity.RegisterType<IMyService, MyService>(new ContainerControlledLifetimeManager(), new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<OutputInterceptionBehavior>());

    Interception By Configuration

    When applying interception by configuration we also cannot target a specific method, but instead specify an interception behavior, which will apply to all method – of course, inside of it we can do our own filtering, by looking at the IMethodInvocation.MethodBase property:

       1: <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
       2:     <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>
       3:     <container>
       4:         <extension type="Microsoft.Practices.Unity.InterceptionExtension.Interception, Microsoft.Practices.Unity.Interception"/>
       5:         <interceptors>
       6:             <interceptor type="InterfaceInterceptor">
       7:                 <default type="MyNamespace.IMyService, MyAssembly"/>
       8:             </interceptor>
       9:         </interceptors>
      10:         <register type="MyNamespace.IMyService, MyAssembly" mapTo="MyNamespace.MyService, MyAssembly">
      11:             <lifetime type="singleton"/>
      12:             <interceptionBehavior type="MyNamespace.OutputInterceptionBehavior, MyAssembly"/>
      13:         </register>
      14:         </register>
      15:     </container>
      16: </unity>

    Executing

    You must Unity to retrieve an instance, which will be properly wrapped in a proxy, and from there all of your configured interceptors will be called:

       1: IMyService svc = ServiceLocator.Current.GetInstance<IMyService>();
       2: svc.DoSomething();

    Next in line: extending Unity.

    Read more...