Showing posts with label VS.NET 2010. Show all posts
Showing posts with label VS.NET 2010. Show all posts

Friday, February 6, 2009

MEF – The new extensibility standard

Preface
One of the most impressive technologies knocked out by Microsoft was Windows Communication Foundation. WCF unified various communication capabilities that exists in .NET 2.0 into a single, common, general framework. I think that it is the great achievement!
Recently I found Visual Studio 2010 training kit which includes the set of the hand-on-labs. One of the labs is called "Introduction To Managed Extensibility Framework". I read the instructions and it made me excited. Managed Extensibility Framework unifies the application extensibility capabilities! Actually .NET doesn't provide any "standard" API's for the applications extensibility. There is the plug-in model which should be implemented from scratch by every application that wants to support it. WPF provides the ways for look-and-feel extensibility by using styles, templates, skins and themes. But until now there was no the technology that unifies the extensibility like WCF unifies the communication. Managed Extensibility Framework is unifier guy for the extensibility. In this post I will try to describe my experience with MEF and provide the real-world code sample.

MEF architecture
The MEF architecture is shown here. It is very simple and the extensibility implementation can be described in the following steps:
  • The application provides the set of extensibility points using MEF API.
  • The application hosts the extensibility parts container using MEF API.
  • The plug-in provides the set of extensibility parts using MEF API.
  • The application imports the extensibility parts using MEF API.
The API is pretty straightforward and it's very easy to implement the extensibility support in your application using MEF.

The real-world sample.
Recently I was thinking about providing one more extensibility facilities for Data Dynamics Reports. Briefly - it should provide the capability to use the custom UI editors of some entities. For the real-world sample I selected the similar task:
WPF application provides the editor of the color of something. For example the application for facial composite construction uses the editor for eyes color. The application should provide the built-in color editor and end-user should be able to specify the custom color editor.
For example : the application provides built-in color editor that allows editing of the Red, Green and Blue color components. End-user can select the custom color editor that allows editing the Hue, Saturation and Brightness color components. The application should provide the visual feedback whenever the selected color is changed.


Implementation of the built-in color editor.
So, the built-in color editor allows editing of the Red, Green and Blue color components. WPF doesn't provide the standard color editor and we need to implement it. The implementation of the RGB color editor is straightforward task. We should:
  • Define the dependency properties for the Red, Green and Blue components.
  • Define the dependency property for the currently selected color.
  • Provide the way which can be used by the hosting application to intercept the event when the selected color is changed.
The last thingie is a bit of pain. There is the beautiful article that describes this pain and offers the various solutions for intercepting the event of changing the dependency property value. I will use the simple event(i.e. not routed event) to allow intercepting the selected color changing. Since all that application should know about the color editor is how to intercept the color changing event, I will define the new interface that provides this event and implement this interface in the built-in color editor. There are several alternate ways to design this system, but for it doesn't matter for the topic I discuss. The basic code that defines the color editor control, the dependency property for Red component, the dependency property for the currently selected color and another needed stuff is shown below.

interface IColorChanged
{
   event ColorChangedEventHandler ColorChanged;
}

delegate void ColorChangedEventHandler(object sender, ColorChangedEventArgs args);

class ColorChangedEventArgs : EventArgs
{
   public Color OldValue{ get; set;}
   public Color NewValue{ get; set;}
}

class RGBColorEditor : Control, IColorChanged
{
   private Color _color = Colors.Black;
   public event ColorChangedEventHandler ColorChanged;

   public ColorEditor()
   {
      SetValue(RProperty, _color.R);
      SetValue(SelectedColorProperty, _color);
   }

   public static readonly DependencyProperty RProperty =
   DependencyProperty.Register("R", typeof (byte), typeof (RGBColorEditor),
   new PropertyMetadata((byte)255, OnRChanged));

   public static readonly DependencyProperty SelectedColorProperty =
   DependencyProperty.Register("SelectedColor", typeof(Color), typeof(RGBColorEditor), new    PropertyMetadata(Colors.Black, OnSelectedColorChanged));

   public byte R
   {
      set { SetValue(RProperty, value); }
      get { return (byte)GetValue(RProperty); }
   }

