design patterns

How to create a plug in using C# .NET (4.0) and MEF


Hello,

Long time ago I wrote my approach of how to write a plugin (add in) using Microsoft Unity (http://unity.codeplex.com/). In my old approach (https://hmadrigal.wordpress.com/2010/03/28/writing-a-plug-in/) was using the unity.config file to load dynamically the plugins. Certainly the major issue with this approach it’s that you will have to update your unity.config file every time you add a new plugin.

As usual there is a code sample of all this at:
https://github.com/hmadrigal/playground-dotnet/tree/master/MsDotNet.PluginWithMEF The code runs in MonoDevelop as well as in Visual Studio.

On this post I’ll explain how to easily use Microsoft Extensibility Framework (MEF) http://msdn.microsoft.com/en-us/library/dd460648.aspx to load plugins from a directory. Additionally MEF is a framework to create plugins and extensible applications, so it supports more operations other than loading types from external assemblies.

The problem

I want to load different language implementations provided in different assemblies. So, each DLL might (or might not) contain an implementation of a supported language. Moreover, the assemblies can be implemented by third party members, so I cannot binding them into my project at compile time.

The Solution

Defining what on my application needs to be extensible
Define a common contract in order to identify a class which provided a supported language. Moreover all the “extensible” portion of your application should be encapsulated into a simple assembly that could be redistributed to other developers who wants to implement the plugin.
BTW, when implementing plug ins, it’s normal to define a contract (or interface) which defines the required functionality.I’ll be using the word “part” when I’m talking about contract or interfaces.
The project MefAddIns.Extensibility defines an interface which can be used to provide a supported language.

namespace MefAddIns.Extensibility
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    /// <summary>
    /// Defines the functionality that third parties have to implement for my language plug in
    /// </summary>
    public interface ISupportedLanguage
    {
        string Author { get; }
        string Version { get; }
        string Description { get; }
        string Name { get; }
    }
}

Implementing the plug in
Now it’s the time to provide implementation of supported languages. Each project of MefAddIns.Language.English, MefAddIns.Language.Japanese and MefAddIns.Language.Spanish provides at least one implementation for the interface ISupportedLanguage. These projects could be developed internally or by third party people. An example of this implementation is:

namespace MefAddIns.Language.English
{
    using MefAddIns.Extensibility;
    using System.ComponentModel.Composition;

    /// <summary>
    /// Provides an implementation of a supported language by implementing ISupportedLanguage.
    /// Moreover it uses Export attribute to make it available thru MEF framework.
    /// </summary>
    [Export(typeof(ISupportedLanguage))]
    public class EnglishLanguage : ISupportedLanguage
    {
        public string Author
        {
            get { return @"Herberth Madrigal"; }
        }
        public string Version
        {
            get { return @"EN-US.1.0.0"; }
        }
        public string Description
        {
            get { return "This is the English language pack."; }
        }
        public string Name
        {
            get { return @"English"; }
        }
    }
}

Please note that the attribute Export indicates to MEF framework that the class EnglishLanguage can be used when a ISupportedLanguage is requested. In other words, if any other application is looking for a part ISupportedLanguage then MEF framework will suggest EnglishLanguage. In further steps we are going to create a MEF catalog which is the mechanism to associate exported parts with the members which need to import parts.

Defining the parts that my application needs to import
The simplest way of doing this with MEF is by using the import attribute. On this case I’ll be using ImportMany because of I’ll be expecting many (0 or more) implementations of the ISupportedLanguage interface. For example:

namespace MefAddIns.Terminal
{
    using MefAddIns.Extensibility;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;

    public class Bootstrapper
    {
        /// <summary>
        /// Holds a list of all the valid languages for this application
        /// </summary>
        [ImportMany]
        public IEnumerable<ISupportedLanguage> Languages { get; set; }

    }
}

Composing your objects by using (MEF) catalogs
Before getting into details I’ll like to point out some concepts:

Part: It’s the portion of our code that can be exported or imported.
Export: It’s the fact of indicating that a portion of our code is available and it fits a set of traits. E.g. EnglishLanguage implements the ISupportedLanguage Interface, thus I can add the attribute Export(typeof(ISupportedLanguage)).
Import: It’s the fact of indicating that a portion of our code requires a part that fits a set of traits. E.g. I need to import a give language, then I define a property of ISupportedLanguage type and set the attribute Import(typeof(ISupportedLanguage)).
Catalog: It a source of Exports and Import definitions. It could be the current execution context or a set of binaries files (such as dlls, exes).
Container: It’s an module which deals with class instantiation. This item uses the catalog when needed in order to create the instances during the composition process.
Composition: It’s the fact of taking an object and making sure that all its needs regarding imports are fulfilled. Certainly this will depends on the catalogs and the export and imports that are being used on the catalog.

