Archive for December, 2008

Visualize project dependencies in Visual Studio

Wednesday, December 31st, 2008

When approaching a new body of code, I like to have a map. This helps me see where to start looking, what avenues to ignore for now, and why the previous authors made the decisions they did.

Accurate documentation is never available. It's just too costly to maintain. I think we've finally stopped beating the "not enough documentation" drum. Now we turn to the code itself.

For a quick first glance at a Visual Studio solution, I run this handy macro.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Imports VSLangProj
Imports System.IO

Public Module Diagram

    Sub ProjectDependency()
        Dim vsProject As VSProject
        Dim file As Integer
        Dim writer As New StreamWriter(DTE.Solution.FileName & ".dot")

        writer.WriteLine("digraph """ & DTE.Solution.FullName & """ {")
        writer.WriteLine("  rankdir=LR")

        For Each project As Project In DTE.Solution.Projects
            vsProject = TryCast(project.Object, VSProject)
            If Not vsProject Is Nothing Then
                For Each reference As Reference In vsProject.References
                    If Not reference.SourceProject Is Nothing Then
                        writer.WriteLine("  """ & project.Name & """->""" & reference.SourceProject.Name & """")
                    End If
                Next
            End If
        Next

        writer.WriteLine("}")
        writer.Dispose()
    End Sub

End Module

This generates a ".dot" file in the solution's folder. Run this through GraphViz to generate a graphical dependency map of the projects in the solution.

Then I start at the left side of the graph, which is where the entry points end up. I work my way down through the layers in a more-or-less breadth-first search of the project space. Tightly coupled project groups end up looking messy, and loosely coupled project groups end up looking neat.

Once I've oriented myself with this coarse map, I'll get more fine grained with a tool like NDepend. But this is a great first step.

Presentation Model in WPF without INotifyPropertyChanged

Saturday, December 27th, 2008

View a video of this demo.

The Presentation Model pattern, otherwise known as Model/View/ViewModel, inserts an intermediate class between your data model and your view. This intermediate class implements presentation logic, behavior directly related to user interaction. This logic doesn't belong in the data model, because it is not related to business logic. Nor does it belong in the view, because the view is difficult to unit test, and is more concerned with style and layout.

Current implementations of Presentation Model in WPF rely on data binding, which requires you to implement INotifyPropertyChanged. While this is just a minor inconvenience when binding directly to data objects, it is particularly troublesome to a presentation model. Since a presentation model consumes properties of a data model, it must register for PropertyChanged events. And since the view binds to the presentation model rather than the data model, it must turn around and fire those events again.

Here's my solution
As I posted earlier, Update Controls replaces WPF data binding and does not require you to implement INotifyPropertyChanged. I've just published a new version of Update Controls (2.0.2), which adds a feature especially useful for the Presentation Model pattern. You can now use dotted identifier syntax to reference objects indirectly. Now the presentation model doesn't have to pass through all of the properties of the data model. It only needs to implement those that it intends to tweak for the UI, and expose a reference to the data model for access to all the others.

Wrap the data object
In the previous post, we created a Person data object and some XAML that bound to it. We'll keep the same Person object, but wrap it in a PersonPresentation object. This object exposes the Person as a property, and adds UI logic for the window title.

public class PersonPresentation
{
    private Person _person;

    public PersonPresentation(Person person)
    {
        _person = person;
    }

    public Person Person
    {
        get { return _person; }
    }

    public string Title
    {
        get { return "Person - " + _person.Display; }
    }
}

Instead of directly using Person as the DataContext for the window, use a PersonPresentation.

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        DataContext = new PersonPresentation(new Person());
    }
}

Now use dotted-identifier syntax in the XAML to access the Person for data properties. But for UI properties, like the window title, go directly after the PersonPresentation object.

<Window x:Class="UpdateControls.XAML.Test.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:u="clr-namespace:UpdateControls.XAML;assembly=UpdateControls.XAML"
    Title="{u:Update Title}" Height="300" Width="300">
    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="First Name:" Width="100"/>
            <TextBox Text="{u:Update Person.FirstName}" Width="170"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="Last Name:" Width="100"/>
            <TextBox Text="{u:Update Person.LastName}" Width="170"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="Display As:" Width="100"/>
                <ComboBox SelectedIndex="{u:Update Person.DisplayStrategy}" Width="170">
                    <ComboBoxItem Content="{u:Update Person.FirstLast}" />
                    <ComboBoxItem Content="{u:Update Person.LastFirst}"/>
                </ComboBox>
        </StackPanel>
    </StackPanel>
</Window>

With the Presentation Model pattern, you achieve separation of concerns. Business logic is encapsulated in the data model, style and layout are in the view, and interaction logic is in the presentation model.

Update Controls for WPF

Wednesday, December 24th, 2008

I've released Update Controls support for WPF. You can see a quick demo video that demonstrates building a WPF application from scratch using the new markup extension. It's better than data binding.

With this release, you can bind WPF controls directly to CLR properties without implementing INotifyPropertyChanged. All you do is use the Independent class to keep track of gets and sets. And the Visual Studio add-in will even do that for you when you select the properties and hit Ctrl+D, G.

public class Person
{
    private string _firstName;
    private string _lastName;
    private int _displayStrategy;

    #region Independent properties
    // Generated by Update Controls --------------------------------
    private Independent _indDisplayStrategy = new Independent();
    private Independent _indFirstName = new Independent();
    private Independent _indLastName = new Independent();

    public string FirstName
    {
        get { _indFirstName.OnGet(); return _firstName; }
        set { _indFirstName.OnSet(); _firstName = value; }
    }

    public string LastName
    {
        get { _indLastName.OnGet(); return _lastName; }
        set { _indLastName.OnSet(); _lastName = value; }
    }

    public int DisplayStrategy
    {
        get { _indDisplayStrategy.OnGet(); return _displayStrategy; }
        set { _indDisplayStrategy.OnSet(); _displayStrategy = value; }
    }
    // End generated code --------------------------------
    #endregion

    public string FirstLast
    {
        get { return FirstName + " " + LastName; }
    }

    public string LastFirst
    {
        get { return LastName + ", " + FirstName; }
    }

    public string Display
    {
        get { return DisplayStrategy == 0 ? FirstLast : LastFirst; }
    }
}

The FirstName, LastName, and DisplayStrategy properties are all independent. Their values are determined by the user. The FirstLast, LastFirst, and Display properties are all dependent. Their values are determined by code. Notice that there is absolutely no bookkeeping code around the dependent properties. Yet you can still bind to them using u:Update.

<Window x:Class="UpdateControls.XAML.Test.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:u="clr-namespace:UpdateControls.XAML;assembly=UpdateControls.XAML"
    Title="{u:Update Display}" Height="300" Width="300">
	<StackPanel>
		<StackPanel Orientation="Horizontal">
			<Label Content="First Name:" Width="100"/>
			<TextBox Text="{u:Update FirstName}" Width="170"/>
		</StackPanel>
		<StackPanel Orientation="Horizontal">
			<Label Content="Last Name:" Width="100"/>
			<TextBox Text="{u:Update LastName}" Width="170"/>
		</StackPanel>
		<StackPanel Orientation="Horizontal">
			<Label Content="Display As:" Width="100"/>
			<ComboBox SelectedIndex="{u:Update DisplayStrategy}" Width="170">
				<ComboBoxItem Content="{u:Update FirstLast}" />
				<ComboBoxItem Content="{u:Update LastFirst}"/>
			</ComboBox>
		</StackPanel>
	</StackPanel>
</Window>

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        DataContext = new Person();
    }
}

And, by the way, it still supports Winforms.

Download it and try it in your next WPF application. You'll never want to go back to plain-old data binding again.

Update Controls in WPF and Silverlight

Wednesday, December 10th, 2008

Update Controls .NET is a library of controls for Windows Forms that automatically update themselves. They are superior to data binding because they can see through layers of business logic and respond to changes in the underlying data. It is not necessary to implement INotifyPropertyChanged, or to bubble up state-change events by any means.

In WPF, and now in Silverlight 2.0, Microsoft has provided a significant improvement to data binding. It is now easy to add data binding to any user control. Data binding can now be expressed declaratively within XAML. And it is trivially simple for one dependency property to depend upon another one. The improvements are so great that it is difficult for people to see the pain that is still there.

INotifyPropertyChanged and ObservableCollection<T>
In WPF and Silverlight data binding, it is still necessary for the developer to fire property changed events. These events are fired by an object that implements INotifyPropertyChanged. The interface makes it possible for dependency properties to register for these events.

Some helper classes implement this interface on your behalf. For example, ObservableCollection<T> is a generic container that fires property changed events when items are added or removed. By exposing these helper classes from your own business class, you can offload the responsibility of notification.

Typically, you use ObservableCollection<T> in your data objects. If you bind your user interface directly to your data objects, then everything works just fine. But if you want a layer of business logic between the data layer and the UI, ObservableCollection<T> is no longer helpful to you. What you want is an intermediate collection that can filter the source, or wrap adapters around each of the items. ObservableCollection<T> only provides a way to bind directly to the source collection without modification.

Presentation Model pattern
The Model/View/ViewModel pattern was created by the Blend team to separate user interface logic from business logic. In this pattern, the view model transforms the raw data from the model into the visible data shown to the user. The view model observes the underlying data model and notifies the view when it changes.

Martin Fowler documents a similar pattern called the Presentation Model. In his document, the role of the ViewModel is played by the Presentation Model. I find this a more descriptive term, so it is the one I adopt. He calls out synchronization between the presentation model and view is the most annoying part of the pattern. While .NET data binding attempts to solve this problem, it still requires that the presentation model subscribe to notifications from the model and forward them to the view.

Update Controls Presentation Model
I am currently working on full support of the Presentation Model pattern in Update Controls. Since the strong point of Update Controls is tracking dependency through layers of business logic, it closes this annoying gap in Fowler's pattern. I will be releasing source code shortly, but here's what I have so far:

    public class PersonPresentation : PresentationObject<Person>
    {
        private PresentationProperty<string> _firstName;
        private PresentationProperty<string> _lastName;
        private PresentationProperty<string> _firstLast;
        private PresentationProperty<string> _lastFirst;
        private PresentationProperty<int> _displayStrategy;
        private PresentationProperty<string> _title;

        public PersonPresentation(Person person) :
            base(person)
        {
            _firstName = new PresentationProperty<string>(this, "FirstName",

                () => BusinessObject.FirstName);
            _lastName = new PresentationProperty<string>(this, "LastName",
                () => BusinessObject.LastName);
            _firstLast = new PresentationProperty<string>(this, "FirstLast",
                () => CalculateFirstLast());
            _lastFirst = new PresentationProperty<string>(this, "LastFirst",
                () => CalculateLastFirst());
            _displayStrategy = new PresentationProperty<int>(this, "DisplayStrategy",
                () => BusinessObject.DisplayStrategy);
            _title = new PresentationProperty<string>(this, "Title",
                () => "Person - " + (BusinessObject.DisplayStrategy == 0 ? CalculateFirstLast() : CalculateLastFirst()));
        }

        private string CalculateLastFirst()
        {
            return BusinessObject.LastName + ", " + BusinessObject.FirstName;
        }

        private string CalculateFirstLast()
        {
            return BusinessObject.FirstName + " " + BusinessObject.LastName;
        }

        public string FirstName
        {
            get { return _firstName.Value; }
            set { BusinessObject.FirstName = value; }
        }

        public string LastName
        {
            get { return _lastName.Value; }
            set { BusinessObject.LastName = value; }
        }

        public int DisplayStrategy
        {
            get { return _displayStrategy.Value; }
            set { BusinessObject.DisplayStrategy = value; }
        }

        public string FirstLast
        {
            get { return _firstLast.Value; }
        }

        public string LastFirst
        {
            get { return _lastFirst.Value; }
        }

        public string Title
        {
            get { return _title.Value; }
        }
    }

The PersonPresentation object (presentation model) wraps the Person business object (data model). The PresentationObject base class implements INotifyPropertyChanged on your behalf. PresentationProperty is a wrapper around a data type that calls a provided Action when the property is out-of-date. You expose the value of each presentation property through a CLR property getter, and pass the setter through to the underlying business object. This allows you to specify attributes like "{Binding FirstName}" in your WPF or Silverlight.

Collections are handled in a similar fashion:

    public class PresentationAddressBook : PresentationObject<AddressBook>
    {
        private PresentationCollection<Person, PresentationPerson> _people;

        public PresentationAddressBook(AddressBook addressBook) :
            base(addressBook)
        {
            _people = new PresentationCollection<Person, PresentationPerson>(this, "People",
                () => BusinessObject.People,
                person => new PresentationPerson(person));
        }

        public ICollection<PresentationPerson> People
        {
            get { return _people.Value; }
        }

        public void AddPerson()
        {
            BusinessObject.AddPerson();
        }
    }

The PresentationCollection performs two actions rather than just one. It first gets the collection of business objects from the parent business object. Then, it wraps each business object in another presentation object. In the process, it performs object recycling so that you reuse a presentation object for a given business object.

Coming soon
I am still refining this mechanism. When it is finished, it will be part of the new Update Controls .NET 2.0 release. I would like to reduce the amount of code necessary to write a presentation object. Ideally, you would need no base class and no members (besides the business object reference). A presentation model should be as simple as this:

    public class PersonPresentation
    {
        private Person _person;

        public PersonPresentation(Person person)
        {
            _person = person;
        }

        public string FirstName
        {
            get { return _person.FirstName; }
            set { _person.FirstName = value; }
        }

        public string LastName
        {
            get { return _person.LastName; }
            set { _person.LastName = value; }
        }

        public int DisplayStrategy
        {
            get { return _person.DisplayStrategy; }
            set { _person.DisplayStrategy = value; }
        }

        public string FirstLast
        {
            get { return _person.FirstName + " " + _person.LastName; }
        }

        public string LastFirst
        {
            get { return _person.LastName + ", " + _person.FirstName; }
        }

        public string Title
        {
            get { return "Person - " + (DisplayStrategy == 0 ? FirstLast : LastFirst); }
        }
    }

That's my goal. Let's see how close I get.

Using the generic type ‘System.Action<T>’ requires ‘1′ type arguments

Sunday, December 7th, 2008

The Action and Func delegates are brilliant -- if late -- additions to the .NET framework. A delegate is a method that can be passed as a parameter. They can be used anywhere that you could use an interface with only one method. But delegate syntax is lighter weight than interface syntax.

The type of a delegate is really nothing more than a function signature. But even though the syntax for declaring a delegate is simpler than the syntax for declaring an interface, it is still more complex than it needs to be. Like any other type, a delegate is given a name. But the name is not important, only the signature.

The Action and Func generic delegates were added to the .NET framework in 2.0, which was the first version of the framework to support generics. Using these generics, the signature of a delegate can be declared in line. No separate type needs to be declared, no name needs to be specified, and all information is visible via intellisense.

One problem, however, was that no Action could be specified taking no arguments and returning no value. At least not until .NET 3.5. My guess is that Microsoft left this out so that the compiler wouldn't get confused having a class and a generic with the same name. But .NET 3.5 includes a compiler upgrade (for features like Linq, extension methods, and many more), so they probably fixed this minor issue at the same time. I haven't taken the time to test this theory.

Regardless the reason, if you need an Action with no parameters and no return type, then you have to target .NET 3.5. If you ever get this error message, check your Target Framework setting in the project properties.

Correspondence preview drop

Thursday, December 4th, 2008

It is with pride (and not a little fear) that I release a preview of Correspondence. Please download and follow along with the discussion.

The preview drop includes the bug tracker sample model that we've been building over the past month. It also includes a unit test that exercises that model using the Postgres storage strategy. I have not yet decided on a license model for the Correspondence library itself. As it is now, it is not yet suitable for production use. So the library is provided for demonstration purposes only, without warrantee, and without license for use in any product or derived work.

The contents of the zip file are an Eclipse project. My preferred distribution of Eclipse is Ganymede, which is ideally suited to building web applications. If you are not an Eclipse user, you can port the project to your environment of choice. I have not included an Ant script, but feel free to do so if that's how you work.

You will have to install Postgres to run the test. Please drop the postgresql jar file in the lib folder and update the reference in bugtracker_model_test. You will then need to run the correspondence.sql script to build the Correspondence database. I could have used the in-memory storage strategy, but I thought you would get more out of seeing an actual working database.

Please give this preview a try and let me know how it goes. This will allow us to continue the conversation about Correspondence by exchanging working source code. Enjoy!