Month: December 2010

Aspect Oriented Programming and Interceptor design pattern with Unity 2


Hello,

I’ve found a Microsoft article about Unity and Aspect Oriented programming. The article was really interesting. Then, to be the theory in action I’ve decide to exemplify how Unity 2 uses the Interceptor design pattern to support Aspect Oriented Programming (aka AOP).  First of all, let talk about the three key elements involved into this example:

Once again, I’ve decide to use MonoDevelop to create the sample and the source code is available to be downloaded from github at
https://github.com/hmadrigal/playground-dotnet/tree/master/MsUnity.AspectOriented

Sample structure

This example supposes that you have a proxy and want it to add logging information. Thus, we’ve defined a contract (interface) called IProxy to define the expected behavior of our proxy. Then, we have in a separate project an concrete implementation Proxy which implements the interface IProxy. At last but not a least, we have a project which defines a Unity interceptor. All these components are united by the configuration file which lets unity know how these components should interact.

AspectOriented.Infrastructure’s project

This project contains all the common resources and the contracts (interfaces) to be used in the sample. Here is defined the IProxy interface:

using System;
namespace AspectOriented.Infrastructure.Services
{
  public interface IProxy
  {
    bool IsEnabled ();
    void Open ();
    void Close ();
  }
}

AspectOriented.UnityInterceptors’s project

The second project we’re going to talk is where the interceptor is defined. As we’ve already mentioned the interceptor will allow unity to perform tasks before and/or after the intercepted method is invoked. To define  which method is going to be intercepted, we can use two alternatives: 1)a configuration file or 2) by writing some code. I’ll talk about the Unity configuration file once I explain the AspectOriented.Terminal’s project.

using System;
using System.Collections.Generic;
using Microsoft.Practices.Unity.InterceptionExtension;

namespace AspectOriented.UnityInterceptors
{
	public class DiagnosticInterceptor : IInterceptionBehavior
	{
		public DiagnosticInterceptor ()
		{
		}

		#region IInterceptionBehavior implementation
		public IMethodReturn Invoke (IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
		{
			System.Console.WriteLine (String.Format ("[{0}:{1}]", this.GetType ().Name, "Invoke"));

			// BEFORE the target method execution
			System.Console.WriteLine (String.Format ("{0}", input.MethodBase.ToString ()));

			// Yield to the next module in the pipeline
			var methodReturn = getNext ().Invoke (input, getNext);

			// AFTER the target method execution
			if (methodReturn.Exception == null) {
				System.Console.WriteLine (String.Format ("Successfully finished {0}", input.MethodBase.ToString ()));
			} else {
				System.Console.WriteLine (String.Format ("Finished {0} with exception {1}: {2}", input.MethodBase.ToString (), methodReturn.Exception.GetType ().Name, methodReturn.Exception.Message));
			}

			return methodReturn;
		}

		public IEnumerable<Type> GetRequiredInterfaces ()
		{
			System.Console.WriteLine (String.Format ("[{0}:{1}]", this.GetType ().Name, "GetRequiredInterfaces"));
			return Type.EmptyTypes;
		}

		public bool WillExecute {
			get {
				System.Console.WriteLine (String.Format ("[{0}:{1}]", this.GetType ().Name, "WillExecute"));
				return true;
			}
		}
		#endregion
	}
}

As you might noticed the interceptor implements IInterceptionBehavior which will let Unity know that this class can act like an interceptor. To simplify things, the interceptor will print message only when the intercepted method is invoked. The printed information is about the method being invoked. However, interceptors can perform more complex such as starting threads, performing web requests and so on.

AspectOriented.Terminal’s project

This is the main project which generates the executable file. Here are two important things to point out. First we’ve configured our container here. In this case  Unity has being configured by using the configuration file, however you can use code instead. The second, the main application performs calls on the instance that unity resolves, the interception process happens behind scenes and we only will see the result when we call the methods of the proxy.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<configSections>
		<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
	</configSections>
	<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
		<!-- Interception is not part of the default Unity configuration schema. -->
		<!-- Before you can configure interception you must add the correct sectionExtension element to your configuration -->
		<!-- section in the configuration file.-->
		<sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration" />
		<!-- Defines some aliast to easily manipulate the mappings -->
		<alias alias="IProxy" type="AspectOriented.Infrastructure.Services.IProxy, AspectOriented.Infrastructure" />
		<alias alias="Proxy" type="AspectOriented.Terminal.Services.Proxy, AspectOriented.Terminal" />
		<alias alias="DiagnosticInterceptor" type="AspectOriented.UnityInterceptors.DiagnosticInterceptor, AspectOriented.UnityInterceptors" />
		<!-- Default Container when creating the tree-chain of resolution-->
		<container>
			<!-- Loading the section extension only enables the interception configuration to be given in the configuration file. -->
			<!-- Interception itself will not work unless you also load the interception container extension in your Unity container instance.-->
			<extension type="Interception" />
			<register type="IProxy" mapTo="Proxy">
				<lifetime type="ContainerControlledLifetimeManager" />
				<interceptor type="InterfaceInterceptor" />
				<interceptionBehavior type="DiagnosticInterceptor" />
			</register>
		</container>
	</unity>
</configuration>

The configuration file defines two section which are mandatory to define interceptors, these are sectionExtension and extension. Then into the registration of a given type (or in our sample the IProxy Type) we can define the interceptors for this particular type resolution.

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;
using AspectOriented.Infrastructure.Services;

namespace AspectOriented.Terminal
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			// Loads the container
			IUnityContainer container = new UnityContainer ();
			container = Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration (container);

