Welcome to the World Kory!

kory01On Tuesday February 8, 2011, at 3:55 AM, Kornelius Aaron Sneed was born at our home in McKinney, Texas. Our daughter Karisma was also born at home, but this time we planned to have a home birth.  We had been a bit nervous because an ice and snow storm had stranded us in our home for several days beforehand, and a snow storm was forecast to hit town Tuesday evening.  We needed for the midwife to be able to get to us, which might not have been possible had a snow storm made the roads impassable.  (Here in Dallas they generally don’t plough the roads after it snows, because it usually only happens once or twice each year and often melts within a day.)  My wife Zuzana spent Monday decorating our guest room and we went out for a date night that evening.  Soon after that she started having contractions.  I went to sleep about 10 pm, and she labored on her own, careful to stay in another room so she wouldn’t wake me up.  I wouldn’t zuzanahave minded waking up, of course, but she wanted to be considerate of me because I had come down with a bad cold.  Well, about 3 am Tuesday morning I did wake up because she had gone into the bathroom off our bedroom to take a shower.  It turned out it wasn’t long before she was going to have the baby!  We called the midwife and explained what was happening.  I was groggy and not fully awake, but I gathered that Zuzana was fairly close to giving birth and asked the midwife to come over as quickly as possible.  Just at that moment, Zuzana exclaimed that she felt the urge to push. I lit some candles (don’t ask me why, Zuzana just asked me to do it), filled the bathtub partially with some water, and guided the midwife as she drove to our home.

midwifeIt was about a 20 minute drive normally, but there is some construction going on the main highway near our house, and the midwife had a hard time navigating around it.  I went out to the garage to open it and turned on the light as a signal for her to find our house.  I thought to myself, “Here we go again!”  The midwife arrived in time to catch the baby, and once Kory arrived, she took care of everything, caring both for Zuzana and the baby.  I snapped the above picture of Kory.  This is the first time we planned to have a home birth and I’m so very glad we did.  The Allen Birthing Center was extremely professional and supportive, and the experience was so much more “homey” than a hospital birth. The midlife, Leslie, and her assistant did an outstanding job. Both Mom and baby are healthy and happy (and Daddy too!). Smile

Posted in Personal | 1 Comment

Using Open Source? Get NuGet.

nugetMy friend and fellow DevelopMentor instructor, Michael Kennedy, just turned me on to the NuGet Package Manager, a very cool way to install and use open source software right from within Visual Studio.  Let’s say you use one or more open source projects, such as my Simple MVVM Toolkit or NHibernate.  Instead of manually downloading and installing the software, if you’ve installed NuGet (from the Extension Manager) you can open a Visual Studio project, right click on references and select “Add Library Package Reference.” NuGet will add the required references, and also references to all dependent assemblies (including other open source projects), as well as additional content, such as templates, code snippets and transforms to app.config or web.config.  Scott Hanselman has a nice article on NuGet (back when it was still called NuPack), and Michael Kennedy has a list of killer open source projects he found on the NuGet Gallery.

NuGet uses the xcopy model or deployment, as opposed to the msi installer model. That means, instead of referencing assemblies from the Global Assembly Cache (GAC), each application has its own private copy of referenced assemblies.  This means you can install a new version without affecting apps using an older version (a problem sometimes referred to as DLL Hell). Packages installed with NuGet are scoped at the level of the Visual Studio project.  So everything you need is installed right there.  A package can target more than one version of the .NET Platform, and NuGet will install the correct version for the Visual Studio project’s target platform.

To get started with NuGet you should install it via the Extensions Manager dialog from within Visual Studio (Tools / Extension Manager).

nuget-install

After you’ve got NuGet, you can right-click on References and you’ll see an open to “Add Library Package Reference,” at which point you’ll be presented with a dialog that lets you search for open source projects on the NuGet Gallery.  For example, searching for the “mvvm” tag you’ll find three packages for Simple Mvvm Toolkit: Silverlight, WP7 and WPF.

nuget-mvvm

After clicking Install and closing the dialog, you’ll see that required references have been added.

nuget-refs

As well as content files.  For example, the package for my Simple MVVM Toolkit adds a readme.txt file, templates, code snippets, source code, and a small sample app.

nuget-after-install

Instructions in the readme file will explain how to add the code snippets and Visual Studio item templates.  If you’ve already done this, you can simply delete them from the project.  And if you want to, you can unzip and add the source code project (under source), add it to the solution, and add a project reference to it.

Unfortunately, NuGet does not perform automatic updates to packages.  So if you want to see if there is a new version, you need to right-click on the References node, select “Add New Package Library Reference,” then click the Updates node on the left to see if there is an update to the packages you’ve installed in the current Visual Studio project.  If so, just click the Update button and both the references and content files will be replaced.

