Friday, December 18, 2009

Speaking at DevTeach Toronto March 8-12

I was selected to speak this year at DevTeach Toronto and will be giving two talks:

Leverage WCF RIA Services for a Quick N-Tier Silverlight Solution

Separate Your UI Concerns with MVVM & Prism

I’m really looking forward to it. DevTeach is a great little show densely packed with awesome speakers, so I count myself lucky to be included among them. It has been a couple of years since I have been able to speak there due to schedule conflicts with all of their shows, so I am happy the timing worked out this year to be able to go.





Friday, December 18, 2009 1:50:19 PM (GMT Standard Time, UTC+00:00)
Comments [1]  | 


  Tuesday, December 08, 2009

Detecting the Active View in a Prism App

A bit overdue, but a while back I wrote a post on handling graceful shutdown in a Prism application through the use of commands here and here. In those posts, I also promised to talk about detecting active views.

Baked into the Prism code since version 1 is an ability to detect when a view is active automatically as long the view is hosted in a region. It is a bit under-documented and hard to discover, but actually works quite nicely for a lot of scenarios.

Specifically in the example simple document editor I showed in the previous posts, I needed to detect when a given document was active so that I could enable or disable the global Save button in the toolbar based on the active document. That was based on state associated with the view in its ViewModel, a dirty flag indicating whether the document had been edited or not. In other contexts you might fire a pub-sub event indicating an active item, or you could change a bunch of formatting on the fly based on the active or inactive state of the view.

It actually takes very little code to get this done.

Part of the infrastructure code for Prism includes some things called region adapters. You mostly don’t have to even know they are there, but they provide the bridge between the abstract concept of a region and a specific type of container control in WPF or Silverlight. If the region that a view ends up in supports selection (specifically derives from Selector in WPF or Silverlight or is a custom container with its own region adapter that indicates selection), then when the view is selected (i.e. TabItem selected in a TabControl, ListBoxItem selected in a ListBox control, ListViewItem selected in a ListView), a behavior in the region is invoked that checks the view to see if it supports the IActiveAware interface.

IActiveAware

IActiveAware is a simple interface you can implement on your views to indicate that you want the view to be notified when it is made active or inactive. It looks like this:

public interface IActiveAware
{
    /// <summary>
    /// Gets or sets a value indicating whether the object is active.
    /// </summary>
    /// <value><see langword="true" /> if the object is active; otherwise <see langword="false" />.</value>
    bool IsActive { get; set; }

    /// <summary>
    /// Notifies that the value for <see cref="IsActive"/> property has changed.
    /// </summary>
    event EventHandler IsActiveChanged;
}

The IsActive flag lets you know if your view is active, and the IsActiveChanged event will fire when that state changes.

If you implement this on your view class (typically a user control), then you need to ensure the event gets fired when the state is changed by the region behavior. Since you shouldn’t put the actual logic code of what to do when that active state changes in the view definition itself, you will also want to get that state change transmitted into the view model. If you are following the typical pattern for ViewModel, your ViewModel will be set as the DataContext for the view. You can also implement IActiveAware on the ViewModel and have a nice decoupled way to dispatch the state change into the ViewModel without coupling the view to the ViewModel.

In the sample document editor, the view implementation of the interface looks like the following:

private bool _IsActive;
public bool IsActive
{
    get
    {
        return _IsActive;
    }
    set
    {
        _IsActive = value;
        IActiveAware vmAware = DataContext as IActiveAware;
        if (vmAware != null)
            vmAware.IsActive = value;

    }
}
public event EventHandler IsActiveChanged = delegate { };

 

The setter for the IsActive property will again be called by the region behavior, and in that setter, we take care of both firing the event on the view (since it fully implements IActiveAware) and also pass the setting call into the ViewModel if appropriate by checking to see if the object set as the ViewModel implements IActiveAware as well. If it does, we just set its IsActive property to the value being set on the view itself.

Notice the syntax for the IsActiveChanged event. We call this the “delegate trick”. By declaring an empty anonymous delegate for the event, you are basically subscribing for the life of the object a single, no-op subscriber to the list who cannot be removed. That means that not only can you blindly fire the event without checking for null, but it also solves a nasty little race condition if your null check gets called right before a thread interrupt and the last subscriber is removed before your thread resumes. The question always comes up of whether that will have a performance impact. The strict answer is yes. A couple extra instructions on the stack when you fire your event. A few nanoseconds lost on a modern machine. If that is truly the performance bottleneck in your program, contact me – I want to hire you, because you are the best programmer on the planet or I don’t want to hire you because you are not building anything real.

