Category: Best Practices

Mar 31 2011

Thoughts on WPF / MVVM Tutorial

Yesterday I spent a couple of hours going through Karl Shifflet’s In the Box Training for WPF / MVVM.  There is a lot of great things I could say about In the Box format for developer training but for today it will have to suffice to say that it is awesome—mostly because it directly integrates with Visual Studio.  

And Karl REALLY knocked himself out with the content.  Except for a few reasonable WPF pre-reqs, this is “ground-zero” training that does not presume on anything.  

I just wanted to documents some takeaways and thoughts on what I learned so that next time I do  the content (I will very likely go through this training multiple times) I won’t be starting over each time.

I thought I would present this in the form of a brass tacks bulleted/ordered list of the steps I would take to complete an MVVM application.

WARNING – these instruction are ultimately WAY to simplistic and does not represent a REAL way to architect and design an application but should work for me based on what I know.

  • First wireframe your UI / Screens and Interactions using Balsamiq Mockups.
  • Create a WPF project and then create a MainPage view in XAML for each major screen and separate xaml views for each logical component of your UI. 
    • The Views and main form will have “empty” code-behind files except for the boilerplate InitializeComponent().  This is how you know you are doing MVVM instead of a traditional windows app.
    • The bootstrapping of the App will be done later, using an IOC container, in the app startup event after all of the ViewModels are completed .
    • For more on this see the UI Design and Bootstrapping sections of the tutorial.
  • Create your Domain objects.  The classes here are just very simple POCOs (plain old clr objects) with no methods.  I think this is because all of the business logic is in the ViewModel itself.  
    • The POCOs had no methods, only property setters and getters.
    • With the exception of light-weight items used to fill lists, all of the objects inherit from ObservableObject.  ObservableObject is a utility class provided in the tutorial that implements INotifyPropertyChanged which is a core WPF interface for using the WPF property system.
    • For light-weight “listable” items that map to real objects but only have the properties needed to fill the list, you do not need to inherit from Observsable object.
    • If any property members are collections make the collection a generic type of ObservableCollection (i.e. ObservableCollection<Expense> _expenses 😉
    • All of the property setters should call the RaisePropertyChanged method passign the property name as a string argument (i.e. RaisePropertyChanged("Notes") 😉
    • All of the Observable POCO clasess are marked as Serializable.  
    • All of the Observable POCOs had a default constructor with no overloaded cosntructor.
    • The light-weight POCO did have a overloaded constructor that hydrates the object.
  • For data access, create a I<OBECT>Repository interface and a matching class for implementing the interface for each domain object.
    • The interface will have all of your basic DAL stuff.  For example…
    • Event GetById(Guid id);
      Int32 Remove(Event @event);
      Int32 Save(Event @event);
      Int32 GetCount();
      Event Create();

    • The example interface also had a method for getting a collection of light-weight IEnumberable (i.e.  IEnumerable<EventSearchResult> GetSearchResults();)
    • The repository implementation will have a private field that keeps a list of objects of the type (i.e. readonly List<Event> _events;)
    • The constructor of the implementation hydrates the POCOs and adds them to the list.  This is great for swapping out DALs at any time and unit testing.
    • Of course, you add implementation for all of the interface defs.  (I wonder what an implementation that actually hits the database would look like?)
  • Create a ViewModel for each major Screen. 
    • A ViewModel is the DataTemplate for the screen and all of the child views/components of that screen. 
    • The startup event of the application wires the main screens (views) to the ViewModel as the DataTemplate.
    • The ViewModels also inherit from ObservableObject.
    • As needed, the ViewModel contains instances of all relevant Domain POCOs and light-weight POCOs and collectionSleeping half-moon of POCOs as needed..  
    • It may implement properties that track the current or active or selected POCO instance.
    • The ViewModel will also have private, read-only fields that hold references to the repository objects that it needs (readonly IEventRepository _repository;)
    • As with the Domain POCOs, the property setters call the RaisePropertyChanged methods. 
    • Some of the property setters can set the Acive / Selected object (i.e. RecordSelected(value);)
    • View and view model interactions are handled through the create of ICommand objects.  The tutorial provides and implementation of this in the RelayCommand class which is what the ICommand method construct and return.   He goes into some length to explain why he implemented this ICommand instead of using the built-in DelegateCommand.
    • View / ViewModel interactions can also be done by defining “behaviours” in the view but this is not explained or demonstrated in the turtorial.
    • Different strategies for implementing and using ICommands are demonstrated.
    • The tutorial also gives helpful information on how to invoke dialog boxes from the ViewModels. 
    • The ViewModel also implements Can<COMMAND>Execute methods that have to be very fast along with void <COMMAND>Execute methods that interact with the collections and repositories to do CRUD operations on the data.
    • A single ViewModel can serve as the DataTemplate for all of the view and child views/components. 

IMPORTANT – PROBABLY THE MOST important thing to understand and master in the tutorial is the page call View-View Model Interactions.  Maybe a future post will explore that in greater details.  But below are the relevant topics.

EventEditView Bindings

The below XAML snippet from EventEditView.xaml illustrates one technique for binding UI controls to model objects exposed from a view model.

The DataContext for this view is the view model. ActiveEvent is a property on the view model. Each of the controls “dot in” to the property on the model object they want to bind to.

<TextBox Text="{Binding Path=ActiveEvent.Title, Mode=TwoWay}" />

<TextBox Text="{Binding Path=ActiveEvent.Location, Mode=TwoWay}"/>

<DatePicker Text="{Binding Path=ActiveEvent.EventDate, Mode=TwoWay}"/>

<TextBox Text="{Binding Path=ActiveEvent.Notes, Mode=TwoWay}"/>

<DataGrid ItemsSource="{Binding Path=ActiveEvent.Expenses}" .../>

It is also possible to assign the ActiveEvent instance to a parent container’s DataContext like a Grid control and then the child controls would not have to “dot in” since their DataContext root would be the ActiveEvent instance instead of the view model instance.

Commands

The MainWindowViewModel exposes the following five ICommand properties; the EventEditView data binds to those properties.

public ICommand DeleteCommand {

get { return new RelayCommand(DeleteExecute, CanDeleteExecute); }

}

public ICommand SaveCommand {

get { return new RelayCommand(SaveExecute, CanSaveExecute); }

}

public ICommand CancelCommand {

get { return new RelayCommand(CancelExecute, CanCancelExecute); }

}

public ICommand ThrowCommand {

get { return new RelayCommand(ThrowExecute, CanThrowExecute); }

}

public ICommand NewCommand {

get { return new RelayCommand(NewExecute); }

}

<StackPanel Orientation="Horizontal" Grid.Row="5" Grid.ColumnSpan="2">

<Button Content="New" Command="{Binding Path=NewCommand}" />

<Button Content="Save" Command="{Binding Path=SaveCommand}" />

<Button Content="Cancel" Command="{Binding Path=CancelCommand}" />

<Button Content="Delete" Command="{Binding Path=DeleteCommand}" />

<Button Content="Throw" Command="{Binding Path=ThrowCommand}" />

</StackPanel>

Jan 20 2011

Looking for a vertical software vendor? Here is a quiz to separate the first-class from the fly-by-night vendors.

If your company is looking for a big-ticket software vendor and you want to take some early steps to find the right vendor, here is a brief quiz you could give to your candidates.

These are mostly adapted from THE JOEL TEST but I have added some things that are relevant since The Joel Test is pretty out of date.

When interviewing the vendors, set it up so that they would only have an hour or so to answer and return the test (so they can’t fake or fudge the answers.)

I would not expect perfection but on the whole most software shops (by that I mean a company whose primary line of business is selling packaged software) should be doing a lot of what is suggested by the questions.   This “test” would do a good job of separating the first class operations from the fly by night ones.  Even the first class ones that are not doing all of what is here will have strong answers and justifications.  The only way a fly by night one could pass this test is by lying through there teeth.

Speaking of lying through their teeth.  Before making a final decision maybe you should ask to SEE the operation.  Have them show you their environment and step you through the use of their ticket system, or release process, or bug-tracking software.

An irony of the economics of vertical market software is that it is traditionally a LOT more expensive but is actually LESS likely to have quality built-in.   Inexpensive single-purpose software vendors can’t afford to deliver crappy software because the support costs can easily overwhelm the revenue stream.  But vendors that charge $100,000 to &1,000,000 per installation can throw money and people at their problems (and very often bill the costs to their customers.)  I am not saying that all really expensive software is crappy.  But the potential is there so you must tread carefully.

Enjoy.

Here is the quiz.

ABOUT VERSION CONTROL

  • Do you use Source/Version Control?
  • Which Version Control system do you use? 
  • Can your developers that are working  remotely (for example, doing customer customizations) do commits and updates to your version control system (as long as there is a internet connection)?

SOFTWARE BUILDS

  • Can you make a releasable build in one step?
  • Do you make daily builds when you are product is in active development?
  • Do you use a continuous integration system?
  • What do you use for continuous integration?

BUG MANAGEMENT

  • Do you use bug tracking software?  Please describe briefly.
  • What bug tracking software do you use?
  • Do you fix bugs before writing new code? (When working against a schedule do you fix bugs before starting new features?)

METHODOLOGY

  • Do you follow a software development methodology? 
  • What is the name of the methodology you follow?
  • Is it an agile or waterfall methodology?
  • In what ways do you NOT follow the recommendations of your proscribed methodology? 
  • What role do developers play in driving your release schedule (as opposed to managers)?
  • Describe your methodology in two paragraphs or less.

PROGRAMMERS

  • Describe the method you use for hiring developers.  What steps do you try to complete?
  • Describe the working condition of your developers. 
  • How often are developer computers replaced in your company?
  • What do your developers do for professional development?

QUALITY ASSURANCE

  • Do you have in-house testers that are not developers?
  • Can developers close their own tickets in your bug tracking software?
  • Do you do usability testing as part of your UI design process?  Please describe briefly.
  • Do you have in house designers for the UI of your software?

UNIT TESTING

  • Do you use Unit Testing in the development process at your company?
  • Would you say that you use Unit Testing as part of the design process or just to be sure that changes don’t break the build.
  • What is the code coverage of your unit test suites?
Nov 29 2010

StackOverflow question answered by heavy-hitters

I asked a StackOverflow.com question today which was answered by two BIG NAMES in tech….Jon Skeet and Eric Lippert.  Pretty cool.

Aug 12 2010

Differences between Unit Testing Mocks, Fakes, and Stubs

Martin Fowler’s page on the matter is a well-known guide.  Here is how he defines the differences in summary:

  • Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
  • Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
  • Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
  • Mocks are what we are talking about here (the article): objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

Happy Unit Testing

Seth

Aug 11 2010

A simple and appropriate way to handle XML in your applications.

Good post here. Also a little more details here. Seth