nuget-update

I spent the better part of the weekend figuring out how to contribute packages to the NuGet online gallery.  Phill Haack has a great post on how to do this.  Here are the steps I followed:

1. Install NuGet from CS Tools/Extension Manager

2. Install NuGet command line
   – Create a new VS project, right-click on References,
     select Add Library Package Reference
   – Search for nuget, select NuGet.CommandLine and install
   – Right-click on the project and select Open Folder in
     Windows Explorer
   – NuGet.exe to where it makes sense – for ex:
     c:\program files\nuget\nuget.commandline
   – Edit Path environment variable to add the folder path
     > Windows start menu, right-click computer, properties,
       advanced system settings, environment variables,
       select PATH system variable to edit, paste ; then path
   – Should be up-to-date, but next time running the cmd line
     you can type: nuget update to install updated version

3. Create a folder to contain package
   – Add libs folder for binaries
     > Can contain framework-specific folder, for ex, net40, sl4
     > Presently there is no client profile support, so you need
       a separate package for wp7 or other client profiles
   – Add content folder for other files (snippets, templates, etc)
   – Add xxx.nuspec file with xml like so:

<?xml version="1.0" encoding="utf-8"?>
<package>
  <metadata>
    <id>MyGreatOpenSourceProject</id>
    <version>0.0.0.1</version>
    <authors>John Doe</authors>
    <owners>John Doe</owners>
    <description>What your project is all about</description>
    <iconUrl>http://yourwebsite.com/icon.png</iconUrl&gt;
    <projectUrl>http://greatstuff.codeplex.com</projectUrl&gt;
    <licenseUrl>http://greatstuff.codeplex.com/license</licenseUrl&gt;
    <tags>tag1 tag2</tags>
    <language>en-US</language>
  </metadata>
</package>

4. Open a cmd prompt, go to the dir where nuspec file, lib & content
   are located, then enter following:
   nuget pack mygreatstuff.nuspec
   – you should get a .nupkg file in that location

5. Create an account at nuget.org
   – They will need to manually approve your registration
   – Click Get Started under Add New Package
   – Go through the steps to add the package

I also spent quite a bit of time writing a good old fashioned batch file with commands to copy files into the package structure.  Now that I’ve got it all automated, building NuGet packages is a breeze.

Posted in Technical | Tagged , | 2 Comments

Simple MVVM Toolkit: Feature Rich with WPF and WP7 Support