			// Resolve the proxy-sample
			var proxy = Microsoft.Practices.Unity.UnityContainerExtensions.Resolve<IProxy> (container);
			if (proxy.IsEnabled ()) {
				proxy.Open ();
			}
			proxy.Close ();

			// End of the test
			Console.ReadKey ();
		}
	}
}

At last but not least we’ve our main code. It’s quite straightforward, it creates a Unity container, loads the container configuration from the configuration file, and then uses the container to resolve the given interface (contract). As I mentioned the magic happens behind-scenes, when you call the Proxy methods there is functionality which is going to be injected before and after each call of this instance. Take a look of the final screen-shot to see the all the terminal messages which were triggered during the method calls of the Proxy.

As you can notice the interception calls are injected before and after each call of the intercepted methods of our proxy instance. Furthermore, we can inject the same logic to different contracts (interfaces) by only updating the configuration file. If there is not a contract, it is still possible to perform interception, Unity 2 supports three mechanisms for interception, just keep in mind that each mechanism has its pros and cons.  Remember that same functionality can be plugged to any other component (instance) by using the same mechanism.

Resources about this topic

Once again, I’ve decide to use MonoDevelop to create the sample and the source code is available to be downloaded from github at
https://github.com/hmadrigal/playground-dotnet/tree/master/MsUnity.AspectOriented

Advertisements

Free ebook “Free ebook: Moving to Microsoft Visual Studio 2010”


Hi,

Microsoft has a new free ebook. This is about Visual Studio 2010, you can get it at:

http://blogs.msdn.com/b/microsoft_press/archive/2010/09/13/free-ebook-moving-to-microsoft-visual-studio-2010.aspx

Best regards,

Herber

Free ebook: Programming Windows Phone 7, by Charles Petzold


Hello

Certainly a platform is as strong as the tools that you can use on it. Microsoft is giving a lot of resources for developers in order to start producing in Windows Phone 7 (WP7). This time Microsoft Press book is giving a free ebook Programming Windows Phone 7 by Charles Petzold.

 

You can download it at Free ebook: Programming Windows Phone 7, by Charles Petzold

Best regards,
Herber

