MEF

IT-Jam 2010 Kharkiv

September 13, 2010 IT-Jam, MEF, Presentation, PublicTalks 4 comments

So, that have happened: I visited Kharkiv and I spoke on Managed Extensibility Framework at IT-Jam conference.

IT-Jam

So the whole conference was divided into many sections in which of them Speakers, like me, talked on different stuff. Sections were: (.NET), (Databases, Management), (Mobile, WEB), (PHP, QA) and they were located on 3rd floor (see picture below).

(Yeah! Really lot of Open Space)

Except of the regular speeches in Open Space sections, there was a huge showroom, were Guru, as they call them, were talking:

As I read from other blog posts this year it was first year, when IT-Jam had separate section for .NET and I should be proved that I took part in it.

So the agenda for .NET section:

  • Viacheslav Agafonov – Visual Studio 2010 new features,tips and tricks
  • Dmitriy Maleev – Parallel extentions in .NET 4.0
  • Andriy Buday – Managed Extensibility Framework
  • Krakovetskiy Aleksandr – Building rich data-driven applications with ASP.NET Dynamic Data
  • Andrey Kasha – Data Visualization in Silverlight
  • Sergey Lytai – Performance Silverlight application on Windows Phone 7
  • Roman Yakimovich – Web-projects competitive analysis: cheap and cheerful

My presentation

Since I was speaker I did not leave my .NET section till my delivery, so I listened to Viacheslav and Dima. Both presented very well. Dima made the whole public laughing by using jokes with mentioning Kharkiv’s governor and organizers of the IT-Jam.

My time. I plugged in proector and it turned out, that my resolution has significantly decreased. Was needed to move to “Full Screen” mode in VS and making sure that other tools I’m using fit well. My presentation was more about writing code then about showing slides and talking around them.

Here is presentation itself:

View more presentations from Andriy Buday.

In first demo I wrote ever simplest console application, you probably saw in many introduction videos on MEF.
Second demo was dedicated to demonstrate features of the MEF, like Laziness, Recomposition, Metadata. So I built simple WPF (maybe my second WPF app, after VS plugin) and plugin functionality. Each plugin was able to provide simple string. Here I mentioned one of the teachers on first courses in Lviv University. She used to write “Hellow Word!” :) on the board. So I was needed to implement new version of plugin (Metadata) and reload it (with Recomposition, for example). Guys, who studied there do you remember?

In the end I got many-many questions. It was just question-storm. Wow! I really liked it. Just presenting is very simple, but being able to answer for all questions is something where you should be additional prepared.

Parts Lifetime Question

There was one question where I answered not completely correctly. Question was: “Does CompositionContainer keep references to the parts it clued together.” I answered that yes. But correct answer is not that trivial. MEF is smart enough to keep references only to things that are shared and do not implement IDisposable. You can read in details here. I hope that guy will take a look at my blog and will get correct answer. I really worry about my reputation as public speaker.

As I counted up to 70 people were listening to me and this is the biggest audience I ever had. Hope that number of readers of my blog will increase. Cannot check it right now, since I’m now in train and out of any acceptable connection.

THANK YOU ALL!

Thanks to organizers everything was on the top of people expectations. They managed to host 1200 attendees and make everyone happy. Plus to organizing conference they prepared free food everywhere and party for the evening. They made IT-Jam awesome kick-ass cool event!

Kharkiv

Next day I had great time in Kharkiv, I will probably put link [here] to the blog post of my girlfriend very soon. Really enjoyed its monuments (except of “red star” kind), a lot of fountains, great zoo, cable way and other see-sights.


4 comments


Speaking on MEF at the IT-Jam, Kharkiv

September 9, 2010 Events, MEF, Presentation 5 comments

I’ll be speaking in Open Space Discussion at IT-Jam in Kharkiv this weekend.

So here is the road I will have to take to get there:

For some reason Ukrainian flights are way-way to expensive and therefor not acceptable by most of the people here. Even more this infrastructure is not really developed to be able to provide good services.
That is why I will have to spend 18 hours only for one way trip (>1000 km). At least I’ll have few friends with me and paper book to read.

Since it is far from Lviv and event is only for one day I’ve decided to stay there for one additional day and go out sightseeing.

Aha, almost forgot, I’ll be speaking on MEF:

After I’m back I will definitely post something about this event.


5 comments


Developing Plugins for Visual Studio 2010

September 4, 2010 MEF, VS2010 1 comment