The ViewModel implementation of the IActiveAware interface is where the real work gets done, specifically setting the enabled state of the Save command.

public bool IsActive
{
    get
    {
        return _IsActive;
    }
    set
    {
        _IsActive = value;
        SaveCommand.IsActive = value;
        IsActiveChanged(this, EventArgs.Empty);
    }
}


public event EventHandler IsActiveChanged = delegate { };

 

So that’s it. Simple, effective. Implement IActiveAware on your view. Dispatch the setting of the IsActive property into your ViewModel by casting the DataContext to IActiveAware and implementing IActiveAware on your ViewModel. In your ViewModel, do whatever behavior is appropriate for your view.

Any comments or questions welcome.





Tuesday, December 08, 2009 3:03:52 AM (GMT Standard Time, UTC+00:00)
Comments [4]  | 


  Saturday, November 14, 2009

Slides and Demos from VS/Architect Connections This Week

I gave 4 sessions and repeat recorded a 5th this week at Visual Studio and Architect Connections in Las Vegas. The line up was as follows:

Build Workflow 4.0 Service Applications – covered the service messaging capabilities of workflow 4.0. Covered the Receive activity (and coupled SendReply) for exposing service operations from workflows, as well as Send/ReceiveReply (and the code generated activities) for calling services. Also covered the three forms of correlation: Request-Reply, Context (protocol), and Content correlation.

Slides    Demos

Wrap Your Head Around Concurrency in WF 4.0 – Covered all the many forms of concurrency in workflows. Where threads are doing what, how to use the parallel activities and the pseudo-concurrency that you get with that. Also showed how the built-in InvokeMethod executes asychronously, as well as how to build a custom async activity.

Slides   Demos

Connecting Smart Clients Through the .NET Service Bus – Covered basic use of .NET Service Bus to connect a client to back end services and the benefits of doing so. Also spent a good deal of time on event driven scenarios -  being able to push things to the client from back end services or for peer-to-peer communications from other clients. Discussed current and future state of affairs for document/data sharing and synchronization.

Slides   Demos

Build Testable Client and Service Applications – Covered practices and patterns for making applications more testable. Discussed benefits and principals of TDD, S.O.L.I.D., IoC, DI, Repository, Separated Presentation, and closed with a number of testability tricks for unit testing.

Slides   Demos





Saturday, November 14, 2009 6:56:11 PM (GMT Standard Time, UTC+00:00)
Comments [2]  | 


  Wednesday, November 04, 2009

Use Extension Methods to Phase Out a Bad API

I’m working on a project for a customer where we are trying to get a new version of a product out the door. We need to add some features to an existing API, but don’t want to break the existing API for existing customers. Common story, common place to be.

However, in adding these new features, we really need to be modifying an existing API to add new options to existing methods. But we find ourselves in a place I’ve seen a number of times: the API tried to be too granular about its arguments. It provided flexibility for optional arguments with overloaded methods. Not a bad thing from an OO perspective. The slippery slope is trying to anticipate how many arguments you might actually need to that method over time and which of those arguments might be optional.

Defining a Clean, Version Tolerant API

Say you start with a simple API like this:

public interface ISomeInterface
{
    void SomeMethod(double alwaysNeeded);
    void SomeMethod(double alwaysNeeded, int optionArg1);
    void SomeMethod(double alwaysNeeded, string optionArg2);
    void SomeMethod(double alwaysNeeded, int optionArg1, string optionArg2);
}

There is one always needed argument, and a couple of optional args. Fine when there are just two options. What about when the list grows to 3, 4, 5, 6? How many overloads do you have to add to cover all the reasonable combinations of those arguments a user might want? The size of your API goes exponential, and the usability of it goes downhill quick.

This is the situation we find ourselves in. And this is why I have long recommended that unless an API is going to be static and always take the same set of arguments, you are better off packaging up those arguments in a single complex argument – a data structure single argument such as the following:

public class MyMethodArg
{
    public double AlwaysNeeded { get; set; }
    public int OptionalArg1 { get; set; }
    public string OptionalArg2 { get; set; }
}

Then you can simplify the interface definition to just the following:

public interface ISomeInterface
{
    void SomeMethod(MyMethodArg arg);
}

Now, over time, you can add additional required or optional arguments without affecting the interface API at all. As long as you write graceful handling for when optional parameters are not set explicitly on the data structure, you have much better ability to change the underlying arguments over time without breaking existing clients. And you have a much cleaner, easier to understand API.

Extension Methods to the Rescue

