Monday 28 July 2008

Microsoft Sponsors Open Source Apache

Given that Microsoft have invested lots of time and money in their own web server (IIS), this is a true endorsement of changes afoot at Microsoft http://news.bbc.co.uk/1/hi/technology/7528857.stm

I personally think this makes complete sense for them. I truly believe as we move to a more service delivered software models, the value of source code (or software IP) becomes less important, as licence revenue becomes less of a percentage of total revenue for the big boys such as MS.

For companies like Microsoft, interoperability is very important and its relevance is definitely growing. For example, I am sure that to allow users to be able to transfer services currently running on a LAMP architecture to run on Microsoft's own hosted Windows "cloud" architecture is going to be important for them in future (even if it's not running on a .NET platform). Here is some more detailed info

Interestingly enough, their competitor Apple seems to be going in the other direction with their iPhone SDK, for which the licence agreement apparently does not allow people to build open source software... hmm!

Wednesday 23 July 2008

Is INotifyPropertyChanged an anti-pattern?

Something is starting to bother me recently about data binding and the INotifyPropertyChanged interface. It's just that EVERY class you write ends up having to implement it (I am generally talking about writing WPF/Silverlight applications here). And that's just not sitting well with me!

It doesn't sit well because I believe it violates the principles of separations of concern. The major annoyance for me lies with calculated properties (those which are derived from another). Lets start with a simple class, Order, which contains two properties, ItemPrice and Quantity (other fields and methods omitted for sake of brevity):

public class Order : INotifyPropertyChanged
{
  public decimal ItemPrice 
  { 
    get { return this.itemPrice; }
    set 
    {
       this.itemPrice = value;
       this.RaisePropertyChanged("ItemPrice");
    }
  }

  public int Quantity 
  { 
    get { return this.quantity; }
    set 
    {
       this.quantity= value;
       this.RaisePropertyChanged("Quantity");
    }
  }
}

We need to add a property TotalPrice to this entity which will expose the total price of the order. What do we do here? This is a calculated value so should clearly be read only, and I usually implement the calculation within the property itself. What I have found myself doing many times in the past (and I have seen done in a lot of examples) is:

public class Order : INotifyPropertyChanged
{
  public decimal ItemPrice 
  { 
    get { return this.itemPrice; }
    set 
    {
       this.itemPrice = value;
       this.RaisePropertyChanged("ItemPrice");
       this.RaisePropertyChanged("TotalPrice");
    }
  }

  public int Quantity 
  { 
    get { return this.quantity; }
    set 
    {
       this.quantity= value;
       this.RaisePropertyChanged("Quantity");
       this.RaisePropertyChanged("TotalPrice");
    }
  }

  public decimal TotalPrice
  {
    get { return this.ItemPrice * this.Quantity; }    
  }
}

This is nasty. We have had to modify our other two properties just because we have added this new one. It works, but as you add more and more dependent properties your code gets messy. Those properties shouldn't need to know that the TotalPrice property exists!

That pattern breaks down completely when you start using inheritance in your domain objects. Imagine if I now require a new type of domain object, SalesOrder, where I want to express the fact that there is a commission (expressed as a fraction) which needs to be paid to some salesperson on this order:

public class SalesOrder : Order
{
  public decimal SalesCommision
  { 
    get { return this.salesCommision}
    set 
    {
       this.salesCommisionPercentage = value;
       this.RaisePropertyChanged("SalesCommision");
       this.RaisePropertyChanged("TotalCommission");
    }
  }

  public decimal TotalCommission
  { 
    get { return this.TotalPrice * this.SalesCommission; }
  }
}

Uh-oh! It's come a bit unstuck here. If the price changes in the base class, my UI is not going to redisplay the total commission! This could be great for my sales person but not so great for my accountant!

So what do we do here to get around this? We clearly can't modify our base class, so how about we listen to our own property notifications, like thus:

public class SalesOrder : Order
{
  // Properties defined as previously //

  protected override void RaisePropertyChanged(string propertyName)
  {
     base.RaisePropertyChanged(propertyName);
     if (propertyName == "TotalPrice")
     {
        this.RaisePropertyChanged("TotalCommission");
     }
  }
}