As you all may know Microsoft committed some efforts to make VS2010 easy to extend. Extensions are built upon Managed Extensibility Framework, which has been shipped in .NET Framework 4.0. If you haven’t heard about it go and check it out on codeplex mef web page or either read my quick article on it.

Visual Studio 2010 SDK

In order to build you first extentions to VS you will need to download Visual Studio SDK
Download Visual Studio 2010 SDK

After you have installed it under New Project -> Other Project Types you will see Extensibility, which leads you to this list of project types:

Add-in Project

If you selected Add-in project it will lead you to nice wizard, which will ask you if you want to have your AddIn in Tools menu if you should like to start it on the start of VS and what are about information. After you finished with wizard you will get project structure similar to this:

What is interesting about this Add-in project?

Connect class

First of all you get Connect class with provides you with basic method within which you can push in your logic. I put MessageBox.Show(“Hello World!”); under Exec() method.

Extensibility configuration

Also you have two xml bases fixes which are describing your plugin. One of the is located inside of your folder and another one lives somewhere like: C:UsersandriyDocumentsVisual Studio 2010AddinsAndriyAddIn – For Testing.AddIn


F5

When you hit F5, accordingly to project properties, it fires devenv.exe with key /resetaddin AndriyAddIn.Connect.
/ResetAddin     Removes commands and command UI associated with the specified Add-in.

When it is re-registering AddIn it is using Extension configuration from file which lifes in Documents folder.You can go to Tools -> Add-in Manager… and turn on/off you plugin.

Here it is

For some odd reason I did not find any way to change the icon it gave for my AddIn:

Anyway it works as designed – show message box. :)


I was able to put my logo only into About section using this config:

<AboutIconLocation>D:DevelopersRoadMapRoadMap.VS2010ExtensionsMyAddin1AndriyAddInDevRoadMapToSuccess32.ico</AboutIconLocation>

Visual Studio Package Project

This time Wizard has 7 pages and it generates a huge (as for template) project:

See there MyControl.xaml? It is WPF UserControl which will be smoothly added to your Visual Studio (just like ToolBox).

To create something at least a bit useful I decided to create ever simplest RSS fetcher and use it for my blog. Being new to WPF it took a lot of my nervous to get that working. And one thought: Why did they create graphic editor for WPF. It is very hard to do something with it. XAML is way to much better choice.

So after I added some not really clear code (crappy?) like this:

            LoadRss();
            if (rssProvider.Document != null)
            {
                var entries = rssProvider.Document.GetElementsByTagName("entry");
                RssTextList.Items.Clear();
                foreach (XmlNode entry in entries)
                {
                    var displayItem = new DisplayItem(entry["title"].InnerText, entry["feedburner:origLink"].InnerText);
                    RssTextList.Items.Add(displayItem);
                }
            }

I know, I know, this doesn’t much standard rss xml, that is why my RssReader will work probably for feedburner urls. Honestly, I’m not sure about that.

Also I gave up to create binding for my ListBox as it could be preferable for WPF. I saw some ready controls for RSS reading, but hey I did it myself.

Ok. Under View -> Other Windows you will see just created Plugin window:

Finally, RSS feed of my blog inside of Visual Studio

And the whole buity of my today’s work – I can see my (or someone else post titles and by clicking navigate to web) inside of Visual Studio:

Looking forward to hear from you.


1 comment


Managed Extensibility Framework

January 27, 2010 .NET, Frameworks, MEF 4 comments

MEF is the Framework which allows you to load extensions to you application easily. It does discovery and composition of parts you need to be included in your application at run-time. You could extend your behavior simply with adding new Plugin. Managed Extensibility Framework will do everything for you.

Hello MEF World!

Assume we have really simple application and we want it to say “Hello MEF World!“:

    class Program
    {
        static void Main(string[] args)
        {
            var program = new Program();
            program.Run();
        }
        private void Run()
        {
            ProgrammGreeter.SayHello();
        }
        protected IGreeter ProgrammGreeter{ get; set;}
    }
    public interface IGreeter
    {
        void SayHello();
    }
    public class Greeter:IGreeter
    {
        public void SayHello()
        {
            Console.WriteLine(“Hello MEF World!”);
        }
    }

That is absolutely how this look and we want to make this work. The main issue is to have instance in property ProgrammGreeter to be real instance of Greeter.

Lets accomplish this with MEF