I’ve rounded out the feature set of my Simple MVVM Toolkit to include a Message Bus (also known as an event aggregator or mediator) for loosely coupled communication among view-models and to support MEF (Managed Extensibility Framework0 for dependency injection (also known as inversion of control) of service agents to better enable unit testing of view-models.  I’ve included in the download sample applications for these features, including how to drive page navigation from business logic in view-models with command-binding.  I’ve also updated the online documentation to cover these features.

On top of all that I’ve also added support for both WPF (Windows Presentation Foundation) and WP7 (Windows Phone).  Now you can use the toolkit with basically any kind of MS UI platform.

I’d like to emphasize once again that, while the toolkit includes every feature you need to develop robust UI applications using the MVVM design pattern, the approach I’ve taken focuses on simplicity and ease of use.  In other words, I’ve designed the toolkit to help you get up and running with MVVM as quickly as possible without chasing your tail pursuing things like zero code-behind or completely concealing the model from the view.  For this reason I have provided over half a dozen sample applications, each with step-by-step instructions, including a real-world end-to-end sample that uses WCF and Entity Framework.

What’s next?  I would like to complete another version of the end-to-end sample in order to futher demonstrate using the Message Bus with page navigation and dependency injection for unit testing.  Then I intend to provide a sample of using the toolkit with WCF RIA Services.

Posted in Technical | Tagged , , , , | Leave a comment

Easier Async for Silverlight Apps using MVVM

It makes sense to execute long-running tasks on a background thread, in order to keep the UI responsive by not tying up the main thread.  However, as is the case with other UI frameworks such as Windows Forms or WPF, you should not touch UI elements from worker threads. This has to do with how Windows apps process messages, which are always handled on the thread that created the visual element.

There are various mechanisms available for you to marshal a call from a worker thread back to the main thread.  Windows Forms has the Control.InvokeRequired / Control.BeginInvoke API.  WPF and Silverlight have Dispatcher.CheckAccess / Dispatcher.BeginInvokeSynchronizationContext has a Post method that offers a higher level of abstraction, checking access and marshaling invocation at the same time.  And the BackgroundWorker component lets you write events handlers that are executed on the UI thread when reporting progress or completion.

The problem all these approaches is that they require you to write code. Smile  It would be nice if there were some framework that took care of the grungy details of cross-thread marshaling so you can focus on the business logic.  Well, it just so happens that my Simple MVVM Toolkit offers support for async execution right out of the box.  For example, whenever you fire NotifyPropertyChanged from the setter in a view-model property, you should check to make sure that you’re on the UI thread and, if not, marshal the call over to the UI thread.  That way, you won’t get an error when the binding handles the PropertyChanged event.  The NotifyPropertyChanged method in ViewModelBase takes care of this for you by calling an InternalNotifyPropertyChanged method that guarantees the event will always be fired on the UI thread.

public static void InternalNotifyPropertyChanged(string propertyName, 
    object sender, PropertyChangedEventHandler propertyChanged)
{
    if (propertyChanged != null)
    {
        // Always fire the event on the UI thread
        if (Deployment.Current.Dispatcher.CheckAccess())
        {
            propertyChanged(sender, 
                new PropertyChangedEventArgs(propertyName));

        }
        else
        {
            Deployment.Current.Dispatcher.BeginInvoke
                (() => propertyChanged(sender, 
                    new PropertyChangedEventArgs(propertyName)));
        }
    }
}

Similarly, the issue of cross-thread calls rears its ugly head whenever you fire an event from the view-model that is handled by the view, for example, to alter the UI or display a ChildWindow.  To shield you from those details, ViewModelBase has a set of Notify methods which support two-way communication between the view-model and view, but they call an InternalNotify method that marshals the call to the UI thread if needed.

protected void Notify
    (EventHandler<NotificationEventArgs> handler, 
    NotificationEventArgs e)
{
    if (handler != null)
    {
        InternalNotify(() => handler(this, e));
    }
}

protected void Notify<TOutgoing>
    (EventHandler<NotificationEventArgs<TOutgoing>> handler, 
    NotificationEventArgs<TOutgoing> e)
{
    if (handler != null)
    {
        InternalNotify(() => handler(this, e));
    }
}

protected void Notify<TOutgoing, TIncoming>
    (EventHandler<NotificationEventArgs<TOutgoing, 
    TIncoming>> handler, NotificationEventArgs
    <TOutgoing, TIncoming> e)
{
    if (handler != null)
    {
        InternalNotify(() => handler(this, e));
    }
}

private void InternalNotify(Action method)
{
    // Always fire the event on the UI thread
    if (Deployment.Current.Dispatcher.CheckAccess())
    {
        method();

    }
    else
    {
        Deployment.Current.Dispatcher.BeginInvoke(method);
    }
}

An example of where you might want to use the Notify method is if you have the need to prompt the user for input in the course of executing a long-running task on a background thread.  The tricky part is halting execution while waiting for a response, then resuming execution after receiving the response.  Your friend here is a synchronization device like AutoResetEvent.  The following is a section of code from a view-model that kicks off a worker thread to execute a for loop, prompting the user to halt or continue when reaching a certain threshold.

public class MainViewModel : ViewModelBase<MainViewModel>
{
    // Events to notify the view or obtain data from the view
    public event EventHandler<NotificationEventArgs<bool, bool>>
        MaxReachedNotice;

    // Perform work asynchronously
    public void DoWork()
    {
        // Spin up a thread
        Thread worker = new Thread(InternalDoWork);
        worker.Name = "My Worker Thread";
        worker.Start();
    }

    private void InternalDoWork()
    {
        // Cancelled flag
        bool cancelled = false;

        // Max reached flag
        bool maxReached = false;

        // Wait handle
        var wait = new AutoResetEvent(false);

        // Flip IsBusy
        IsBusy = true;

        // Do the work
        for (int i = 0; i < Iterations; i++)
        {
            // Pause
            Thread.Sleep(500);

            // Calc value
            int val = (i + 1) * 10;

            // Notify view if we've reached the max
            if (val >= max && !maxReached)
            {
                var ea = new NotificationEventArgs<bool, bool>
                    (null, true, cancel =>
                    {
                        // Set cancelled and signal wait handle
                        cancelled = cancel;
                        wait.Set();
                    });
                Notify<bool, bool>(MaxReachedNotice, ea);

                // Here we want to pause for the user
                wait.WaitOne();

                // Set max reached
                maxReached = true;

                // Exit loop if cancelled
                if (cancelled) break;
            }

            // Set Result
            Result = val;
        }

        // Flip IsBusy
        IsBusy = false;
    }
}

Notice that the Notify method takes event args that include a callback, which is specified using a lambda expression in which we set a cancelled flag and then signal a wait handle.  Execution of the loop is paused until the wait handle is signaled.  The code-behind for the view simply subscribes to the view-model’s OnMaxReachedNotice event and handles it by displaying the QueryUserDialog, invoking the Completed property of the events args, which tells the view-model whether or not to continue iteration.

public partial class MainPage : UserControl
{
    // Reference view model
    MainViewModel viewModel;

    public MainPage()
    {
        // Get model from data context
        viewModel = (MainViewModel)LayoutRoot.DataContext;

        // Subscribe to notifications from the model
        viewModel.MaxReachedNotice += OnMaxReachedNotice;
    }

    void OnMaxReachedNotice(object sender, 
        NotificationEventArgs<bool, bool> e)
    {
        QueryUserDialog dialog = new QueryUserDialog();
        dialog.Closed += (s, ea) =>
        {
            // Set the flag
            e.Completed(dialog.DialogResult == false);
        };
        dialog.Show();
    }
}

Check out the sample app by downloading the Simple MVVM Toolkit and opening the SimpleMvvm-Async project.

Posted in Technical | Tagged , | 4 Comments

Tackling the Problem of Modal Dialogs in MVVM

One of the first issues you’ll run into when wading into the waters of MVVM is how to display model dialogs to the user while executing code in the view-model.  Popping up a dialog, such as a MessageBox or a ChildWindow, from the view-model is an anti-pattern that violates the separation of concerns that exists between the view and the view-model.  One of the main benefits of MVVM is better application maintainability. If you separate concerns of presentation (the view) from business logic (the view-model) and data (the model), making a change in one area is less likely to impact other areas.  Another benefit is testability.  It is notoriously difficult to test the user interface by simulating things like button clicks and mouse overs.  Encapsulating functionality into a view-model means that you can test it independently of the view, which is just another consumer of the view-model.  If you were to display a dialog from the view-model in order to get input from the user, it would be impossible to run a unit test against the view-model because there’s no way for a unit test to respond to the dialog.  In addition, MVVM promotes better workflow between designers and developers.  Designers can wire up actions to elements straight from the XAML.  Some code-behind may still be necessary, but it should be restricted to view-related activities, such as starting and stopping animations or communicating with the user via messages or dialogs.

In response to these arguments I’ve heard it said, “We don’t have designers, and I don’t care about testability or maintainability.”  In this case, the answer is simple: don’t use MVVM! If all you care about is quickly building an app, then just use code-behind and forget about MVVM, even if everyone else is doing it.  Better not to use MVVM than sabotage it by taking shortcuts.

OK, so let’s say I’ve convinced you not to display dialogs from the view-model.  How do you go about obtaining information from the user from a method that resides in the view-model?  One approach is to define a dialog service interface.  The problem I have with this method is that it feels too tightly coupled to me.  This is typical of interfaces in general. The view-model needs to hold onto a reference to the object implementing the interface, and classes must implement all members of the interface even the ones they may not care about.  Another approach is to use a message bus to handle all communication between view and view-model.  This feels to loosely couples to me.  I can appreciate the need for a mediator to pass messages between various view-models (and I plan to add this feature to my toolkit), but the view already holds a reference to the view so decoupling them seems pointless to me.

In my Simple MVVM Toolkit I advocate what I like to call “goldie locks” coupling: not too tight, not too loose.  The answer is to use an event-based communication model.  Events have finer granularity than interfaces because subscribers can pick and choose which events to subscribe to, and the publisher is relieved from the burden of maintaining direct references to subscribers.  In addition, the view-model is not aware that it’s displaying a dialog – it just needs some data from somewhere and doesn’t care who provides it or how it’s obtained.  Using events also alleviates the need for an intermediary such as a message bus.  Because the view already has a reference to a view-model, it can easily subscribe to events and specify a callback method.  In the callback the view can show information to the user and get a response in any way it wants.

Let’s say you want to notify the user if there is an exception in your view-model. You may want to display a message box or set the content of a label control on the view.  Doing so directly from the view-model would violate the separation of concern and tightly couple the view to the view-model, at the same time making the view-model untestable.  To inform the view that you want to notify it of an error all you have to do is expose an event on your view-model and let the view subscribe to it.  It’s customary to use the built-in EventHander<T> delegate type, where T is a class that extends EventArgs.  My toolkit has a NotificationEventArgs type for just this purpose. It has a single Message property of type string.

public class NotificationEventArgs : EventArgs
{
    public string Message { get; protected set; }
}

There is also a generic version of NotificationEventArgs that allows you to send along an outgoing payload, which the subscriber can consume.

public class NotificationEventArgs<TOutgoing> : NotificationEventArgs
{
    public TOutgoing Data { get; protected set; }
}

Your view-model simply exposes an event as an EventHandler<NotificationEventArgs>, then fires the event when it wants to communicate with external parties, such as a view or unit test.

public class ProductListViewModel
{
  public event EventHandler<NotificationEventArgs
    <Exception>> ErrorNotice
    
  private void ProductsLoaded(List<Product> entities,
    Exception error)
  {
    if (error != null && ErrorNotice != null)
    {
      ErrorNotice(this, new NotificationEventArgs<Exception>
          ("Unable to retrieve products", error));
    else
      Products = entities;
    }
  }
}

The view can subscribe to the ErrorNotice event with a method that, for example, shows a message box or dialog of some sort.

public partial class ProductListView : UserControl
{
  ProductListViewModel model;

  public ProductListView()
  {
    InitializeComponent();

    // Get model from data context
    model = (ProductListViewModel)DataContext;

    // Subscribe to notifications from the model
    model.ErrorNotice += OnErrorNotice;
  }

  void OnErrorNotice(object sender, 
    NotificationEventArgs<Exception> e)
  {
    // Show user message box
    MessageBox.Show(e.Message, "Error", MessageBoxButton.OK);

    // Trace error information
    Debug.WriteLine(e.Data.ToString());
  }
}

This shows how the view-model can communication information to the view in a loosely coupled manner.  But what if you need to obtain information from the user that the view-model needs in order to proceed? The way to accomplish this is with a callback parameter in NotificationEventArgs where you can process the user response, which could be anything from a boolean (for example in the case of a delete confirmation) to the result of a child window.  This plays nice with the asynchronous nature of dialogs in Silverlight, which are not truly model as they are in WPF or Windows Forms (this is because you can’t rely on the Windows message pump in a cross-platform framework such as Silverlight).

Here is an example of a event fired by the view-model to indicate that a particular product is available for order. It exposes an event with a NotificationEventArgs that takes two type arguments, both boolean, for outgoing and incoming data.  The view-model needs to send a boolean value to the view indicating whether or not the product is available, and the view needs to reply with a boolean value indicating whether the user wishes to order the product.

public class ProductListViewModel 
  : ViewModelBase<ProductListViewModel>
{
  public event EventHandler<NotificationEventArgs<bool, bool>> 
    ProductAvailableNotice;

  private void ProductAvailable(bool available)
  {
    // Notify view that product is available
    if (ProductAvailableNotice != null)
    {
      ProductAvailableNotice(this, 
        new NotificationEventArgs<bool, bool>
        (null, available, PlaceOrder));
    }
  }

  private void PlaceOrder(bool confirm)
  {
    if (confirm) serviceAgent.OrderProduct();
  }
}

This version of NotificationEventArgs also has a Completed event, which is an Action<TIncoming> and can be set in the constructor.  That’s the secret sauce of allowing the view to communicate a response back to the view-model, thus enabling two-way communication between the two.  In this example, we are calling OrderProduct on the service agent if we received a confirmation from the user.

public class NotificationEventArgs<TOutgoing, TIncoming> 
    : NotificationEventArgs<TOutgoing>
{
    // Completion callback
    public Action<TIncoming> Completed { get; protected set; }
}

In this case we wish to prompt the user by displaying a ChildWindow with a message that shows the product name and asks the user to click either the Yes or No button.  After receiving a response, we will execute the callback passed to the view in the NotificationEventArgs parameter.

void OnProductAvailableNotice(object sender, 
    NotificationEventArgs<bool, bool> e)
{
    // Product is available
    if (e.Data)
    {
        // Show OrderProductView
        OrderProductView orderProductView = new OrderProductView();
        var orderProductVm = (OrderProductViewModel)
            orderProductView.DataContext;
        orderProductVm.Product = model.SelectedProduct;
        orderProductView.Closed += (s, ea) =>
        {
            if (orderProductView.DialogResult == true)
            {
                // Notify view model to order product
                e.Completed(true);
            }
        };
        orderProductView.Show();
    }
    else
    {
        MessageBox.Show("Product is unavailable.",
            "Product Availability", MessageBoxButton.OK);
    }
}

Notice how we invoke the event args Completed event in the Closed event of the dialog if the user clicked the Yes button, which sets the DialogResult of the ChildWindow to true.  We now have full two-way loosely-coupled communication based on events.  Using events keeps the view-model UI-agnostic and fully testable. And because views and view-models are generally paired, there’s no need in this case for an event mediator or message bus.

For the full source code to this example, just download the latest version of my Simple MVVM Toolkit and open up the solution in the SimpleMvvm-Main folder in the Samples directory.

Posted in Technical | Tagged , | 25 Comments

Type-Safe Two-Way Data Binding with INotifyPropertyChanged

Anyone who’s developed a UI application using Windows Forms, WPF or Silverlight is probably aware that you have to implement the INotifyPropertyChanged interface to get two-way data binding between UI elements and an underlying data source. The problem is that you have to pass the name of the property as a string when you fire the event from each property setter. In this post I will show you a better way, namely, how you can use lambda expressions instead of strings to pass the property name.  That way, the compiler will check that the property name matches a valid property on the class, which will prevent your data bindings from breaking should you change a property name on your class and forget to update the property changed argument.  My Simple MVVM Toolkit provides base classes that include convenient helper methods for firing the PropertyChanged event in a type-safe manner.  You can download the code for this blog post here.

For example, let’s say you have a Person class with Name and Age properties.

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

And you want to bind it to a XAML page that has two textboxes.

<Grid x:Name="LayoutRoot" Background="White"
        Height="150" Width="300">
    <Grid.DataContext>
        <my:Person Name="John" Age="20"
            xmlns:my="clr-namespace:TypeSafeTwoWayDataBinding"/>
    </Grid.DataContext>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <sdk:Label Content="Name:" />
    <sdk:Label Content="Age:" Grid.Row="1"/>
        
    <TextBox Grid.Column="1" Height="30" 
                Text="{Binding Path=Name, Mode=TwoWay}"/>
    <TextBox Grid.Column="1" Grid.Row="1" Height="30" 
                Text="{Binding Path=Age, Mode=TwoWay}"/>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"
                Grid.Row="2" Grid.ColumnSpan="2">
        <Button Name="showPersonButton" Margin="5"
            Height="30" Width="100" Content="Show Person" 
            Click="showPersonButton_Click" />
        <Button Name="birthdayButton" Margin="5"
            Height="30" Width="100" Content="Birthday" 
            Click="birthdayButton_Click" />
    </StackPanel>
</Grid>

The XAML looks like this in the Visual Studio designer:

person-page_thumb11

In the button click of “Show Person” you display a message box with Person Name and Age, and in the click of “Birthday” you increment Person Age.

private void showPersonButton_Click(object sender, RoutedEventArgs e)
{
    Person person = (Person)LayoutRoot.DataContext;
    MessageBox.Show(person.Name + " " + person.Age);
}

private void birthdayButton_Click(object sender, RoutedEventArgs e)
{
    Person person = (Person)LayoutRoot.DataContext;
    person.Age++;
}

If you were to run the app and click the Birthday button you would not see the value in the Age textbox increase, even though clicking the Show Person button reveals that the age has indeed increased. The reason for this is that Person needs to inform the binding that the Age property has changed so that it can get the new value.  This is accomplished by implementing INotifyPropertyChanged on Person and firing the PropertyChanged event in each property setter.

public class Person_Bad : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string name;
    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            if (PropertyChanged != null)
                PropertyChanged(this,
                    new PropertyChangedEventArgs("Name"));
        }
    }

    private int age;

    public int Age
    {
        get { return age; }
        set
        {
            age = value;
            if (PropertyChanged != null)
                PropertyChanged(this,
                    new PropertyChangedEventArgs("Age"));
        }
    }
}