Now, that we now more about come MEF concepts. Lets talk more about MEF in our example. MEF detects that some code is Exporting parts, and other code is Importing. The process of loading the parts is made by creating a catalog. There are many ways of creating catalogs, on my example is using a DictionaryCatalog. The DictionaryCatalog uses a directory to look for files, and it creates a catalog with all the exported parts from the assemblies (or files) of the given directory. Finally our application creates an instance of the Bootstrapper class, this instance indicates that it requires all the possible instances of ISupportedLanguages that are into the DictionaryCatalog. Here is a sample of this:

namespace MefAddIns.Terminal
{
    using System.ComponentModel.Composition.Hosting;
    using System.ComponentModel.Composition;
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            var bootStrapper = new Bootstrapper();

            //An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();
            //Adds all the parts found in same directory where the application is running!
            var currentPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(Program)).Location);
            catalog.Catalogs.Add(new DirectoryCatalog(currentPath));

            //Create the CompositionContainer with the parts in the catalog
            var _container = new CompositionContainer(catalog);

            //Fill the imports of this object
            try
            {
                _container.ComposeParts(bootStrapper);
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }

            //Prints all the languages that were found into the application directory
            var i = 0;
            foreach (var language in bootStrapper.Languages)
            {
                Console.WriteLine("[{0}] {1} by {2}.\n\t{3}\n", language.Version, language.Name, language.Author, language.Description);
                i++;
            }
            Console.WriteLine("It has been found {0} supported languages",i);
            Console.ReadKey();
        }

    }
}

Now that we have all that our application requires, we’re able to run the app and see the following output:

Example of the output where it lists all the supported languages

Hey It’s not printing anything!!!
Ok. There is an additional thing to talk, which it’s not strictly related to MEF. As your might noticed our sample application does not have references to any of the MefAddIns.Language.* Dlls but it’s running code from them. Here is the deal, since our application uses MEF we don’t need to reference directly these DLLS, we just need to copy them into the directory where the DirectoryCatalog is going to look for them. The code sample looks into the directory where the application is running, so we have configured our main csproj to copy the DLLS to the output directory of our main application.
To keep it simple, you can do it in two steps 😉
1) Add the external DLLs into your project. First, Right click on your main project, and click on “Add existing item…”. Look for the DLL, and select “Add as a Link”. The configure the properties of the added file to copy always or copy when newer.
2) Update the csproj file. Right click on your project, and the select “Unload project”. Then once again right click on your project and select “Edit xxxxx.csproj”. This will open the project as an XML file. Look for the added DLL, and replace part of portions of the path for MSBuild variables such as $(Configuration). Note that there are more options to do this, such as using the Copy task from MSBuild (see http://stackoverflow.com/questions/266888/msbuild-copy-output-from-another-project-into-the-output-of-the-current-project ). In our sample this was enough because we are looking for DLLs into the current directory, but depending on your file structure this won’t be recommended.

<ItemGroup>
    <Content Include="
..\MefAddIns.Language.English\bin\$(Configuration)\MefAddIns.Language.English.dll;
..\MefAddIns.Language.Japanese\bin\$(Configuration)\MefAddIns.Language.Japanese.dll;
..\MefAddIns.Language.Spanish\bin\$(Configuration)\MefAddIns.Language.Spanish.dll;">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>false</Visible>
    </Content>
  </ItemGroup>

At last comment, this is the most basic sample of using MEF to create a plugin-based structure. There are more things to consider , e.g. the path where your DLLs are going to be placed or how your main application is going to exchange information with the plugins. MEF has also more options to create extensible applications. Also, it’s important to consider when it’s good to create plugin based architectures rather that tightly coupled apps.

EDIT In my last update I modified the project (csproj) to make it run on MonoDevelop ;-). The major change is that some tasks on MSBuild aren’t available in XBuild. So, the last step which modified the csproject, now looks like:

<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <Content Include="..\MefAddIns.Language.English\bin\Debug\MefAddIns.Language.English.dll">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>
    <Content Include="..\MefAddIns.Language.Japanese\bin\Debug\MefAddIns.Language.Japanese.dll">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>
    <Content Include="..\MefAddIns.Language.Spanish\bin\Debug\MefAddIns.Language.Spanish.dll">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>
  </ItemGroup>
  <ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <Content Include="..\MefAddIns.Language.English\bin\Release\MefAddIns.Language.English.dll">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>
    <Content Include="..\MefAddIns.Language.Japanese\bin\Release\MefAddIns.Language.Japanese.dll">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>
    <Content Include="..\MefAddIns.Language.Spanish\bin\Release\MefAddIns.Language.Spanish.dll">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>
  </ItemGroup>

The code sample for this application is at:
https://github.com/hmadrigal/playground-dotnet/tree/master/MsDotNet.PluginWithMEF

Best regards,
Herber

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

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