In order to do this we need to include reference to System.ComponentModel.Composition.

Accordingly to MSDN: “MEF is an integral part of the .NET Framework 4 Beta 1, and is available wherever the .NET Framework is used. You can use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server applications that use ASP.NET. In addition, there are plans to add MEF support for Silverlight applications.

Most likely MEF will be included into .NET Framework 4.0, but for now we could download it from codeplex site here.

Once we added reference we could add Import and Export attributes.
Export stands for exposing some capabilities and Import stands for dependency on some other capability.

Our Greeter provides some capabilities so we add Export there:

    [Export(typeof(IGreeter))]
    public class Greeter : IGreeter

We want to use that capability in our Programm class, we depend on that functionality. Add Import:

        [Import]
        protected IGreeter ProgrammGreeter { get; set; }

Usually our capabilities lives in other asseblies, but also they could live in called assembly. Anyway we need to say how to compose all our dependencies to MEF.
This could be done with method Compose which we be calling before we are using capabilities, usually at the start of app:

        private void Run()
        {
            Compose();
            ProgrammGreeter.SayHello();
        }
        private void Compose()
        {
            var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var compositionContainer = new CompositionContainer(assemblyCatalog);
            compositionContainer.ComposeParts(this);
        }

I ran my application and got:

How does Managed Extensibility Framework work?

I think that you are bit concerned/confused regarding that Compose method. Just read comments in code of Compose, which I made more detailed:

        //We need guide MEF how to Compose all we need
        private void Compose()
        {
            //Catalog says where to search for capabilities (Where do exports live)
            var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            //CompositionContainer holds defined dependencies and coordinates creation
            var compositionContainer = new CompositionContainer(assemblyCatalog);
            //CompositionBatch object holds references to all objects that need to be composed
            var compositionBatch = new CompositionBatch();
            //one of such objects is Programm instance (this), it needs to be composed
            compositionBatch.AddPart(this);
            //And finally Container has method called Compose to do actuall Composing
            compositionContainer.Compose(compositionBatch);
        }

In Managed Extensibility Framework there are primitives called ComposablePart which holds extensions to your application grabbed from Catalog. But also it might be that they have Imports which also needed to be composed.

Take a look on this picture from Managed Extensibility Framework wiki page.

More complex Example

In this example we will have application which parses XML file (contains information about some developer). Then when we want to deploy our application to Clients we want that XML to pass some rules, but they could differ from Client to Client. To accomplish this we put rules into separate dll and will work with it as with plugin.

We have two assemblies:

  • MEF.DEMO which declares ISecurityRule and IDataRule.
  • MEF.Rules has implementation of those interfaces.

Like on picture below. I simply don’t want to bore you with explaining of Rules logic. If you want sources just ping me.

Our Programm class wants to load rules from other assembly so we put Imports.

        [Import]
        public ISecurityRule SecurityRule { get; set; }
        [ImportMany]
        public IDataRule[] DataRules { get; set; }
        public void Run()
        {
            Console.WriteLine(“Programm run.”);
            Compose();
            Console.WriteLine(“Composition completed.”);
            var document = XDocument.Load(“developer.xml”);
            Console.WriteLine(document.ToString());
            var passesValidation = SecurityRule.PassesValidation(document);
            Console.WriteLine(string.Format(“Rule {0}: {1}”, SecurityRule.GetType(), passesValidation));
            foreach (var d in DataRules)
            {
                var valid = d.IsValid(document);
                Console.WriteLine(string.Format(“Rule {0}: {1}”, d.GetType(), valid));
            }          
        }

As you noticed we are using ImportMany, name says for itself.

We need to change our Compose method to search for Exports in Directory where execution assembly is located. For that we use DirectoryCatalog.

        private void Compose()
        {
            var catalog = new DirectoryCatalog(Environment.CurrentDirectory);
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }

Put those dlls in one folder, and run MEF.DEMO. You will get:

The goal of MEF is to seamlessly glue together classes which import services from other parts of the application, and some classes which export those services. You could say that MEF is like DI container. Yes it has a lot of it, but Managed Extensibility Framework is concentrated on composition. And that composition could be done at run time at any point of time you want that to happen. Also you could do re-composition whenever you want to do that. You could load capabilities with Lazy technical or add some metadata to your exports. Discovering of dependencies in Catalog could be done with Filtering.

Managed Extensibility Framework is great feature, that Microsoft added to .NET 4.0 Framework.


4 comments