As you can see, this requires a lot of repetitive code and the use of strings is error-prone. If you were to change the property name and forget to update the string, the bindings would break without even the benefit of a runtime exception. To solve this, it’s possible to write a helper method that accepts a lambda expression instead of a string.  When a lambda is assigned to an Expression<T> the compiler generates an expression tree instead of a delegate.  Expression trees are simply a representation of code as data, usually in order to transform it to something else.  In this case that something else would just be the name of the property. A convenience place for this helper method is in a base class, which can also check to make sure the PropertyChanged event is not null.

public class ModelBase<TModel> : INotifyPropertyChanged
{
    // Allows you to specify a lambda for notify property changed
    public event PropertyChangedEventHandler PropertyChanged;

    // Defined as virtual so you can override if you wish
    protected virtual void NotifyPropertyChanged<TResult>
        (Expression<Func<TModel, TResult>> property)
    {
        // Convert expression to a property name
        string propertyName = ((MemberExpression)property.
            Body).Member.Name;

        // Fire notify property changed event
        InternalNotifyPropertyChanged(propertyName);
    }

    protected void InternalNotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, 
                new PropertyChangedEventArgs(propertyName));
        }
    }
}

We can then refactor our Person class to call NotifyPropertyChanged in each property setter. The really nice thing about this is that the compiler is smart enough to infer TModel and TResult type arguments, which makes the code much cleaner.

