Sunday, February 15, 2009

Fun with error messages

Recently I posted some thoughts about error messages construction. Today I found the nice example which shows how the error message should not be constructed. This year we started to use Surround SCM for the source code of our products. Today I get the following error when tried to check the sources out:

"Surround SCM encountered an error. Communication error." The phrase seems very familiar to me..Yeah! "My Name is Bond - James Bond". There is no any other sense with such an error message except of it looks very funny. When you report about the error, don't make people laugh, tell them as much helpful information as possible.

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!

Friday, January 30, 2009

Conceptual blocks and programming tasks. Part II.

Preface
In the previous post I offered the following problem to solve:
The input data is the graph representation, for example the instance of LinkedList class. The output is Boolean value which is true if the graph has the cycle and false otherwise. The constraints are no additional memory should be used.
Let me publish the solution and the comments.
   

The solution.
To show the solution, I would like to use C# language. I realized that LinkedList<T> class which I referred in the puzzle definition can't represent the graph that has cycles because the methods of this class don't allow to set the next and previous node to the node which already belongs the list. So, the following class is used to show the solution.

internal class GraphNode<T>
{
   private T _value;
   private GraphNode<T> _next;
   public GraphNode(T value)
   {
      _value = value;
   }
   public GraphNode<T> Next
   {
      get{ return _next;}
      set{ _next = value;}
   }
   public override string ToString()
   {
      return _value.ToString();
   }
}

And here is the solution:

static bool HasCycle<T>(List<GraphNode<T>> list)
{
   if (list == null)
      throw new ArgumentNullException("list");
   if (list.Count == 0)
      throw new ArgumentException("empty list", "list");
   GraphNode<T> current1 = list[0];
   GraphNode<T> current2 = list[0];
   do
   {
      if (current1.Next == null || current2.Next == null || current2.Next.Next == null)
      {
         return false;
      }
      current1 = current1.Next;
      current2 = current2.Next.Next;
      if (ReferenceEquals(current1, current2))
      {
         return true;
      }
   } while (current1 != null && current2 != null);
   return false;
}


The Analysis.
The idea behind the scene is very simple. The solution is using two pointers to the graph nodes, the first pointer goes through the graph with step 1(current1=current.Next) and the second pointer goes through the graph with step 2(current2=current.Next.Next). If the graph has the cycle, these two pointers will refer to the same node at some point which is obvious.However, I seen a lot of situations when people were not able to solve this puzzle quickly or didn't solve it at all.When I was asked to solve this puzzle several years ago I didn't solve it as well. And the reason of that is the conceptual blocks.
When I studied at the university, we learned the common algorithms and implemented them quite intensively. A lot of the algorithms dealt with the graphs - visiting the graph nodes, finding the shortest way between two graph nodes, etc. I used to use single pointer to the graph nodes for these algorithms. After more than 5 years this habit still persisted. This is some sort of the stereotype which is definitely the conceptual block. The second block is the same as I shown in the previous post - the tendency to delimit the problem area poorly. Sometimes people restrict themselves to using the single pointer. If one would know about the conceptual blocks and control the process of the problem solving, the "finding the cycle in the graph" become the pretty trivial task.

Monday, January 26, 2009

Conceptual blocks and programming tasks.

Preface
One of my favorite nonfictional books is “Conceptual Blockbusting” by James L. Adams. The book describes the conceptual blocks which are “mental walls that blocks the problem solver from correctly perceiving a problem or conceiving its solution”. There is the set of puzzles that intended to understand how the conceptual blocks can hamper the problem solving. I believe that reading this book can really help you to become a better thinker. Indeed it’s helpful if you aren’t a genius like Albert Einstein. Every time I read this book I try to figure out how the conceptual blocks can hamper the solving of the problems that I face doing my job every day. And recently I found the interesting issue…

Delimiting the problem area poorly.
One of the perceiving conceptual blocks is tendency to delimit the problem too closely. It is demonstrated using the following puzzle:
Draw no more than four straight lines without lifting the pencil from the paper which will cross through all nine dots:
Work on it a while. One possible solution is shown here
A lot of people don’t exceed the imaginary boundary even though it is not in the definition of the problem at all. The overly strict limits are a block in the mind of the solver.

Find cycle in the graph puzzle
Consider the following puzzle.
The input data is the graph representation, for example the instance of LinkedList class. The output is Boolean value which is true if the graph has the cycle and false otherwise. The constraints are no additional memory should be used.
Try to solve this puzzle. In the next post I will explain the issues that hamper this puzzle solving and why they appear.

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.

Tuesday, January 13, 2009

The Error Message - the fresh glance.