So then the question becomes: If you find yourself with an API that looks like the original version and you want to move to the cleaner version immediately above, do you have to break all your existing clients to get there? Thanks to extension methods, the answer is no.

Say you have existing clients that have code that depends on the original API. A simple one might look like the following console app:

class Program
{
    static void Main(string[] args)
    {
        ISomeInterface itf = new SomeImplementation();
        // V1 methods - obsolete
        itf.SomeMethod(1.0);
        itf.SomeMethod(1.0,42);
        itf.SomeMethod(1.0,"foo");
        itf.SomeMethod(1.0, 42,"foo");
        // V2 method
        itf.SomeMethod(new MyMethodArg { OptionalArg1 = 42 });
        Console.WriteLine("Press Enter to Exit...");
        Console.ReadLine();
    }
}

For sample purposes, say the original implementation looked like the following:

public class SomeImplementation : ISomeInterface
{
    void ISomeInterface.SomeMethod(double alwaysNeeded)
    {
        Debug.WriteLine("SomeMethod no optional args");
    }

    void ISomeInterface.SomeMethod(double alwaysNeeded, int arg)
    {
        Debug.WriteLine("SomeMethod optional int arg");
    }

    void ISomeInterface.SomeMethod(double alwaysNeeded, string arg)
    {
        Debug.WriteLine("SomeMethod optional string arg");
    }

    void ISomeInterface.SomeMethod(double alwaysNeeded, int arg1, string arg2)
    {
        Debug.WriteLine("SomeMethod optional int and string args");
    }
}

What you can do is use Extension methods to move the old API off the primary interface you want to keep for the long term (assuming there are also other methods and properties on that interface that you want to remain there instead of just defining a new interface with the new API). You could add the following class to your existing project:

public static class SomeInterfaceExtensions
{
    [Obsolete]
    public static void SomeMethod(this ISomeInterface itf, double alwaysNeeded)
    {
        itf.SomeMethod(new MyMethodArg { AlwaysNeeded = alwaysNeeded });
    }

    [Obsolete]
    public static void SomeMethod(this ISomeInterface itf, double alwaysNeeded, int arg)
    {
        itf.SomeMethod(new MyMethodArg { AlwaysNeeded = alwaysNeeded, OptionalArg1 = arg });
    }

    [Obsolete]
    public static void SomeMethod(this ISomeInterface itf, double alwaysNeeded, string arg)
    {
        itf.SomeMethod(new MyMethodArg { AlwaysNeeded = alwaysNeeded, OptionalArg2 = arg });
    }

    [Obsolete]
    public static void SomeMethod(this ISomeInterface itf, double alwaysNeeded, int arg1, string arg2)
    {
        itf.SomeMethod(new MyMethodArg { AlwaysNeeded = alwaysNeeded, OptionalArg1 = arg1, 
                                                                    OptionalArg2 = arg2 });
    }
}

Then, the implementation class can be collapsed to the following:

public class SomeImplementation : ISomeInterface
{
    void ISomeInterface.SomeMethod(MyMethodArg arg)
    {
        Debug.WriteLine("SomeMethod complex arg");
    }
}

The client can remained unchanged against the V1 API thanks to the extension methods, but will now get compiler warnings that the API is obsolete thanks to the Obsolete attributes. But they won’t break. New clients will not even see the old API unless they go looking for it, and then they should be smart enough not to write new code against things marked with the Obsolete attribute when there is a perfectly usable method on the primary API itself.

So this is the approach we are going to use to move forward the original lack-of-forethought API and clean it up for the long term.

Obviously this approach will only work if your clients (that you don’t want to break) are on .NET 3.5. If you could afford to lock them down to just .NET 4.0 or later, you would have another option with C# optional parameters or default values, but that is unlikely for most apps at this point in time.





Wednesday, November 04, 2009 8:51:30 PM (GMT Standard Time, UTC+00:00)
Comments [1]  | 


  Wednesday, October 28, 2009

Sydney .NET User Group Fit Walk

Last week I had the privilege of speaking at the Sydney .NET User’s Group while in Sydney teaching a WCF Master Class. It was an outstanding group and I spoke on WF 4 and Prism (Composite Application Guidance for WPF and Sliverlight). Had some great questions and discussion with the attendees, which is always what makes a group stand out in my mind.

If you want the slides and demos for the talks, you can find them here:

First Look at WF 4:   Slides   (no pre-built demo code, all on the fly demos in VS 2010 Beta 2)

Building Composite WPF and Silverlight Applications:   Slides    Demos