Here we override the method which raises the event, check if the relevant dependent property is being raised, and if so we raise a changed event on our commission property. This works, but YUCK! Just imagine having to unit test all this! :-(

Note that we end up with the same problem if we use composition. Imagine that instead of storing the sales commission on our entity, it was actually stored on a related SalesPerson entity and we need to calculate it from there. Now we need to know that if the sales person's commission changes, the order's total commission has changed:

public class SalesOrder : Order
{
  public SalesPerson SalesPerson
  { 
    get { return this.salesPerson; }
    set 
    {
       if (this.salesPerson != null)
       {
          this.salesPerson.PropertyChanged -= HandleSalesPersonPropertyChanged;
       }

       this.salesPerson = value;
       this.RaisePropertyChanged("SalesPerson");
       this.RaisePropertyChanged("TotalCommission");

       this.salesPerson.PropertyChanged += HandleSalesPersonPropertyChanged;
    }
  }

  public decimal TotalCommission
  { 
    get { return this.TotalPrice * this.SalesPerson.Commission; }
  }

  protected virtual void HandleSalesPersonPropertyChanged(object sender, PropertyChangedEventArgs e)
  {
     if (e.PropertyName == "Commission")
     {
        this.RaisePropertyChanged("TotalCommission");
     }
  }
}

We subscribe to the PropertyChanged event on our sales person, and when its commision is changed, we act accordingly.

I think this is all a mess, and it just gets worse and worse as you build up your domain model and add more classes and more relations. It's easy to forget one of these dependencies. If you are building a fairly complex UI on top of this (e.g. one which allows you to drill down and navigate through the relationships and make changes to objects), I'm so sure you will introduce bugs due to not raising the event, I know it's happened to me!

On my next (real) WPF project this is definitely something I will be thinking about seriously.

Anyway I would be interested to know what people think about this. Is this a problem which other people have faced? How do you architect your applications to avoid this complexity?

Saturday 19 July 2008

Refactoring Silverstone - Removing static container and cleaning up the Shell

Hey readers, hope all is good! Firstly to apologise on having been fairly quiet on the Silverstone / Silverlight blog postings, especially with regards to my series on architecting Silverlight applications using the MVC patterns (most recent article here).

So, Silverlight Beta 2 came out and I spent some time absorbing those changes and trying to work out how they affect what I was doing. I have also made some alterations to the Silverstone framework to remove some code smells I was experiencing when wiring the Views and ViewModels together in preparing part 4 of the series.

One thing that Beta 2 adds is much better support for bubbling of RoutedEvents. This is a great change, but it actually caused a problem for my CommandManager class! The CommandManager was relying on the mouse and keyboard events bubbling up from their target element to the application root in order to provide automatic invalidation of the CanExecuteChanged handler on registered commands. Now that Silverlight has more advanced handling of these events, they no longer bubble up to the application root (as the textbox/button/whatever marks them as e.Handled=true). This is the correct behaviour and mirrors WPF, but it means my technique no longer works, making the ViewModels slightly more complex as they need to manually raise the CanExecuteChanged event.

Once Silverlight gets event tunnelling, which I'm sure (hope!) will be incorporated into the next release, I will add this back in as we will be able to capture the events before they are actually handled by the target element (e.g. PreviewKeyDown / PreviewMouseDown).

So I now have a basic view working, and will be creating the other views soon and blogging the next part in the near future.

As I mentioned, whilst working on this, I made a few refactorings to Silverstone (and to the sample code):

The Ioc Container is no longer a static class. This always bothered me - why have a static class here? So I made it a non static and also made it implement an interface (IContainer). The added bonus of this (and the real reason I did it) is that other components can access the container without going through a static reference. So, the container now registers itself with itself, and you can get it passed to your class simply by adding a constructor parameter of type IContainer.

Once I did that, I refactored the Shell class, which was looking rather nasty from the client API side of things! If you remember in Part 2 of my series, I was writing a LoginViewModel but I was having to pass the other related views into the constructor in order that I could navigate to them upon certain actions (see the comments saying This is just an empty view interface for now *shudder*). I think having to do this makes iterative development much harder as you need to create fakes and register them with the Ioc container just to have your class be constructed!

So instead, the Shell now uses the IContainer to get the views from it and all I need to do is pass the type of the View interface to the Shell and it can do everything from there, like so:

this.shell.Navigate<IFriendListView>();

Finally, I moved the entire sample code into the actual Silverstone SVN repository, which makes it much easier for me to develop the two things side by side! So if you want to an early preview of the code, you can get it from svn

I will be posting the entire solution once it's finished, and hopefully uploading it to some hosting area in the cloud.

Wednesday 9 July 2008

An unmanaged version of WPF coming?

This sounds incredibly interesting - it appears Microsoft are working on what looks like a native version of WPF!

Anyone heard about this or know any more about this - I would love to know some details! An unmanaged version would be great and would probably yield massive performance issues even for unmanaged WPF as a lot of the grunt work would presumably be able to be pushed to unmanaged code.

Could this be the return of the Microsoft's old Cairo project (which now seems to be being worked on by an external group of developers if I'm not mistaken - www.cairoshell.com)