public class Person : ModelBase<Person>
{
    private string name;
    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            NotifyPropertyChanged(m => m.Name);
        }
    }

    private int age;
    public int Age
    {
        get { return age; }
        set
        {
            age = value;
            NotifyPropertyChanged(m => m.Age);
        }
    }
}

Lastly, the toolkit also comes with a code snippet that inserts the property code and includes the call to NotifyPropertyChanged.  So all you have to do is type mvvmprop, then hit the tab key to expand the snippet.  Then just type content for each field as you tab through the snippet replacements for the property type, field name, property name, and lambda parameter name.

mvvmprop-before_thumb3

mvvmprop-after_thumb3

You now have properties that fire PropertyChanged in a type-safe manner for robust two-way data binding on your model classes.  The toolkit provides this support for view-models as well.  In a prior post I also described an AssociateProperties method that will link property notifications for two properties together, for example, a property in the view-model that is dependent on one or more properties in the model.  In a future post I’ll discuss the asynchronous support provided by the toolkit, which ensures that PropertyChanged always fires on the UI thread if you are updating properties or firing notification events from a background task running on a worker thread.

Posted in Technical | Tagged , | 13 Comments

Simple MVVM Toolkit Improvements: Documentation, Features, Sample Apps

I’ve released a new version of my Simple MVVM Toolkit for Silverlight that has improved documentation, a bunch of new features and additional sample applications.  The emphasis of the toolkit is simplicity – not in the sense that it’s rinky-dink – but in the sense that simple designs are a) concise and elegant, b) easier to learn and understand, c) easier to build and maintain, and d) more robust because there are fewer moving parts.  In fact, I would be so bold as to say my toolkit probably has more features than other toolkits (such as the very popular MVVM Light Toolkit by Laurent Bugnion).  And many of those other toolkits are woefully lacking in the way of documentation and code samples. My toolkit is also targeted to Silverlight applications (although I plan to add Windows Phone support shortly), because Microsoft has positioned Silverlight as its primary platform for business application development.

