Logo

Maarten Balliauw {blog}

ASP.NET, ASP.NET MVC, Azure, PHP, OpenXML, VSTS, ...

About the author

Maarten Balliauw is an MVP ASP.NET and is currently employed as .NET Software Engineer at RealDolmen. His interests are mainly web applications developed in ASP.NET (C#) or PHP.
More about me More about me
Send mail E-mail me


Microsoft Most Valuable Professional - MVP - ASP.NET

Subscribe to my RSS feed Follow me on Twitter! View Maarten Balliauw's profile on LinkedIn RealDolmen - Rock-solid passion for ICT
I'm a speaker at TechDays Belgium and TechDays Finland

Search

Latest Twitter

    Follow me on Twitter...

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

    © Copyright Maarten Balliauw 2010

    MEF will not get easier, it’s cool as ICE

    Over the past few weeks, several people asked me to show them how to use MEF (Managed Extensibility Framework), some of them seemed to have some difficulties with the concept of MEF. I tried explaining that it will not get easier than it is currently, hence the title of this blog post. MEF is based on 3 keywords: export, import, compose. Since these 3 words all start with a letter that can be combined to a word, and MEF is cool, here’s a hint on how to remember it: MEF is cool as ICE!

    kick it on DotNetKicks.com

    Imagine the following:

    You want to construct a shed somewhere in your back yard. There’s tools to accomplish that, such as a hammer and a saw. There’s also material, such as nails and wooden boards.

    Let’s go for this! Here’s a piece of code to build the shed:

    public class Maarten
    {
        public void Execute(string command)
        {
            if (command == “build-a-shed”)
            {
              List<ITool> tools = new List<ITool>
              {
                new Hammer(),
                new Saw()
              };

              List<IMaterial> material = new List<IMaterial>
              {
                new BoxOfNails(),
                new WoodenBoards()
              };

              BuildAShedCommand task = new BuildAShedCommand(tools, material);
              task.Execute();
            }
        }
    }

    That’s a lot of work, building a shed! Imagine you had someone to do the above for you, someone who gathers your tools spread around somewhere in the house, goes to the DIY-store and gets a box of nails, … This is where MEF comes in to place.

    Compose

    Let’s start with the last component of the MEF paradigm: composition. Let’s not look for tools in the garage (and the attic), let’s not go to the DIY store, let’s “outsource” this task to someone cheap: MEF. Cheap because it will be in .NET 4.0, not because it’s, well, “cheap”. Here’s how the outsourcing would be done:

    public class Maarten
    {
        public void Execute(string command)
        {
            if (command == “build-a-shed”)
            {
              // Tell MEF to look for stuff in my house, maybe I still have nails and wooden boards as well
              AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
              CompositionContainer container = new CompositionContainer(catalog);

              // Start the job, and ask MEF to find my tools and material
              BuildAShedCommand task = new BuildAShedCommand();
              container.ComposeParts(task);
              task.Execute();
            }
        }
    }

    Cleaner, no? The only thing I have to do is start the job, which is more fun when my tools and material are in reach. The ComposeParts() call figures out where my tools and material are. However, MEF's stable composition promise will only do that if it can find ("satisfy") all required imports. And MEF will not know all of this automatically. Tools and material should be labeled. And that’s where the next word comes in play: export.

    Export

    Export, or the ExportAttribute to be precise, is a marker for MEF to tell that you want to export the type or property on which the attribute is placed. Really think of it like a label. Let’s label our hammer:

    [Export(typeof(ITool))]
    public class Hammer : ITool
    {
      // ...
    }

    The same should be done for the saw, the box of nails and the wooden boards. Remember to put a different label color on the tools and the material, otherwise MEF will think that sawing should be done with a box of nails.

    Import

    Of course, MEF can go ahead and gather tools and material, but it will not know what to do with it unless you give it a hint. And that’s where the ImportAttribute (and the ImportManyAttribute) come in handy. I will have to tell MEF that the tools go on one stack, the material goes on another one. Here’s how:

    public class BuildAShedCommand : ICommand
    {
      [ImportMany(typeof(ITool))]
      public IEnumerable<ITool> Tools { get; set; }

      [ImportMany(typeof(IMaterial))]
      public IEnumerable<IMaterial> Materials { get; set; }

      // ...
    }

    Conclusion

    Easy, no? Of course, MEF can do a lot more than this. For instance, you can specify that a certain import is only valid for exports of a specific type and specific metadata: I can have a small and a large hammer, both ITool. For building a shed, I will require the large hammer though.

    Another cool feature is creating your own export provider (example at TheCodeJunkie.com). And if ICE does not make sense, try the Zoo example.

    kick it on DotNetKicks.com


    Microsoft PDC09 keynote highlights

    Finally found some time to write a short blog post on the announcements this morning at PDC 2009.Microsoft PDC keynote highlights Ray Ozzie started the keynote this morning, focusing on Microsoft’s “three-screen” vision for the future. There will be three screens connected to the cloud: TV, (handheld) devices and of course good old PC. This vision is driven by some key players: Windows 7, Internet Explorer, Silverlight and Windows Azure. Make sure to have a look at these four if you want to play in this future.

    Some announcements were made as well:

    Had a great day yesterday, driving trough the city of Los Angeles and looking at various places in town. Conference day one was also very interesting, lots of good sessions. Currently missing a session slot though, waiting for a Channel9 interview on the Windows Azure SDK for PHP. Stay tuned!


    ASP.NET MVC TDD using Visual Studio 2010

    Phil Haack announced yesterday that the tooling support for ASP.NET MVC is available for Visual Studio 2010. Troy Goode already blogged about the designer snippets (which are really really cool, just like other parts of the roadmap for ASP.NET MVC 2.0). I’ll give the new TDD workflow introduced in VS2010 a take.

    kick it on DotNetKicks.com

    Creating a new controller, the TDD way

    First of all, I’ll create a new ASP.NET MVC application in VS2010. After installing the project template (and the designer snippets if you are cool), this is easy in VS2010:

    Step 1

    Proceed and make sure to create a unit test project as well.

    Next, in your unit test project, add a new unit test class and name it DemoControllerTests.cs.

    Step 2Go ahead and start typing the following test:

    Step 3Now when you type CTRL-. (or right click the DemoController unknown class), you can pick “Generate other…”:

    Step 4A new window will appear,  where you can select the project where you want the new DemoController class to be created. Make sure to enter the MvcApplication project here (and not your test project).

    Step 5

    Great, that class has been generated. But how about the constructor accepting List<string>? Press CTRL-. and proceed with the suggested action.

    Step 6

    Continue typing your test and let VS2010 also implement the Index() action method.

    Step 7You can now finish the test code:

    Step 8The cool thing is: we did not have to go out of our DemoControllerTests.cs editor while writing this test class, while VS2010 took care of stubbing my DemoController in the background:Step 9Run your tests and see it fail. That’s the TDD approach: first make it fail, and then implement what’s needed:

    Step 10

    If you run your tests  now, you’ll see the test pass.

    Conclusion

    I like this new TDD approach and ASP.NET MVC! It’s not ReSharper yet, but I think its a fine step that the Visual Studio team has taken.

    kick it on DotNetKicks.com


    Categories: ASP.NET | C# | CodePlex | General | ICT | Internet | MVC | VSTS | VS2010