The other thing that made this group stand out for me (besides the above and the fact that it is run by friend and fellow RD Adam Cogan from SSW Software) was that instead of going out for beers or something else unhealthy afterwards, a small group of us went for a short power walk for some exercise afterwards around the area of the user group meeting. You can see the route we walked here:

http://www.mapmyride.com/route/australia/earlwood/465125612609191527

Nice variation for someone who is trying to lose weight and good chance to keep the technology discussion going with some of the attendees afterwards. Thanks to Adam for organizing!





Wednesday, October 28, 2009 4:41:32 PM (GMT Standard Time, UTC+00:00)
Comments [1]  | 


  Sunday, October 11, 2009

Australia Tour

I’m spending the next two weeks in Australia to teach some classes and speak at some user groups. This week, 12-16 Oct, I am teaching our Architect Master Class through our training partner Readify in Melbourne. Next week I’ll be teaching our WCF Master Class in Sydney 19-23 Oct, also through Readify.

The timing worked out perfectly that I also get to be the guest speaker at a user group in each city as well. On 13 October, I’ll be presenting a talk on Prism at the Victoria .NET User Group. On Wed 21 October, I’ll be giving two sessions at the Sydney .NET User’s Group on Prism and WF 4.

It’s always fun to give talks to user groups, but it is extra special fun to get to give user group talks in other countries. Really looking forward to both, as well as the classes. And spending two weeks in Australia doesn’t suck one bit either. :)





Sunday, October 11, 2009 5:02:10 AM (GMT Standard Time, UTC+00:00)
Comments [2]  | 


  Monday, October 05, 2009

Avoiding Memory Leaks with CompositeCommands

I had some good follow on discussions from my recent post on Graceful Shutdown with Ward Bell and Jeremy Miller about how “graceful” my shutdown example really was. They argued a point that I agreed was a big weakness with the approach: sending information back to the shell about whether to shutdown through a command parameter is not a very clean path of communication. Also, my arguments about using a command vs a pub-sub event were difficult to defend. Either one would work fine, but both suffer this same problem of obscure communication paths.

Jeremy also pointed out that the use of Prism CompositeCommands is always a little dirty and hazardous for two reasons. First, they are typically used as globals – a static singleton instance of the CompositeCommand that any control can source and any other part of the app can hook up to through the CompositeCommand.RegisterCommand method. And we all know that globals are evil.

The other problem with CompositeCommands is that it is too easy to have some chunk of code register a child command with the RegisterCommand method and then forget that now the CompositeCommand holds a reference chain back to the child command, the object on which the child command is a member, and the object on which the child command handler method exists.

In my simple example, there was the smell of a potential memory leak – an app that lets you open multiple documents, each document gets its own view and view model, and the view models are the command handlers for composite commands. Since those views are being dynamically created (in this case in response to another composite command for “New”), the registration is being done on the fly as their view models are initialized. So this begs the question of when do they get unregistered so that you don’t leak memory (in the form of residual command references into view models that are no longer being used). Prism commands do not currently use weak references like the Prism events do, although you could modify them to do so without too much difficulty.

You can get the updated code for this post here.

With the original sample code from my last post, it turned out this was not really a problem because the sample provided no way to close a view once opened. But it was just a sample focusing on the communication path for the Closing event after all. But say it was a real app and you were going to allow the user to close a document. I’ve modified the sample to allow closing a document through an X button on the tabs that the documents get opened in.

10-5-2009 8-40-21 AM

I didn’t take the time to beautifully style it, so forgive me my artistic ineptitude. But now that there is a mechanism to close the views, presumably the references to the views and view models are released when their document is closed, but if we don’t make sure we call UnregisterCommand in that process, we will have an effective memory leak – the CompositeCommands for Shutdown and Save will be holding references to the view models keeping them from being garbage collected. Each new document we open gets a new view and ViewModel instance, registers it, and over time we would see the memory of this app grow and grow.

So the direct solution is to ensure through whatever means practical to call UnregisterCommand before all refs to the ViewModel go away. Lets take a quick look at the code for this sample to get that done.

I added a data template to the shell where the TabControl is defined to add the X buttons into the tab headers:

<DataTemplate x:Key="ButtonTabItem">
    <DockPanel>
        <Button DockPanel.Dock="Right" 
          Command="{Binding Path=Content.DataContext.CloseCommand, 
          RelativeSource={RelativeSource AncestorType=TabItem}}">X
        </Button>
        <TextBlock Text="{Binding Path=Content.DataContext.DocumentTitle,
           RelativeSource={RelativeSource AncestorType=TabItem}}" VerticalAlignment="Center"/>
    </DockPanel>
</DataTemplate>

 