The initial version of my toolkit includes the following features:

    • Helper classes, Visual Studio templates, code snippets
    • Sample applications with step-by-step instructions
    • Model and ViewModel base classes
    • Strongly typed data binding with lambda expressions
    • View-model locator service
    • DelegateCommand based on ICommand
    • AssociateProperties method to link view-model and model properties
    • Event-based facility for two-way communication between views and view-models (useful for getting user input via modal dialogs)
    • IEditableDataObject support with deep cloning
    • Conversion of enums to lists for populating combo boxes
    • Async support with transparent marshaling to the UI thread

One of my main goals is that you can use the toolkit as a way to learn how to implement the MVVM design pattern for building more robust and maintainable Silverlight applications. I have spent quite a bit of time fleshing out documentation for the toolkit, and the download includes several sample applications. The documentation has a Getting Started section that walks you through building your first Silverlight MVVM app with the toolkit, and there’s a sample app that goes with it, which you can use to follow along.  Other sample apps demonstrate features such as enum lists, associated properties, and async support.  And there’s a main sample that explores all the other features of the toolkit with an end-to-end application that connects to a WCF service with a backend database.

The toolkit has only been out for 3 weeks and there have already been 179 downloads so far, which is a good sign that there’s a need out there for an approach to MVVM that’s easy to understand and use.  I’d especially like to thank Jeremy Alles for listing the toolkit in this Mvvm Frameworks listing.