Thoughts?

Sunday 6 July 2008

Using Linq's Expression Trees to Enable Better Refactoring

How many times have you seen code like this:

public DateTime StartDate
{
  get { return this.startDate; }
  set
  {
    this.startDate = value;
    this.RaisePropertyChanged(this, "StartDate");
  }
}

I know I have! There are many areas of .NET development where you are required to specify the name of a property or method as a string. This is fine, but if you rename the property, there is a chance that you will forget to update the string too, which is definitely not good!

.NET 3.5 and Linq introduces a new feature called expression trees in the C#3 compiler. Compilers typically generate an AST (abstract syntax tree) from the code you write, which is then checked and transformed into machine code (or in .NET case, MSIL). By using an expression tree, you tell the C# compiler not to compile your code into MSIL, but instead to create a representation of the code in object form. This tree can then be navigated through methods on the Expression objects.

Using an expression tree, we can simply write a method which will return the name of whichever method or property is being called (I used an extension method):

public static class Extensions
{
    public static string GetPropertyName<T,S>(this T obj, Expression<Func<T,S>> expr)
    {
        return ((MemberExpression) expr.Body).Member.Name;
    }
}

To call this is fairly simple, we rewrite the previous code as:

public DateTime StartDate
{
  get { return this.startDate; }
  set
  {
    this.startDate = value;
    this.RaisePropertyChanged(this, this.GetPropertyName(p => p.StartDate));
  }
}

The code above creates a lambda which returns the value of StartDate method and passes it to the GetPropertyName() method. If this lamdba was to be executed, it would return the startDate, however the GetPropertyName() function never executes the lambda, it simply peeks into the code being called and returns the name of the property.

This technique is starting to be used everywhere and it's so useful. Code as strings is nasty!

Have a great day...

Selecting the Detail Level to View at Runtime in WPF - An even better way!

Regarding my previous post Josh rightly commented that this technique could lead to lots of extra visuals being created that are never displayed, which for large data loads is not desirable and definitely a waste of resources. Josh also made a number of other salient points which are worth reading.

Well it was upon reading this comment that it struck me that there was in fact no need to be creating (and hiding lots of visuals) when they are not used! We simply need a SINGLE content presnter, and just change the template of that with a trigger, like so:

  <DataTemplate x:Key="SelectorTemplate">
    <Grid>
      <ContentPresenter x:Name="proxyDataPresenter" Content="{Binding}" />
    </Grid>
    <DataTemplate.Triggers>
      <DataTrigger Binding="{Binding ElementName=detailLevelSlider, Path=Value}" Value="1">
        <Setter TargetName="proxyDataPresenter" Property="ContentTemplate" 
                Value="{StaticResource LowTemplate}" />
      </DataTrigger>
      <DataTrigger Binding="{Binding ElementName=detailLevelSlider, Path=Value}" Value="2">
        <Setter TargetName="proxyDataPresenter" Property="ContentTemplate" 
                Value="{StaticResource MediumTemplate}" />
      </DataTrigger>
      <DataTrigger Binding="{Binding ElementName=detailLevelSlider, Path=Value}" Value="3">
        <Setter TargetName="proxyDataPresenter" Property="ContentTemplate" 
                Value="{StaticResource HighTemplate}" />
      </DataTrigger>
    </DataTemplate.Triggers>
  </DataTemplate>

The simplicity baffles me and it really works a treat... again this kind of thing just makes me appreciate the sheer power of WPF and it's declarative style of programming.

Saturday 5 July 2008

Selecting the Detail Level to View at Runtime in WPF - An alternate way?

I recently read Josh Smith's post on codeproject which explained how to use a Slider control to dynamically apply a WPF data template a runtime. If you haven't read it, I suggest you read it before continuing.