Free ebook: Programming Windows Phone 7, by Charles Petzold

Xhader 1.0 has been released!


Hello,

This is my first open source project that I’ve been published. It’s not based on my code, it’s based on a set of several tools and helpers I’ve been able to find in the web. So, the project itself is just a easy way to access all that resources in one single point by using your Microsoft Blend tool.

Xhader 1.0 Summary

Xaml is a markup language based on xml, which is used to create presentation layer in your Microsoft Application e.g. Silverlight Applications and WPF applications. There is a particular feature that is available for certain users which is to use the support to modify the rendere

See more information at:
Documentation

Download

Best regards,

Herber

Free ebooks from Microsoft Patterns and Practices


Hi,

I’ve collected some information about Microsoft free publications, and I think that they’re something people might be interested in. These ebooks are free and are updated by Microsoft Community (I think most of them from Patterns and Practices). So, the following is a list of the ebooks you will find from Microsoft:

Electronic books (ebooks)

Certainly there are many resources on when which are available to learn about development. Microsoft editorial for example they offer free ebooks from time to time. Microsoft Patterns and Practices also have some free ebooks available to download. Following are ebooks available for free:

Notes

  1. Microsoft Patterns and Practices is an constantly evolving project it’s possible see their progress at Microsoft Patterns and Practices Complete Catalogbacause of this it’s possible that the local version is outdated.
Cover Name Summary Source
Improving Web Services Security byMicrosoft Corporation Patterns and Practices This guide shows you how to make the most of WCF (Windows Communication Foundation). With end-to-end application scenarios, it shows you how to design and implement authentication and authorization in WCF. Learn how to improve the security of your WCF services through prescriptive guidance including guidelines, Q&A, practices at a glance, and step-by-step how tos. It’s a collaborative effort between patterns & practices, WCF team members, and industry experts. wcfsecurityguide at codeplex
Microsoft Application Architecture Guide, 2nd Edition byMicrosoft Corporation Patterns and Practices The guide is intended to help developers and solution architects design and build effective, high quality applications using the Microsoft platform and the .NET Framework more quickly and with less risk; it provides guidance for using architecture principles, design principles, and patterns that are tried and trusted. The guidance is presented in sections that correspond to major architecture and design focus points. It is designed to be used as a reference resource or to be read from beginning to end. Application Architecture Guide at MSDN
Performance Testing Guidance for Web Applications byMicrosoft Corporation Patterns and Practices This guide shows you an end-to-end approach for implementing performance testing. Whether you are new to performance testing, or looking for ways to improve your current performance testing approach, you will find insights that you can tailor for your specific scenarios. perftestingguide at codeplex

Performance Testing Guidance for Web Applications At MSDN

Team Development with Visual Studio Team Foundation Server by Microsoft Corporation Patterns and Practices This guide shows you how to make the most of Team Foundation Server. It starts with the end in mind, but shows you how to incrementally adopt TFS for your organization. It’s a collaborative effort between patterns & practices, Team System team members, and industry experts. tfsguide at codeplex

Team Development with Visual Studio Team Foundation Server at MSDN

Developers Guide to Microsoft Prism byMicrosoft Corporation Patterns and Practices Prism provides guidance designed to help you more easily design and build rich, flexible, and easy to maintain Windows Presentation Foundation (WPF) desktop applications and Silverlight Rich Internet Applications (RIAs) and Windows Phone 7 applications. Using design patterns that embody important architectural design principles, such as separation of concerns and loose coupling, Prism helps you to design and build applications using loosely coupled components that can evolve independently but which can be easily and seamlessly integrated into the overall application. Such applications are often referred to as composite applications. Developer’s Guide to Microsoft Prism at MSDN

Excuse me if I didn’t hosted the ebooks to download, instead I provide the original source link. I think it’s worthy to visit the site because  you are more likely to find the latest version, and visit their site is a good price to pay for a free ebook.

 

Best regards,

Herber