   private void OnRChanged(byte newValue)
   {
      _color.R = newValue;
      SetValue(SelectedColorProperty, _color);
   }

   private static void OnRChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   {
      (d as ColorEditor).OnRChanged((byte)e.NewValue);
   }

   private void OnSelectedColorChanged(DependencyPropertyChangedEventArgs e)
   {
      if (ColorChanged != null)
         ColorChanged(this, new ColorChangedEventArgs { NewValue = (Color)e.NewValue, OldValue =       (Color)e.OldValue });
   }

   private static void OnSelectedColorChanged(DependencyObject d,       DependencyPropertyChangedEventArgs e)
   {
      (d as ColorEditor).OnSelectedColorChanged(e);
   }
}

The rest of the code defines the dependency properties for the green and blue components of the color and also provides the default control template. RGBColorEditor is contained in the main application assembly.


Custom color editor sample.
So, our custom editor control will allow editing of the Hue, Saturation and Brightness color components. The implementation would be very similar to RGBColorEditor. We implement IColorChanged interface, define the dependency properties for Hue, Saturation, Brightness and SelectedColor properties. Here is the snippet of the code:

class HSBColorEditor : Control, IColorChanged
{
   private static Color ConvertHsbToRgb(double h, double s, double b)
   {
      //return new color created from h,s,b values;
   }
   public static readonly DependencyProperty RProperty =
   DependencyProperty.Register("H", typeof(double), typeof(HSBColorEditor),
   new PropertyMetadata(0, OnHChanged));

   void OnHChanged(double newValue)
   {
      Color newColor = ConvertHsbToRgb(newValue, S, B);
      SetValue(SelectedColorProperty, newColor);
   }

   private static void OnHChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   {
      (d as HSBColorEditor).OnHChanged((double)e.NewValue);
   }
}

HSBColorEditor class is contained in the separate assembly. Let's say its name is FacialCompositeCustomControls.


Extensibility without MEF.
I think that the most suitable way to provide the extensibility facility without MEF is using Provider Model Design Pattern. The application configuration file would have the list of the available color editors, the application would provide end-user with UI that shows this list and allows selecting the appropriate editor. Then the application would create the selected control instance and add it to the corresponding place.

MEF world.
For our application purpose we will use the color editor selector dialog which is responsible for collecting the custom color editor implementations and allowing end-user to select the appropriate editor. The color editor selector will try collecting the color editors from the assemblies located in the Plugin folder of the the directory of the executing application. Also, the built-in color editor should be added in the collection. So, the first thing that we should do if defining the extensibility points in the color editor selector. MEF allows to do that by using different ways, but the key is System.ComponentModel.Composition.ImportAttribute. Look at the code:

class ColorEditorSelector : Window
{
   [Import(typeof(IColorChanged))]
   private ExportCollection<Control> EditorCollection { get; set; }
   public Control SelectedEditor { get; set; }
}

We defined the extensibility point using ImportAttribute and set the contract for the plug-in - it should implement IColorChanged interface. The color editor collection will be stored in the property of type System.ComponentModel.Composition.ExportCollection<Control>. SelectedEditor property is used by the application to get the color editor selected by user. Then we need to add the code which looks for the available color editors in the executing assembly and Plugin folder. The code is shown below. In the MEF terms we will add the composition container which loads the compositions parts from the executing assembly and from Plugins folder.

private void Compose()
{
   var catalog = new AggregateCatalog();
   var catalog1 = new AssemblyCatalog(typeof(ColorEditorSelector).Assembly);
   catalog.Catalogs.Add(catalog1);
   var catalog2 = new DirectoryCatalog("Plugins", true);
   catalog.Catalogs.Add(catalog2);
   var container = new CompositionContainer(catalog);
   var batch = new CompositionBatch();
   batch.AddPart(this);
   container.Compose(batch);
}

This code is like design pattern for the composition. It defines several places from which the extensible parts can be loaded, adds them to the container and performs the composition. The composition batch is used for the dynamic re-composition. I.e. if one copies the new assembly contains the custom color editor in Plugins folder, then it is handled dynamically without re-run the application. Compose method is called from ColorEditorSelector constructor. Here is the code that runs the composition and fills the listbox by the type names of the available color editors:

public ColorEditorSelector()
{
   Compose();
   var list = new ListBox();
   foreach(var colorEditor in EditorCollection)
   {
      var control = colorEditor.GetExportedObject();
      list.Items.Add(control.GetType().Name);
   }
}

The last thing that we should do is add the extensibility points definition in the color editor implementations. It is done by using System.ComponentModel.Composition.ExportAttribute:

[Export(typeof(IColorChanged))]
internal sealed class RGBColorEditor : Control, IColorChanged

[Export(typeof(IColorChanged))]
internal sealed class HSBColorEditor : Control, IColorChanged

And that's all about the extensibility. The rest of ColorEditorSelector dialog composes the UI which allows to select the appropriate color editor and sets SelectedEditor accordingly. The application uses the SelectedEditor to add it to UI. Looks very straightforward and great, isn't it?


In conclusion.
MEF is included in .NET Framework 4.0 CTP and I think it is really new standard for the application extensibility. Microsoft did the great job in design and implementation of MEF library and I will definitely will use it!

Saturday, January 24, 2009

C# 4.0 - the first look at the DYNAMICITY.

This week I looked at C# dynamic features that were added in C# 4.0 CTP and Visual Studio 2010. Tremendous amount of resources have appeared on dynamic features of C# over the web. C# developers provided the description of dynamic features on their blogs, i.e. Sam Ng’s blog and Chris Borrows’ blog have the great posts about the topic. However, not all the dynamic features are available in C# 4.0 2008 CTP. I.e. a lot of samples listed in the mentioned blogs don’t event compile in the current VS.NET 2010 preview. So I didn’t dive in the specific language constructions and tricks. What makes me excited is step forward to “dynamicity” in .NET. I never worked with dynamic languages before but apparently it’s about time to learn more about the dynamic languages facilities. Well, I found MSDN magazine article called CLR Inside out: IronPython and read the beautiful thing:

The most common question I hear about dynamic languages is "why should I use them?" Trying to show a longtime C++ or C# developer that a dynamic language is useful for problems outside the scripting domain is difficult. One concrete benefit of dynamic languages is that they facilitate an iterative development cycle. The interactive capabilities of dynamic languages make them a better match for this type of cycle than compiled languages. Developers can focus on exploring and prototyping functionality, refactoring if necessary, and then repeating with new functionality. This allows for a more exploratory process of development than the code/build/run/debug loop that most other languages constrain the programmer to.

So, the dynamic language, well C# 4.0, will allow transition from code/build/run/debug loop to evaluation/print loop? Yes, in PDC 2008 “Future of C#” talk Anders Hejlsberg shows it in action and it looks amazing. The new language features like dynamic type, IDynamicLanguage interface, optional and named parameters also look very promising. Next week I will try to work with C# 4.0 as with dynamic language, I think the best way to do this is get some problem, solve it using C# 3.0(statically typed language), then solve it using C#4.0(dynamic language). I will write about any interesting stuff.

Thursday, December 4, 2008

VS.NET 2010 - the illusion of the built-in TDD support.

TDD means Test Driven Development. Every person involved in the software development used it or at least heard about that. VS.NET 2010 "what's new" documentation has the "TDD support" item in the list of the new features. What would it mean? How did they make the support of software development philosophy in IDE? I tried to figure it out and was totally disappointed...
Well, there is the new Project Template in VS.NET 2010. It is called "Test Project" and it's description is "The project that contains the test":) In reality this is the Class Library Project that has the reference to the new MS assembly that contains classic "TestFixture", "Test" attributes, assertion methods and so on. Also, the newly created project contains the class with the test methods and text file with the brief description of TDD concept.
So, once you start the development keeping TDD in mind you should start with writing the new test. The test typically consists of creating the new instance of some type, invoking this type methods and compare the real results of something with the expected result. You write the code that creates the new instance of non-existing type. Visual Studio IDE reports about the error. You click on the smart tag near the code that creates the instance of the non-existing type and IDE creates the new type for you. Then you can run the tests, see if they fail, fix the code, run the tests again and so on.
So, what actually MS did for "TDD support"?
  • They created VS.NET add-in that allows to automatically create the new classes, methods, properties, indexers and so on by clicking on the smart tags near the piece of the code. Frankly, it can be done for a couple of days by every programmer who intimate with VS add-in development.
  • They created the new assembly that actually copies NUnut.Framework assembly. Yeah, I bet no one will want to re-write tons of unit tests created using NUnit or MBUnit using this new library.
  • They added the tools that allow to run the unit tests that created using the MS unit tests library.(Resharper has the tools that allow to run NUnit tests from IDE:))
  • They added the new Project Template which is actually not new.
  • They called all these stuff "built-in TDD support".
