Author Archives: Brian Pratt

Effin’ with MEF – Trying to actually understand what is going on this time.

I’ve used MEF before, as well as Prism, and any other number of IOC containers.  I’ve never bothered to actually understand what and how they work.  For this post (and any possible future posts), I want to take it really simple and slow.  I want to understand what MEF is doing (but not the behind-the-scenes, bare metal behind the scenes… maybe someday).

So, here is my first stab at a very simple MEF project that even I can understand.

First thing we have to do is reference the MEF assemblies.





Create your module interface, and classes:

My module classes will have a simple DoIt() method that returns a string message.  The interface defines the contract for that method.

   1:   /// <summary>
   2:   /// MEF searches for classes that implement IDoIt
   3:   /// </summary>
   4:   public interface IDoIt
   5:   {
   6:       string DoIt();
   7:   }


Now we need to make some concrete classes that implement the interface IDoIt.

You’ll notice that we have to tell MEF that these classes are “Export”, which means that MEF knows that these classes should be considered for injection into our main class.

 1:  [Export(typeof(IDoIt))]
 2:  public class Di1 : IDoIt
 3:  {
 4:     public string DoIt()
 5:     {
 6:         return "Executed DoItModule1" + System.Environment.NewLine;
 7:     }
 8:  }
 10: [Export(typeof(IDoIt))]
 11: public class Di2 : IDoIt
 12: {
 13:    public string DoIt()
 14:    {
 15:       return "Executed DoItModule2" + System.Environment.NewLine;
 16:    } 
 17: }

Now to set up MEF.

We have to create a container to hold our objects, and some startup code to tell MEF to do its thing.  The IEnumerable DoItModules ends up being a list modules that MEF found that are of type IDoIt.  MEF automatically creates the list of IDoIt modules when we call ComposeParts().

   1:   /// <summary>
   2:   /// This gets filled in by MEF automatically with IDoIt objects
   3:   /// found in this assembly
   4:   /// </summary>
   5:   [ImportMany(typeof(IDoIt))]
   6:   public IEnumerable<Lazy<IDoIt>> DoItModules { get; set; }
   8:   /// <summary>
   9:   /// Load up our catalog of modules
  10:   /// </summary>
  11:   private void AvengersAssemble()
  12:   {
  13:       var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
  14:       var container = new CompositionContainer(catalog);
  15:       container.ComposeParts(this);
  16:   }

Here’s the whole thing:

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.Composition;
   4:  using System.ComponentModel.Composition.Hosting;
   5:  using System.Linq;
   6:  using System.Reflection;
   7:  using System.Text;
   8:  using System.Threading.Tasks;
   9:  using System.Windows;
  10:  using System.Windows.Controls;
  11:  using System.Windows.Data;
  12:  using System.Windows.Documents;
  13:  using System.Windows.Input;
  14:  using System.Windows.Media;
  15:  using System.Windows.Media.Imaging;
  16:  using System.Windows.Navigation;
  17:  using System.Windows.Shapes;
  19:  namespace MefTest
  20:  {
  21:      /// <summary>
  22:      /// Interaction logic for MainWindow.xaml
  23:      /// </summary>
  24:      public partial class MainWindow : Window
  25:      {
  26:          public MainWindow()
  27:          {
  28:              InitializeComponent();
  29:              AvengersAssemble();
  30:              this.Loaded += MainWindow_Loaded;
  31:          }
  33:          /// <summary>
  34:          /// This gets filled in by MEF automatically with IDoIt objects
  35:          /// found in this assembly
  36:          /// </summary>
  37:          [ImportMany(typeof(IDoIt))]
  38:          public IEnumerable<Lazy<IDoIt>> DoItModules { get; set; }
  40:          /// <summary>
  41:          /// Load up our catalog of modules
  42:          /// </summary>
  43:          private void AvengersAssemble()
  44:          {
  45:              var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
  46:              var container = new CompositionContainer(catalog);
  47:              container.ComposeParts(this);
  48:          }
  50:          void MainWindow_Loaded(object sender, RoutedEventArgs e)
  51:          {
  52:              // making sure there are objects here
  53:              foreach (var module in this.DoItModules)
  54:              {
  55:                  info.Text += module.Value.DoIt();
  56:              }
  57:          }
  58:      }
  60:      /// <summary>
  61:      /// MEF searches for classes that implement IDoIt
  62:      /// </summary>
  63:      public interface IDoIt
  64:      {
  65:          string DoIt();
  66:      }
  68:      [Export(typeof(IDoIt))]
  69:      public class Di1 : IDoIt
  70:      {
  71:          public string DoIt()
  72:          {
  73:              return "Executed DoItModule1" + System.Environment.NewLine;
  74:          }
  75:      }
  77:      [Export(typeof(IDoIt))]
  78:      public class Di2 : IDoIt
  79:      {
  80:          public string DoIt()
  81:          {
  82:              return "Executed DoItModule2" + System.Environment.NewLine;
  83:          }
  84:      }
  87:  }


The output of the project loads both DoIt modules, and prints out their DoIt() method to the user control.


WPF IronPython Converters

I often want to do visual displays with loose WPF files that get loaded at runtime (using XamlReader.Load), but to really get work done, you have to create a bunch of converters to do all maths that is required for Storyboards and DoubleAnimations. These converters must exist in your main application as pre-compiled code so that the XamlReader can create the Xaml object at runtime.

So, the idea using IronPython to create scriptable converters at runtime (embedded in the loose Xaml files) came up. Here is the sample program I created to demonstrate it.

This is only a proof of concept app, and probably has many holes in it, but the idea does work.

1. Create an empty WPF Windows project

2. Add IronPython to the project using Nuget