You can see the binding code is expecting a CloseCommand to be exposed from the ViewModel which is the DataContext of the view, and the view is the Content of the TabItem. The DocumentEditorView did not have to be modified at all, but the CloseCommand was added to the ViewModel as a DelegateCommand, as well as a Closed event to notify the controller:

public DocumentEditorViewModel()
{
    SaveCommand = new DelegateCommand<object>(OnSave, OnCanSave);
    SaveCommand.IsActive = true;
    Commands.SaveCommand.RegisterCommand(SaveCommand);

    ShutdownCommand = new DelegateCommand<CancelEventArgs>(OnShutdown);
    Commands.ShutdownCommand.RegisterCommand(ShutdownCommand);

     ...
    CloseCommand = new DelegateCommand<object>(OnClose);
 }

public DelegateCommand<object> CloseCommand { get; set; }
public event Action<DocumentEditorViewModel> Closed = delegate { };

private void OnClose(object obj)
{
    // Prompt to save, save document, etc.
    Commands.ShutdownCommand.UnregisterCommand(ShutdownCommand);
    Commands.ShutdownCommand.UnregisterCommand(SaveCommand);
    Closed(this); // Notify controller through an event, could also use a Prism event if others might care...
}

 

In this case, since the command handling for closing can be collocated with the code that did the registration, it is easy to make sure that we UnregisterCommand as part of the closing process. The controller is the one that takes care of presenting the views in this case, so the event is fired so the controller can choose to do what is appropriate, which in this case is to just remove the view from the region. That takes a bit of convoluted code to locate the view that corresponds to the ViewModel since the two are loosely coupled.

private void OnViewClosed(DocumentEditorViewModel vm)
{
    vm.Closed -= OnViewClosed;
    IRegion region = m_RegionManager.Regions[Constants.DOCUMENTREGION];
    DocumentEditorView viewToRemove = null;
    foreach (var view in region.Views)
    {
        DocumentEditorView docView = view as DocumentEditorView;
        if (docView == null) continue;
        if (docView.DataContext == vm)
        {
            viewToRemove = docView;
            break;
        }
    }
    if (viewToRemove != null)
        region.Remove(viewToRemove);
}

 

So for this simple example, it was not too terribly hard to make sure a memory leak did not happen with the use of the CompositeCommand once I added the functionality to close a view. However, what you can see emerging here is that the complexity is growing disproportionate to the work that this little sample is really doing. With a large app with many views/ViewModels, lots of commands and cross module communications, etc. this could get out of control pretty quick, and it would be easy to miss a place where you are not unregistering correctly.

The net result of all this is that the use of CompositeCommand works, but is not completely satisfying here, and especially not in a large complex  app. Modifying CompositeCommand to use weak references would be one choice, or switching to Prism events for the communications would be another choice.

Coupled with this challenge of potential memory leaks is the scenario of the previous post – graceful shutdown communications – is a another responsibility relative to view management that really cries out for some centralized management. Then you have the view activation/deactivation that I will talk about in my next post that also requires some common handling, and it turns out that what you really need is a pattern/abstraction that Prism does not yet really provide – you need a screen conductor / director of some sort that keeps track of what views are being presented, when they are activated/deactivated, whether they can close, etc.

Jeremy is working on a chapter for his upcoming book  that will cover an approach to this problem. I and others are trying to wrap our heads around the best way to tackle this problem. Ward Bell has suggested a “Close Service” that is responsible for coordinating the shutdown and he spiked an implementation of this that definitely felt cleaner than doing the back-channel communications through command or event arguments. I’ll be sure to blog more about this as my thoughts gel on it and if I can get a decent implementation put together, or will link to whoever beats me to it publicly first.

But before I get there, I do want to explain the IActiveAware mechanism of Prism, since it was important in getting the application to work correctly as well and is severely under-documented in the Prism docs. So that will be my next post, stay tuned…

You can get the updated code for this post here.





Monday, October 05, 2009 1:22:17 PM (GMT Standard Time, UTC+00:00)
Comments [0]  | 


  Wednesday, September 30, 2009

Deep Fried Bytes – Workflow Part 2 is up

Part 2 of my interview on workflow foundation, past, present, future, and focus on workflow services is up and available for your listening pleasure (or torture as the case may be).

dfb





Wednesday, September 30, 2009 1:00:43 PM (GMT Standard Time, UTC+00:00)
Comments [0]  | 











Ads by Lake Quincy Media









Sign In
Copyright © 2006-2007 Brian Noyes. All rights reserved.
Advertise on this site through Lake Quincy Media
designed by NUKEATION STUDIOS