Posted in Technical | Tagged , | Leave a comment

MVVM: Simple is Beautiful

It’s been a few weeks since I published the Simple MVVM Toolkit for Silverlight on CodePlex. Since that time I’ve fleshed out the documentation, which includes installation instructions and a programming reference.  I’ve also published an update that includes some additional helper methods and samples.  As I stated in my initial blog post, there are numerous approaches to implementing the Model-View-ViewModel pattern.  And while MVVM offers addresses issues such as maintainability, testability and designability – features required by any large scale Silverlight application – you should not attempt to implement MVVM without the aid of an MVVM toolkit.  A toolkit will usually include one or more base classes that provide support for things like data binding and async, and have a mechanism displaying modal dialogs, as well as a facility for locating view-models.

So the problem now is which toolkit to choose! That means you have to survey the half dozen toolkits that support Silverlight, compare their features, supporting documentation and samples, and then spend time learning how to use the toolkit.  All of this assumes you are already familiar with MVVM, which has its own learning curve and requires familiarity with basic aspects of Silverlight, such as XAML, data binding and commands. What’s a developer to do?

It was to address conundrum that I developed the Simple MVVM Toolkit for Silverlight.  Rather than try to compete with existing toolkits by including a bunch of features you might not even use, I decided to provide a core set of features that every MVVM application needs and to favor simplicity and pragmatism over architectural purity.  I also designed the toolkit to be a learning device for developers coming up to speed on Silverlight and MVVM, so the toolkit comes both with online documentation and a comprehensive sample application that has “before” and “after” versions and a ReadMe file with step-by-step instructions (I also intend to publish a screencast).