3. Create the Python IValueConverter in code

   1:      public class PythonConverter : IValueConverter
   2:      {
   3:          /// <summary>
   4:          /// The default imports that python needs to create objects WPF can use
   5:          /// </summary>
   6:          string imports = "import clr\r\nclr.AddReferenceByPartialName(\"PresentationCore\")\r\nclr.AddReferenceByPartialName(\"PresentationFramework\")\r\nclr.AddReference('System.Data')\r\nfrom System.Windows import Media\r\n";
   8:          #region IValueConverter Members
  10:          /// <summary>
  11:          /// I expect the Python code to always have a method called "ReturnValue()" defined
  12:          /// </summary>
  13:          public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  14:          {
  15:              string v = value.ToString();
  16:              string p = parameter.ToString(); // parameter is the python code
  17:              p = p.Replace(@"\r\n", System.Environment.NewLine); // we want to add crlf since Python cares about them
  18:              // create the scripting engine
  19:              ScriptEngine pyEngine = Python.CreateEngine();
  20:              // add the default imports to the script
  21:              ScriptSource source = pyEngine.CreateScriptSourceFromString(imports + p, Microsoft.Scripting.SourceCodeKind.Statements);
  22:              ScriptScope scope = pyEngine.CreateScope();
  23:              // create the python object
  24:              var s = source.Execute(scope);
  25:              // get a reference to a method in the code called "ReturnValue"
  26:              // this always expects a string as input and object as output
  27:              Func<string, object> doit = scope.GetVariable("ReturnValue");
  28:              // execute the python method with the converter value
  29:              return doit(v);
  30:          }
  32:          public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  33:          {
  34:              throw new NotImplementedException();
  35:          }
  37:          #endregion
  38:      }

4. Create the converter in Xaml

   1:  <Window x:Class="PythonConverters.MainWindow"
   2:          xmlns=""
   3:          xmlns:x=""
   4:          xmlns:local="clr-namespace:PythonConverters"
   5:          Title="MainWindow" Height="350" Width="525">
   6:      <Window.Resources>
   7:          <local:PythonConverter x:Key="pythonConverter"></local:PythonConverter>
   8:      </Window.Resources>
   9:      <StackPanel>
  10:          <TextBlock>
  11:              <TextBlock.Text>
  12:                  <!-- SETTING JUST PLAIN TEXT WITH PYTHON -->
  13:                  <Binding Path="PythonText"
  14:                           Converter="{StaticResource pythonConverter}"
  15:                           ConverterParameter="def ReturnValue(n): return n + 'hello world';"/>
  16:              </TextBlock.Text>
  17:          </TextBlock>
  19:          <TextBlock Text="This should have color">
  20:              <TextBlock.Background>
  21:                  <!-- SETTING BACKGROUND WITH PYTHON-->
  22:                  <Binding Path="PythonText"
  23:                           Converter="{StaticResource pythonConverter}"
  24:                           ConverterParameter="def ReturnValue(n):\r\n  if n == '':\r\n    return Media.Brushes.Orange;\r\n  else:\r\n    return Media.Brushes.Green;\r\n"/>
  25:              </TextBlock.Background>
  26:          </TextBlock>
  28:      </StackPanel>
  29:  </Window>

5. Run the app


Have a Less Stressful Job with Better Time Management

I’ve been bombarded with tasks at work.  When you constantly get interrupted, it is hard to keep a positive outlook on your day.  While listening to a .Net Rocks! podcast episode #980 “ Managing Your Career with John Sonmez“, they talked about a tool I tried out about a year ago, but let slip by me:  The Pomodoro Technique® (trademark Francesco Cirillo).

The trouble I had when first trying this technique (my only job was software developer) was that I already had a task list from Team Foundation and Scrum, and it seemed like I was just repeating lists.  Now that I need to manage things and people outside of pure development, it makes great sense.

The thing I like about the technique is that I can, at the start of the day, make a list of things I need to accomplish that day.  That list almost never gets done, but the interruption list builds up from the bottom.  Where I used to have only a sense of never accomplishing anything during the day (because of interruptions), I now have a list at the end of the day of things I have done.

I used to go home feeling like the day was a complete waste because I did not complete what I set out to do.  Now I can look back and say “you know what?  I really did accomplish quite a bit today!”

I still keep my daily paper, but I also use KanBan Flow to keep my master list, and to timebox my work iterations.

Give it a shot!  I’m really feeling less stressed because of it.


This blog is not affiliated with, associated with, or endorsed by the Pomodoro Technique® or Francesco Cirillo.


Duplex WCF “Service Bus”: Part 1

We’ve created a mini service bus for use here at work. Many of our services and client applications require information from each other. Sometimes to display active states, sometimes to take action on incoming data. Regardless, we need information delivered to many different endpoints, in an event-like fashion (non-polling).

We started out with this post from Juval Lowy “What you need to know about one-way calls, callbacks and Events.” This was a great starting point for us because it did most of what we wanted: publish and subscribe.

What it did not do was allow for ad-hoc publishing (and subscribing).  All of your callback methods had to be defined.  It was more of WCF method callback framework than a actual service bus.  While there are many free and purchasable ESBs around, our company dislikes using open-source, and purchasing a large ESB didn’t really make sense for our needs.  We needed something lightweight and easy to use.

Using the callback framework, I added just a few simple methods to the classes to allow for generic serialized XML data to be published, and that data to be subscribed to by name alone.  This allows anyone with access to the bus to publish any data they want, under any name they want.  No recompilation required.

Published data is serialized before sending.  The bus always expects an XElement.  It is up to the subscriber to know how to decode the XML into something useful (generally by deserializing the XElement into a known object).

In Part 2, I go into more detail about how it works.