# Wednesday, June 24, 2009

I'm really looking forward to attending the CodeStock conference in Knoxville, TN this weekend.

The speaker lineup looks amazing (not just because I'm in it) and the two-day format should give me time to talk with a lot of attendees outside of the sessions.

I will bring my video camera to CodeStock in hopes of recording more interviews for my online TV show "Technology and Friends". In this show I interview technologists about their passions.  Past shows have focused on topics such as frameworks, careers, events and community-building. A typical show lasts 10-20 minutes, so it tends to be very focused. You can see the first 29 episodes by clicking here: http://www.davidgiard.com/CategoryView,category,Interviews.aspx

If you would like to be on this show, please e-mail at me at  and suggest a topic you would like to cover.

And if you see me at CodeStock, please stop me and say "Hello".

Join me at CodeStock

Wednesday, June 24, 2009 1:40:18 PM (GMT Daylight Time, UTC+01:00)

Mike Cramer and I grew up in suburban Detroit when Mark "The Bird" Fidrych burst onto the sports scene.  Tall, lanky, long-haired and filled with quirks, the Bird captured the imagination of both kids and adults during his time with the Detroit Tigers. His career was brief but spectacular. He won Rookie of the Year in 1976, but an misdiagnosed arm injury the following year hindered his performance for the rest of his career.  Several attempted comebacks fell short and Fidrych pitched his last Major League game in 1980.

In 1976, Fidrych was famous for both his pitching prowess (he started the All-Star game and was runner-up in the Cy Young voting as a rookie) and for his on-field personality.  I saw him pitch once that year.  I was 14 years old and I remember well his enthusiasm for the game.  He would talk to the baseball between pitches and sometimes he would get down on his hands and knees to smooth out the dirt of the mound. He never hid his joy after getting a batter out or retiring a side or winning a game.

Now Mike Cramer has a film which features Mark Fidrych and the effect he had on a young boy in suburban Detroit - an effect The Bird still had when the boy grew up and struggled with his empty life at middle age and set out across the country to find the answers from his boyhood hero.

Mike's movie - Dear Mr. Fidrych - debuts this Friday night June 26 at the Detroit-Windsor International Film Festival.

Mr. Fidrych will not be in attendance.  The Bird passed away less than three months ago, killed while working alone on a dump truck on his Massachusetts farm.

But the Bird is in this film and I believe he will be at this screening in spirit. I hope you go watch it. The Bird and the movie may inspire you the way he inspired me when I was a kid; the way he inspired Mike Cramer and the boy turned man of the movie.  Maybe he'll inspire a generation of sports fans and movie fans who never got a chance to see him.

Maybe this is the comeback that baseball denied The Bird.

Wednesday, June 24, 2009 3:40:49 AM (GMT Daylight Time, UTC+01:00)
# Tuesday, June 16, 2009

Episode 29

Berlin software developer Ziad Hakim recently completed his first iPhone application. In this interview, Ziad discusses his application and the process of developing for the IPhone.

12 mins, 18 secs

 

Tuesday, June 16, 2009 3:10:41 AM (GMT Daylight Time, UTC+01:00)
# Monday, June 15, 2009

In previous articles, I showed how to create a simple MEF contract based on a string and a contract based on an Interface.

Recall that MEF uses a contract that matches Import and Export components at runtime.  Contracts are defined by Import and Export attributes applied to declarations and definitions, respectively.

In this article, I'll show how to add metadata to your export data and to read that metadata at runtime.

We'll start with the sample created in my article about Interfaces.  In this sample, we created three projects:

  • MEFInterface contains the IToDo interface.
  • MEFConsoleApp1 is our console application.  It contains the Import property based on the IToDo interface.
  • MEFComponent1 is a class library containing an exported property implementing the IToDo interface.

We can add metadata to an Export with the ExportMetaData attribute.  The ExportMetaData attribute accepts two parameters: the name and the value of metadata applied to that export.  When MEF imports this export, the metadata is imported as well and is accessible from code.  Below is an Export from our sample with the ExportMetaData attribute applied.

    [Export(typeof(IToDo))]
    [ExportMetadata("Priority", 2)]
    public class FirstTask : IToDo
    {
        ...
    }

We apply a similar attribute to the other Export in MEFComponent1

    [Export(typeof(IToDo))]
    [ExportMetadata("Priority", 1)]
    public class ImportantTask : IToDo
    {
        ...
    }

MEFConsoleApp1 contained an Import that declared a collection of IToDo objects. To access the metadata of this collection, we should change the declaration to an ExportCollection. An ExportCollection implements the IEnumerable interface, but also exposes MEF metadata.

        [Import(typeof(IToDo))]
        public ExportCollection<IToDo> ToDoList { get; set; }

The code telling MEF to match up contracts remains the same; but the code to access the data and metadata changes to loop through the ExportCollection, as shown below.

            foreach (Export<IToDo> exTd in ToDoList)
            {
                IToDo td = exTd.GetExportedObject();
                Console.WriteLine(td.TaskName);
                int priority = Convert.ToInt32(exTd.Metadata["Priority"]);
                Console.WriteLine("Priority=" + priority.ToString());
            }

In the above code, exTd is an Export object.  The Export object contains not only the IToDo object we imported (via the GetExportedObject method); it also allows us to retrieve metadata.  Since metadata is a set of name-value pairs, we can retrieve a value by passing the name to the Metadata collection.  In this case, we pass get the value of Metadata["Priority"].

In this article, we showed how to apply metadata to an MEF Export and how to retrieve that metadata at runtime.

Code: MEFDemo3.zip (574.93 KB)

Note: The code in this article uses MEF CTP 5.

MEF
Monday, June 15, 2009 12:10:38 PM (GMT Daylight Time, UTC+01:00)
# Saturday, June 13, 2009

In my last article, I showed how to create a Managed Extensibility Framework (MEF) contract using the [Import] and [Export] attributes.  The code in that article created a contract based on a string and imported only a string variable.  I chose that sample because it was the simplest I could think of to illustrate the concepts of a contract.  But if all you are doing is swapping strings at runtime, there are simpler ways to accomplish this than MEF.

In this article, we will create a contract based on an interface.  Interfaces describe public properties and methods of a class without providing any implementation of those properties and methods.  This gives developers the flexibility to decide later which class to instantiate.  With MEF, that flexibility is increased even more because developers do not need to set a reference to classes at compile time.

Recall that MEF uses a contract that matches Import and Export components at runtime.  Contracts are defined by Import and Export attributes.

In our sample, we create three projects:

  • MEFInterface contains the IToDo interface.
  • MEFConsoleApp1 is our console application.  It contains the Import property based on the IToDo interface.
  • MEFComponent1 is a class library containing an exported property implementing the IToDo interface.

MEFConsoleApp1 and MEFComponent1 each have a reference to MEFInterface because each contains a class that implements the IToDo interface.  However, MEFConsoleApp1 does not contain a reference to MEFComponent1, even though the console app will consume classes in the class library.  An MEF contract replaces the tight coupling of a typical application.

Creating the Contract 

To accomplish this, we do the following
1. Create the IToDo interface in the MEFInterface project.  This interface defines two properties: TaskName and HoursRequired, as shown below

    public interface IToDo
    {
        string TaskName { get; }
        double HoursRequired { get; }
    }


2. In the console application, declare a variable of type IToDo and decorate this variable with the Import attribute.  The Import attribute accepts a parameter that defines the contract.  Assign the contract type of the import attribute as TypeOf (IToDo) as shown below

        [Import(typeof(IToDo))]

public IToDo MyTask {get; set;}

3. In the MEFComponent1 project, create a class that implements IToDo.  Return a value from each property's getter and decorate this class with the Export attribute.  Assign the contract type parameter as TypeOf(IToDo).  We now have a contract because we have an import and an export with the same contract parameter.  MEF will match these up when we tall it where to compose its parts.

    [Export(typeof(IToDo))]
    public class FirstTask : IToDo
    {
        public string TaskName
        {
            get
            {
                return "Get out of bed";
            }
        }
        public double HoursRequired
        {
            get
            {
                return .10;
            }
        }
    }

4. As in the code from the last article, we must tell MEF where to find all the parts to compose.  Add the following code to the MEFConsoleApp1.

            string folderToWatch = 
System.Configuration.ConfigurationSettings.AppSettings["MEFExportFolder"];
var catalog = new DirectoryCatalog(folderToWatch); var container = new CompositionContainer(catalog); var batch = new CompositionBatch(); batch.AddPart(this); container.Compose(batch);

5. The above code gets the folder location from App.Config file, so you will need to add to the MEFConsoleApp1 project an application configration file with the following contents. (Set the directory to the location of the compiled DLL for the MEFComponent1 project).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="MEFExportFolder"
         value="C:\Development\MEF\DGCode\MEFDemo2\MEFComponent1\bin\Debug" />
  </appSettings>
</configuration>

6. Finally, add code in MEFConsoleApp1 to output values of our variable.

            Console.WriteLine
(
string.Format
(
"It takes {0} hours to do the task: {1}.",
MyTask.HoursRequired,
MyTask.TaskName
)
);

What if there are Multiple Exports matching an Import? 

In this case, MEF was able to match a single IToDo Export with a single IToDo import. But what would happen if MEF found two Exports to match just one import? 

In our example, we might add to MEFComponent1 a second exportd class that implements IToDo.

    [Export(typeof(IToDo))]
    public class ImportantTask : IToDo
    {
        public string TaskName
        {
            get
            {
                return "Make the donuts";
            }
        }
        public double HoursRequired 
        { 
            get
            {
                return .25;
            }
        }

Which Export would MEF choose to match the Import?  Both satisfy the contract.  The answer is that MEF would choose to throw an exception.  If we can't be sure of how many Exports MEF will find to match our Import contract, we should replace our IToDo declaration with an collection of IToDo objects for the Import, as shown below.

        [Import(typeof(IToDo))]
        public IEnumerable<IToDo> ToDoList { get; set; }

Then, we can loop through this collection and output all the properties:

            foreach (var td in ToDoList)
            {
                Console.WriteLine
(
string.Format
(
"It takes {0} hours to do the task: {1}.",
td.HoursRequired,
td.TaskName
)
); }

In this article, we showed how to create an MEF contract based on an interface and how to handle mutliple exports for a single import in an MEF contract.

Code: MEFDemo2.zip (574.36 KB)

Note: The code in this article uses MEF CTP 5.

MEF
Saturday, June 13, 2009 4:19:00 AM (GMT Daylight Time, UTC+01:00)
# Wednesday, June 10, 2009

Microsoft Managed Extensibility Framework (MEF) is a framework for building applications composed of parts.  By constructing an application of parts, any part can be replaced at runtime. 

In order to use this framework in your project, you will need to set reference to System.ComponentModel.Composition.dll (which you can download from http://codeplex.com/MEF) and add the following statements to the top of any module with MEF code or attributes

using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

The composition of MEF parts is very loosely coupled.  Coupling occurs using contracts.  A contract consists of an Import and one or more Exports.

An Import is a place in your application that defines a variable but does not explicitly state how that variable is implemented.  Instead, a declaration is decorated with the [Import] attribute.  A parameter of the [Import] attribute describes the implementation that the variable is seeking.  This parameter can be a string, a type or an interface.  When MEF encounters an Import, it looks for an Export that matches the Import's contract parameter.

An Export is a class decorated with the [Export] attribute. This attribute tells MEF that the class is available to satisfy any matching Import request.  Just as with the [Import] attribute, the [Export] attribute accepts a parameter that is a string, a type or an interface.

For example, the following variable declaration

        [Import("MyMEFString")]
        string SomeString { get; set; }


defines an import with a contract "MyMEFString". That contract is satisfied by the following export

        [Export("MyMEFString")]
        string ThatExportedMefString
        {
            get
            {
                return "This string was provided by an MEF contract.  It is from  an external assembly.";
            }
        }

Simply declaring this contract isn't enough.  We need to tell MEF to match up the imports and exports.  The following steps are necessary for MEF to do its thing
1. Create a catalog.  A catalog tells MEF where to find the Imports and Exports.
2. Create a container that uses the catalog.
3. Create a batch and call the Compose method of that batch.  The Compose method tells MEF to find the Imports and Exports that make up each contract and match them up.

If you want to compose parts that all exist in the currently executing assembly, this is done with the following code

 var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();
batch.AddPart(this);
container.Compose(batch);

The code above assumes that the contract's Exports and Imports are in the same project. 

Notice the first line of code, in which we declare a variable named 'catalog'.  This line instantiates a Catalog object.  A Catalog object defines where MEF looks for parts.  MEF supports the following types of Catalogs 

  • An Assembly Catalog retrieves MEF components compiled into a given assembly.
  • A Directory Catalog retrieves all MEF components in all assemblies in a given directory.
  • An Aggregating Catalog is used when you want to retrieve MEF components from multiple places - for example, from a specific assembly and from a directory; or from two different directories.

Of course it doesn't make much sense to go to the trouble of using a loosely-coupled framework like MEF and getting your parts from the current assembly. In fact, it often doesn't make sense to get parts from an assembly that is known at design time.  If we know the assembly name and location, we might as well set an explicit references to it.

A more likely scenario is to import all MEF assemblies found in a specific folder. To do this, we use a Directory Catalog.  We replace the declaration/initialization of the catalog with the following line

 string folderToWatch = @"C:\Development\MEF\DGCode\MEFDemo1\MEFComponent1\bin\Debug";
var catalog = new DirectoryCatalog(folderToWatch);

By setting our catalog to a DirectoryCatalog, we tell MEF to search for imports in all assemblies found in a well-known folder.  We can just drop DLLs into this folder and MEF will find them and use them at runtime, even if our projects do not set a reference to them.

The MEFDemo1 solution is a very simple sample that uses this code. 

In MEFDemo1, a console application declares a string variable named "SomeString" which is decorated with the Import attribute and defined by the contract "MyMEFString". 

At runtime, MEF determines the The value of SomeString by searching for the Export half of the contract.  It finds it in ThatExportedMefString variable, declared in the Class1 class of the MEFComponent1 project.  MEF knows to look here because we pointed a DirectoryCatalog at the folder where MEFComponent1.dll is compiled.  (If you copy this solution to a different directory, you will need to change the path defined in folderToWatch and recompile the MEFComponent1 project. In a real-world application, we would probably pull the folder name from a configuration file or otherwise set it at runtime to make it even more flexible.) 

The important point is that we don't need to set any references between these projects in order for them to communicate.  The contract and MEF take care of this for us.

In this article, we showed a very simple MEF contract, based on a string.  In the next article, we'll show how to create a contract based on an interface.

Code: MEFDemo1.zip (563.48 KB)

Note: The code in this article uses MEF CTP 5.

 

MEF
Wednesday, June 10, 2009 11:43:53 AM (GMT Daylight Time, UTC+01:00)
# Monday, June 1, 2009

Episode 28

In this interview, Aydin Akcasu describes how to use Microsoft .Net to write applications that interface with the remote controller for the Wii game console.

13 mins, 8 secs

Monday, June 1, 2009 12:23:57 PM (GMT Daylight Time, UTC+01:00)