So I have come up with an alternative solution which is done in pure XAML. This is a technique which I have used on previous projects and it involves creating a "surrogate" data template which simply passes control to another data template via a content presenter. Because a data template is used to do this, it has access to the inheritance context so does not require any freezable hacks to find the slider or other data templates.

Note that in order to make this a pure xaml solution I replaced the data source (which was originally in code) with an XmlDataProvider nested in the XAML document. Hence that lovely Pam girl does not appear in my version, which will probably disappoint most people...

Anyway check it out below, simple copy and paste in XamlPad/Kaxaml to see it working!

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <DockPanel>  
    <DockPanel.Resources>
    
      <XmlDataProvider x:Key="Data" XPath="/people">
        <x:XData>
          <people xmlns="">
            <person name="Neil" age="29" gender="M" />
            <person name="Jane" age="40" gender="F" />
            <person name="Jack" age="23" gender="M" />
          </people>
        </x:XData>
      </XmlDataProvider>        
    
      <DataTemplate x:Key="LowTemplate">
        <TextBlock Text="{Binding XPath=@name}" />
      </DataTemplate>
    
      <DataTemplate x:Key="MediumTemplate">
        <TextBlock>
            <TextBlock Text="{Binding XPath=@name}" />
            <Run>(</Run>
            <TextBlock Text="{Binding XPath=@age}" Margin="-4,0" />
            <Run>)</Run>
          </TextBlock>
      </DataTemplate>
    
      <DataTemplate x:Key="HighTemplate">
        <TextBlock>
          <TextBlock Text="{Binding XPath=@name}" />
          <Run>(</Run>
          <TextBlock Text="{Binding XPath=@age}" Margin="-4,0" />
          <Run>) -</Run>
          <TextBlock Text="{Binding XPath=@gender}" />
        </TextBlock>
      </DataTemplate>
      
      <DataTemplate x:Key="SelectorTemplate">
        <Grid>
          <ContentPresenter x:Name="lowPresenter" 
                Content="{Binding}" ContentTemplate="{StaticResource LowTemplate}" 
                Visibility="Collapsed" />
          <ContentPresenter x:Name="mediumPresenter" 
                Content="{Binding}" ContentTemplate="{StaticResource MediumTemplate}" 
                Visibility="Collapsed" />
          <ContentPresenter x:Name="highPresenter" 
                Content="{Binding}" ContentTemplate="{StaticResource HighTemplate}" 
                Visibility="Collapsed" />
        </Grid>
        <DataTemplate.Triggers>
          <DataTrigger 
                Binding="{Binding ElementName=detailLevelSlider, Path=Value}" 
                Value="1">
            <Setter TargetName="lowPresenter" 
                       Property="Visibility" 
                       Value="Visible" />
          </DataTrigger>
          <DataTrigger 
                Binding="{Binding ElementName=detailLevelSlider, Path=Value}" 
                Value="2">
            <Setter TargetName="mediumPresenter" 
                       Property="Visibility" 
                       Value="Visible" />
          </DataTrigger>
          <DataTrigger 
                Binding="{Binding ElementName=detailLevelSlider, Path=Value}" 
                Value="3">
            <Setter TargetName="highPresenter" 
                       Property="Visibility" 
                       Value="Visible" />
          </DataTrigger>
        </DataTemplate.Triggers>
      </DataTemplate>
      
    </DockPanel.Resources>
      
    <StackPanel 
      DockPanel.Dock="Bottom" 
      Background="LightGray"
      Margin="4" 
      Orientation="Horizontal"
      >
      <TextBlock 
        Margin="2,0,4,0" 
        Text="Detail Level:" 
        VerticalAlignment="Center" 
        />
      <Slider 
        x:Name="detailLevelSlider"
        DockPanel.Dock="Bottom" 
        Minimum="1" Maximum="3" 
        SmallChange="1" LargeChange="1" 
        IsSnapToTickEnabled="True" TickFrequency="1"
        Value="0" 
        Width="120" 
        />
    </StackPanel>
    
    <ScrollViewer>
      <ItemsControl
        ItemsSource="{Binding Source={StaticResource Data}, XPath=person}"
        ItemTemplate="{StaticResource SelectorTemplate}"
        />
    </ScrollViewer>
    
  </DockPanel>
</Page>