Preface
December 2008 issue of MSDN magazine introduces the new column called Usability in Practice. January 2009 issue includes the first Usability in Practice article from which I learned something new.
The article itself isn't very worth. Almost entire content of the article is brief description of Error Message guidelines part of Windows Vista Users Experience Guidelines. Error message guideline has the great, comprehensive and straightforward directions of how the application error messages should be constructed. Actually the guideline has two logical parts - what information should be presented by the error message and how the error message should look like. The first part is quite clear and just tells us which points and questions we should consider for good error messages constructing. The second part - how the error message dialog should look like - is the thing which this post about.


Task Dialog
Windows Vista introduces a new standard dialog box called task dialog. According to the error messages guideline the task dialogs should be used to show the error message if the error can't be fixed immediately, if the error isn't contextual user input problem and if the error isn't delayed detected problem. I.e. When Things Go Wrong article demonstrates how the simple error message can be presented by the task dialog. Here is the table that shows the correspondence between the task dialog areas and the simple error message parts.
Task dialog areaError message part
Title barA problem. States that a problem occurred.
Main instructionA cause. Explains why the problem occurred.
Content areaA solution. Provides a solution so that users can fix the problem.
Command areaCommit button(Close).


Using task dialog in .NET application.
The managed code can create and show the task dialog using the corresponding API. The example of wrapping task dialog API in the managed code can be found in CodeProject.
But the task dialog API is supported only by Vista. What about earlier versions of Windows? Which dialog we should use for show the error message if the application is run in Windows XP? What about using MessageBox class? Unfortunately, MessageBox dialog doesn't allow distinguish between the main instruction area and the content area which I referred above. However, I think we definitely should follow the error message guideline and at least simulate the task dialog for non-Vista(and non-Windows 7) OS. At least for the simple error message we should show the dialog which has the parts described above. Here is the very basic sample of error message dialog that can be used in Windows XP:

The sample of task dialog emulator can be found in CodeProject as well. However, if I need to show the simple error messages only, I would implement the simple task dialog emulator like one that is shown in the picture above.


Postscriptum.
I will definitely follow the error message guideline in the future and revise the existing error messages in the product I actively work on.

Monday, January 12, 2009

My first experience with Windows 7

Recently Microsoft has knocked out Windows 7 beta and published the build for testing purposes. I was not excited about the new version of Windows at all. I remember the experience with the first beta release of Windows Vista - I installed it and then stopped using in 2 or 3 days. The main reasons were - I was not able to install drivers for the sound card, the new interface seemed terrible for me, Windows Vista seemed working slowly than Windows XP and so on. As far as I know, in our days Windows XP is still being chosen over Windows Vista for the majority of business computer sales, so I am sure that I am not only person who stopped using Vista once looked at the first beta release. However, for now I had the new motivation to install Windows 7 - I wanted to see whether the product I work on - Data Dynamics Reports - can be used on Windows 7. This is what I really excited about. In this post I briefly describe the Windows 7 installation experience and the point where I decided to stop using it - yep, again!

The Installation
The installation of Windows 7 is pretty intuitive and requires very few actions from end-user. The thing I loved is my motherboard integrated devices were detected and installed properly. I thought that it would be a problem because the motherboard drivers for Windows XP and Vista are not compatible with the new OS. However, this fact didn't become the problem at all. The only problem with the installation I faced is "applying personal settings hang" during the first run. However, this problem isn't specific for Windows 7 and I managed it by rebooting the machine several times, starting windows 7 in safe mode and then starting it normally. Sounds crazy, but it works:)

The first run.
During the first run I faced the problem with WinMail service. It used 100% CPU during the first run. I managed it by running Windows 7 in safe mode and erasing WinMail.exe file. Sounds crazy but it works.

The end.
Well, I successfully installed and run Windows 7 and I thought that I probably was wrong and Microsoft did the great job this time and probably I can use Windows 7 as the primary OS. The new OS interface looks great and it is very convenient. Various software is being installed just fine. The idyll finished when I tried to install Visual Studio .NET 2008. I was not able to install it. The setup is run, the first window with choices to install VS.NET, install MSDN and check for the new releases appeared. I selected install VS.NET and nothing happened. The main window closed, no new processes were run. I tried to run VS.NET 2008 setup with administrator privileges, this doesn't help. I tried setting the compatibility mode for setup.exe and this doesn't help as well. Visual Studio .NET 2005 can't be installed as well with the same symptoms. This looks as weird fact for me - Microsoft software can't be installed on Microsoft OS. And indeed I don't want using OS that doesn't allow installing Visual Studio. This is how my experience with Windows 7 has finished...

PS. If someone reads this blog and uses Windows 7 beta and was able to install VS.NET 2005(2008) please tell me the secret of the success.