I want to emphasize how important it is to keep things simple.  A simple design requires greater forethought but is easier to learn and maintain.  A good example is deciding whether to bind the view to model entities or to completely encapsulate the model within the view-model.  At first glance it might appear that encapsulation would be a better design choice.  But it depends on how much control you have over the model.  If you are handed a pre-existing set of classes for your model, then wrapping the model in the view-model might make sense.  In this case you would create a property in your detail view-model for every property in your model that you want to expose.  That way, your view-model can look quite different than your model, perhaps aggregating several model classes and converting properties to what the view needs.

However, you need to keep in mind that this level of indirection comes at a price.  It means you have to replicate a lot of properties in your view-model that are identical to those of the model, which may not make very much sense if your model classes are not pre-defined and you do have control over their look and feel.  In fact, I would argue this is probably a more common scenario, especially if you are using a code-generation tool, such as a T4 template or a RIA Services domain context.  In this case it would make more sense to expose your model as a property on your view-model and let the view bind directly to it.  And this is the approach I take in my toolkit, which has a ViewModelDetailBase class that has a Model property set to the model that is exposed by the view-model.

This is facilitated by the fact that data binding in Silverlight is smart enough to use a property of a property.  For example, if I have a Customer model and a CustomerViewModel that has a Customer property, I can bind a textbox in the CustomerView like so:

<TextBox Text="{Binding Path=Customer.FirstName, Mode=TwoWay}" />

But let’s say I have a TextBlock that I want to bind to FirstName and LastName concatenated together?  The way to do this is for the view-model to expose a CustomerName property.

public string CustomerName
{
    get
    {
        // Concatenate first and last name
        return string.Format("{0} {1}",
            Model.FirstName, Model.LastName);
    }
}

The problem is that I need to have the TextBlock update when either the Customer FirstName or LastName changes, which means the view-model needs to subscribe to the PropertyChanged events of the model and in turn fire its own PropertyChanged event whenever the FirstName or LastName properties change in the model.  To support this scenario, ViewModelDetailBase has an AssociateProperties method that fires PropertyChanged for a view-model property whenever a model property changes.  To use it, all you have to do is call it from the Customer property setter in the view-model.

public class CustomerViewModel

: ViewModelDetailBase<CustomerViewModel, Customer> { public Customer Customer { get { return Model; } set { Model = value; // Associate model and view-model properties AssociateProperties(m => m.FirstName, vm => vm.CustomerName); AssociateProperties(m => m.LastName, vm => vm.CustomerName); AssociateProperties(m => m.IsActive, vm => vm.OrdersVisibility); } }

If you’re curious as to how AssociateProperties works, here’s the source code:

protected virtual void AssociateProperties

<TModelResult, TViewModelResult> (Expression<Func<TModel, TModelResult>> modelProperty, Expression<Func<TViewModel, TViewModelResult>> viewModelProperty) { // Convert expressions to a property names string modelPropertyName = ((MemberExpression)modelProperty.Body).Member.Name; string viewModelPropertyName = ((MemberExpression)viewModelProperty.Body).Member.Name; // Propagate model to view-model property change Model.PropertyChanged += (s, ea) => { if (ea.PropertyName == modelPropertyName) { InternalNotifyPropertyChanged(viewModelPropertyName); } }; }

Enjoy!

Posted in Technical | Tagged , | 12 Comments

Follow Me Everywhere

Here are some places where you can follow what I’m doing:

Twitter: http://twitter.com/tonysneed

Facebook page: http://www.facebook.com/anthony.sneed

I’ve started a Facebook group for people using MVVM with Silverlight: http://www.facebook.com/home.php?sk=group_181987988497920

You-tube: http://www.youtube.com/tonyzuzana

In particular, check out the snowball fight where I get creamed by my two kids.

Enjoy!

Posted in Personal, Technical | Leave a comment

WCF RIA Services Talk

At 6 pm on Thursday January 13th, 2011, I’ll be presenting a talk on WCF RIA Services at the Dallas .NET Developer Group.  Go here to register:

http://ddnug20110113.eventbrite.com

Turbocharge Silverlight Development with WCF RIA Services

Writing a full-fledged Rich Internet Application presents a number of daunting challenges: forced n-tier, async, latency, validation, concurrency, and authentication.  WCF RIA Services simplifies and streamlines the process with support for query composability, change-tracking and batch updates, attributes for presentation and data validation, shared code and async support.  In this seminar Tony will pull back the curtain to show you how RIA Services performs its magic, and he’ll provide tools and techniques to reduce the time and effort required to build Silverlight business applications.

UPDATE: Had a fantastic time with the Dallas dev community.  Here are the slides and code from the talk: http://bit.ly/ddnug-ria

Posted in Technical | Tagged | 2 Comments