And I am ready to hear the words like "TDD makes your business flow easier and VS.NET 2010 has the TDD support!" in MS sessions.
So, what is conclusion? The conclusion is - MS developed the pretty simple and useless feature, packed it to the nice wrappers and called it "TDD support!"
Everyone knows what would be result if pack the useless feature to the nice wrappers.


Sunday, November 30, 2008

VS.NET 2010 - Call Hierarchy

Every day I use the splendid VS.NET add-in called ReSharper in the development routine. This tool greatly reduces the amount of efforts that are needed to find the syntax errors in the code, refactor the code, search various entities of the code, etc. etc. I don't realize how I can code without using ReSharper.
One of the pretty useful features of R# is "Find usages..." functionality. Right click on the method, property, constructor, type, etc., then select "Find Usages" or "Find Usages Advanced..." and R# shows you the points of code where the selected entity is used. You can find the derived classes of some base type or the implementations of some interface, etc. etc. This is really great feature and it has a lot of options...Now I realize that this feature and R# doesn't provide another brilliant option...
So, sometimes I need to analyze
the convoluted and very complex code to figure out how it works to find the possible flaws or realize the possible solution for the newly required features. Say I am interested in some method("A" method), I want to figure out it's place in the the flow of code execution. If I don't want to debug the code I usually use Find Usages feature if R#. I find the usages of the method A. Let's say method A is called by methods B and C. This fact isn't very informative. Then I need to find the usages of the methods B and C, etc. etc. Then I need to realize the entire picture of the place of method A in the flow of the code execution based on the list of usages of the related methods and believe me, this is not pretty straightforward in the complex code(or I am just retard:))
Anyway, VS.NET 2010 introduced the new feature called Call Hierarchy and this is exactly what I needed for more productive and quick code analysis in the complex projects! Right-click on the method, property, constructor or indexer then select "View call hierarchy" and Visual Studio shows you the entire picture of the selected entity place in the flow of the code execution. It shows the calls to "method A" that I referred to in the previous paragraph and calls from "method A". For every calling or called method VS shows it's invokers and invoked methods. You can navigate to calling or called methods and change the scope of call hierarchy analysis! Here is the screen shot of the call hierarchy of the piece of the code of one of my projects:


I am impressed by this new feature and undoubtedly I will use it every day once the standalone version of VS.NET 2010(outside of virtual machine) is released :)

Thursday, November 27, 2008

VS.NET 2010 - the first look

Well,
As I supposed the guest operation system in virtual machine that hosts VS.NET 2010 is Windows Server 2008! It has VS.NET 2008, VS.NET 2010, SQL Server 2008, Office 2008, etc. installed.
It's now clear why you need 75 GB on hard drive to get this heavy virtual PC image :)
The first thing I looked for is documentation for VS.NET 2010. It would allow me looking at new features in VS IDE, C#, etc..and..there is no MSDN available! The only available documentation is the set of walkthroughs that briefly describe the new features. Okay, I briefly read this document..
The first feature that I liked and tried immediately is customizing the VS.NET 2010 Start Page. Start page for now can be any content that is built using WPF. It has no limits - you can add RSS feed, animation, flow documents, etc. in the Start Page. You can bind the VS commands to the elements of start page, i.e. execute any main menu item commands.
The steps that needed for customization are pretty straightforward - create XAML document that contains the start page content, copy it to the certain folder and voila!
Well, I tried that and now my Start Page looks like below


That's all for this brief post:)