# Thursday, 21 May 2009

In my book, I talked a bit about programming by contract and how that makes everyone’s lives easier.  Say I have a method that divides one integer by another

public double Divide(int dividend, int divisor)
{
  return dividend / divisor;
}

I’d like to be able to let callers know that they can’t pass a 0 for the divisor, because that will result in a DivideByZeroException, and nobody wants that.  In the past I had a couple of choices on how to express that, mostly involving writing different kids of code, because C# doesn’t have a native expression of design by contract like Eiffel does.  One way is to use Debug.Assert

public double Divide(int dividend, int divisor)
{
  Debug.Assert(divisor != 0);

  return dividend / divisor;
}

That way any caller that passes a 0 will get an assertion dialog at runtime, which brings it pretty dramatically to everyone’s attention.  The assumption is that using the Debug.Assert will flush out all cases where people are incorrectly calling my method during development, so it’s OK that the assertion will get compiled out of my Release build.  However, that doesn’t make it impossible for a caller to pass a 0 at runtime and cause the exception.  Another option is explicitly checking parameters and throwing a different exception.

public double Divide(int dividend, int divisor)
{
  if (divisor == 0)
      throw new ArgumentException("divisor cannot be zero", "divisor");

  return dividend / divisor;
}

Patrick argues that this has now moved from defining contract to defining behavior, and I can agree with that, although I’d probably argue that it defines both contract and behavior since I’ve extended the functionality of the Debug.Assert to the release build, while also protecting my internal state from bad data.  But that’s really a separate discussion… :)

Now thanks to the Microsoft Code Contracts project, I have a third option.  The Code Contracts project is the evolution of the work done on Spec#, but in a language neutral way.  The Code Contracts tools are currently available from DevLabs for VS 2008, as well as shipping with VS 2010 B 1.  Just at the moment, there are more features in the DevLabs version that what made it into the 2010 beta.  With Code Contracts, I can rewrite my Divide method like this

public double Divide(int dividend, int divisor)
{
  Contract.Requires(divisor != 0);

  return dividend / divisor;
}

I like the syntax, as it calls out quite explicitly that I’m talking about contract, and making an explicit requirement.  The default behavior of this method at runtime is identical to Debug.Assert, it brings up an assertion dialog and brings everything to a screeching halt. However, it’s configurable at build time, so I can have it throw exceptions instead, or do whatever might be appropriate for my environment if the contract is violated.  I can even get the best of both worlds, with a generic version of Requires that specifies an exception

public double Divide(int dividend, int divisor)
{
  Contract.Requires<ArgumentException>(divisor != 0, "divisor");

  return dividend / divisor;
}

I could configure this to bring up the assertion dialog in Debug builds, but throw ArgumentNullException in Release builds.  Good stuff.

The example above demonstrates a required “precondition”.  With Code Contracts, I can also specify “postconditions”. 

public void Transfer(Account from, Account to, decimal amount)
{
  Contract.Requires(from != null);
  Contract.Requires(to != null);
  Contract.Requires(amount > 0);
  Contract.Ensures(from.Balance >= 0);

  if (from.Balance < 0 || from.Balance < amount)
      throw new InsufficientFundsException();

  from.Balance -= amount;
  to.Balance += amount;

}

This isn’t the greatest example, but basically the Transfer method is promising (with the Contract.Ensures method) that it won’t ever leave the Balance a negative number.  Again, this is arguably behavior rather than contract, but you get the point. 

A really nifty feature is that I can write an interface definition and associate it with a set of contract calls, so that anyone who implements the interface will automatically “inherit” the contract validation.  The syntax is a bit weird, but you can see why it would need to be like this…

[ContractClass(typeof(ContractForCalucluator))]
interface ICalculator
{
   int Add(int op1, int op2);
   double Divide(int dividend, int divisor);
}

[ContractClassFor(typeof(ICalculator))]
class ContractForCalucluator : ICalculator
{
   #region ICalculator Members

   public int Add(int op1, int op2)
   {
       return default(int);
   }

   public double Divide(int dividend, int divisor)
   {
       Contract.Requires(divisor != 0);

       return default(double);
   }

   #endregion
}

Now any class that implements ICalculator will have the contract validated for the Divide method.  Cool.  The last thing I want to point out is that the team included a handy sample of how to work with contract validation in your MSTest unit test code.  The Contract class exposes an event called ContractFailed, and I can subscribe to the event to decide what happens on a failure.  For a test assembly, I can do this

[AssemblyInitialize]
public static void AssemblyInitialize(TestContext tc)
{
  Contract.ContractFailed += (sender, e) =>
  {
      e.SetHandled();
      e.SetUnwind();
      Assert.Fail(e.FailureKind.ToString() + " : " + e.Message);
  };
}

which will translate contract failures into test failures with very explicit error messages.  In the case of my Divide method if I run this test

[TestMethod()]
public void DivideContractViolation()
{
  Calculator target = new Calculator(); 
  int dividend = 12; 
  int divisor = 0; 
  double actual;
  actual = target.Divide(dividend, divisor);
  Assert.Fail("Should have failed");
}

I get a test failure of

Test method CalculatorTests.CalculatorTest.DivideContractViolation threw exception:  System.Diagnostics.Contracts.ContractException: Precondition failed: divisor != 0 divisor --->  Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: Assert.Fail failed. Precondition : Precondition failed: divisor != 0 divisor.

Cool.  This is definitely something I’ll be looking at more in the future.

Thursday, 21 May 2009 14:50:38 (Pacific Daylight Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, 20 May 2009

Not this weekend but next (5/30) is PDX Code Camp 2009.  A whole day of free software learning and general nerdy hanging out.  I’ll be talking about building business apps in Silverlight 3, and my SoftSource compadre Tim Johnson is going to be talking about making your web application more accessible for people with disabilities.  There are also a host of other sessions including some big names like Ward Cunningham, so it’s an event not to be missed, and cheap at twice the price!

Wednesday, 20 May 2009 13:45:43 (Pacific Daylight Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  | 

This came up in class yesterday, so I did a little digging.  Everyone may already know this, but it came as news to me. :)

If I’ve got a collection in memory, as well as a LINQ to SQL DataContext

List<FavoriteFood> foods = new List<FavoriteFood>(){
	new FavoriteFood{CustomerID = "ALFKI", Favorite="Chips"},
	new FavoriteFood{CustomerID = "ANATR", Favorite = "Fish"}};

NorthwindDataContext context = new NorthwindDataContext();

and I want to do an INNER JOIN between the foods list and the Customer table in Northwind, it would seem like this should do it

var bad = (from cust in context.Customers
         join f in foods on cust.CustomerID equals f.CustomerID
         select new
         {
             cust.ContactName,
             f.Favorite
         }).ToList();

but sadly, no.

image

if you stop to think about it, it totally makes sense that it wouldn’t work like that, since there’s no way to translate that into SQL in any rational way to send to SQL server. 

OK, so the next step would be to first get the customers in memory, then do the join

//this executes the whole query, thus retrieving the entire customer table
var customers = (from c in context.Customers
             select c).ToList();

//an inner join between the customers from SQL and the in-memory list
var inner = from cust in customers
     join f in foods on cust.CustomerID equals f.CustomerID
     select new
     {
         cust.ContactName,
         f.Favorite
     };

That works, but I’ve had to pull the entire Customer table into memory just to join two rows.  If I wanted to do a LEFT OUTER JOIN, I’d need that anyway, like so

//here's the left outer join between the customer list from SQL 
//and the in-memory favorites
var leftouter = from cust in customers
             join f in foods on cust.CustomerID equals f.CustomerID into custFoods
             from custFood in custFoods.DefaultIfEmpty()
             select new
             {
                 cust.ContactName,
                 Favorite = custFood == null ? null : custFood.Favorite
             };

but I want an inner join without pulling down all the customers, so I need to only fetch those rows that will join from Customer

//this is how you manage the IN clause
var x = from c1 in context.Customers
     where (from cf in foods
           select cf.CustomerID).Contains(c1.CustomerID)
     select c1;

//Note that to join the result in x back to the foods collection you would have to 
//execute the query just like with customers above...
var littleInnerJoin = from filteredCustomer in x.ToList()
                   join f in foods on filteredCustomer.CustomerID equals f.CustomerID
                   select new
                       {
                           filteredCustomer.ContactName,
                           f.Favorite
                       };

It’s two steps, but now I’ve just loaded the rows that will join into memory, and then done the join with LINQ to Objects.  It bears a little thinking about, but doesn’t seem like too much overhead, IMHO.

Work | LINQ
Wednesday, 20 May 2009 13:38:43 (Pacific Daylight Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, 07 May 2009

Let’s say I’ve got to the effort of creating a modal dialog or it’s equivalent in a Silverlight application.  What I would like to complete the picture is a “default” button, so that if I hit the Enter key while in a text box, the dialog will be “submitted”.  There are probably several ways of achieving this end, but I wanted something that was simple, and encapsulated in an attached property so the consumer wouldn’t have to deal with much code.  I wrote the attached property so that I could use it on text boxes like this

<TextBox x:Name="theText" VerticalAlignment="Center" Margin="10,0,10,0" 
	Grid.Row="0" my:DefaultButtonService.DefaultButton="theButton"/>

where “theButton” here is the default button I want to be pressed when the Enter key happens inside my text box.  The downside is that I have to apply this property to every text box on the page, but so be it, that seems like a relatively small price to pay.  So I got as far as finding the named button in the visual tree, but the the question was, how to “press” the button.  The Button class in Silverlight has a protected OnClick that would do the trick, if it wasn’t protected.  I could derive my own control from Button and expose the OnClick method, but ewww.  If I did that then every dialog that wanted this behavior would have to remember to use the derived Button class.  I tried reflecting over the Button and Invoking OnClick anyway, but turns out you get a security exception.  OK.  Then, thanks to a presentation Stuart gave us yesterday on Accessibility, I remembered the Automation framework in Silverlight.  That turned out to be super easy, just create an instance of ButtonAutmationPeer from the Button, then Invoke it.  Cool.

public static class DefaultButtonService
{
   public static readonly DependencyProperty DefaultButtonProperty =
       DependencyProperty.RegisterAttached("DefaultButton", typeof(string), typeof(DefaultButtonService), new PropertyMetadata(OnDefaultButtonChanged));


   public static string GetDefaultButton(DependencyObject d)
   {
       return (string)d.GetValue(DefaultButtonProperty);
   }

   /// <summary>
   /// Sets the CommandParameter property.
   /// </summary>
   public static void SetDefaultButton(DependencyObject d, string value)
   {
       d.SetValue(DefaultButtonProperty, value);
   }

   private static void OnDefaultButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   {
       TextBox tb = d as TextBox;
       if (tb != null)
       {
           tb.KeyUp += new KeyEventHandler(tb_KeyUp);
       }
   }

   static void tb_KeyUp(object sender, KeyEventArgs e)
   {
       switch (e.Key)
       {
           case Key.Enter:
               string name = (string)((DependencyObject)sender).GetValue(DefaultButtonProperty);
               object root = App.Current.RootVisual;
               object button = ((FrameworkElement)root).FindName(name);
               if (button is Button)
               {
                   ButtonAutomationPeer peer = new ButtonAutomationPeer((Button)button);

                   IInvokeProvider ip = (IInvokeProvider)peer;
                   ip.Invoke();
               }
               break;
       }
   }
}
Thursday, 07 May 2009 13:27:54 (Pacific Daylight Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, 07 April 2009

We just added a set of new one day classes starting in May, including “Agile in day”, Silverlight 3, and UI design patterns for WPF and Silverlight.  These are lecture-style classes that will give you an in depth look at each subject.  Like our previous Silverlight event, these are 300-400 level, technical sessions that will give you a leg up on each subject in a day.  Because they are presented lecture style, we can offer them for only $125 each, so feel free to collect the whole set. :-)  Details and registration here.  We may be adding some additional topics soon, so check back often.

Tuesday, 07 April 2009 10:41:19 (Pacific Daylight Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, 19 March 2009
I'll probably have some more cogent things to say about it all in a few days, but my first set of takeaways as of mid-day Thursday:
  • Silverlight 3 solves many if not most of the downsides of working in Silverlight vs. WPF
  • Silverlight 3 + .NET RIA services totally removes any and all barriers to building business apps in Silverlight
  • .NET RIA services is the killer app we’ve been waiting for as far as building RIA apps is concerned.  it’s like Astoria, only better, and doesn’t require Entities (long live LINQ to SQL!). 
  • Blend 3 will revolutionize the way designers and developers work together, and make the design process much faster
  • Free martinis are both a blessing and a curse
  • Having a DJ at your keynotes is a fantastic idea
  • Not only would downtown Hillsboro (where I live) fit inside the Venetian, but you probably wouldn’t actually notice it.
Thursday, 19 March 2009 12:45:58 (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [1]  | 
# Tuesday, 10 March 2009

After logging in, be sure to visit all the options under Configuration in the Admin Menu Bar above. There are 26 themes to choose from, and you can also create your own.

 

Tuesday, 10 March 2009 23:00:00 (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 

I’m building a MVVM app in WPF, and needed to show a modal dialog, but I couldn’t figure out how to make it work and still maintain the separation between ViewModels and Views.  I have been mapping Views to ViewModels using DataTemplates, so that the relationship is declarative in XAML rather than in code someplace.  What I ended up with was a new Window called Dialog that takes a type in its constructor that corresponds to a ViewModelBase-derived type.  (See Josh Smith’s WPF Apps With The Model-View-ViewModel Design Pattern article for background on how the pieces fit together…) 

public partial class Dialog : Window
{
    public Dialog(Type vmType)
    {
        InitializeComponent();

        ViewModelBase vmb = Activator.CreateInstance(vmType) as ViewModelBase;
        
        item.Content = vmb;

        this.Title = vmb.DisplayName;
    }
}

In the XAML for Dialog, there’s just a Grid that contains a ContentPresenter called “item”.  The constructor sets item’s content to be the ViewModel, and the DataTemplate takes care of associating the View (a UserControl) with the ViewModel.  Note the use of SizeToContent="WidthAndHeight" on the Dialog window, which causes the window to resize to how ever big the UserControl that represents the View might be.

<Window x:Class="SomeNamespace.Dialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Dialog" SizeToContent="WidthAndHeight">
    <Grid>
        <ContentPresenter x:Name="item">
            
        </ContentPresenter>
    </Grid>
</Window>
<DataTemplate DataType="{x:Type vm:NewThingViewModel}">
    <vw:NewThing/>
</DataTemplate>

To create an instance of the new modal dialog, I just create a new instance of Dialog and pass the type of ViewModel it’s supposed to host…

new Dialog(typeof(NewThingViewModel)).ShowDialog();

There are still some details to work out as far as getting results from said dialog, but hey, progress…

Tuesday, 10 March 2009 15:36:01 (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, 04 March 2009

So yesterday I was reading Josh Smith’s WPF Apps With The Model-View-ViewModel Design Pattern article in last month’s MSDN magazine, and I really liked the sample app that he built.  It totally cleared up for me some rough edges (in my understanding) of MVVM.  Most specifically, I had been conflicted about where to put things like button click handlers.  Do you put a Click event handler in your codebehind, which just defers to the View Model?  Do you create a generic CommandBinding handler to wire up commands to your View Model’s methods?  (I’ve seen both in various examples…)  The former seems like cheating a bit on MVVM (no code behind would be ideal, it seems to me) and the latter overly complicated.  Josh’s solution is to bind the Command property of the UIElement (button, menu item, whatever) to a property of type ICommand on the View Model. 

That totally made sense to me.  No more code behind (like at all, basically) and I don’t have to build additional framework to make it happen, with the exception of coming up with an ICommand implementation.  Josh solved that with a class he calls RelayCommand, which just wraps an ICommand implementation around a delegate (or lambda) of type Action<object>, with an optional Predicate<object> to handle the CanExecute method of ICommand. 

Groovy, now my XAML knows absolutely nothing about the View Model, and it’s only links to said View Model are through data binding.

Then I got to wondering if something as easy could work in Silverlight…  The answer turned out to be almost, but not quite.  Since Silverlight controls don’t expose a Command property, you have to hook them up yourself, but otherwise it works just the same way.

So if I’ve got a page with a single button on it

CropperCapture[10]

<UserControl x:Class="SilverlightCommands.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:my="clr-namespace:SilverlightCommands"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Button Content="Say Hello..." VerticalAlignment="Center" 
                HorizontalAlignment="Center" 
                my:ButtonService.Command="{Binding Path=SayHello}"/>
    </Grid>
</UserControl>

I can add an attached property whose value is bound to the ICommand property on the View Model.  The attached property grabs the ICommand and hooks up the button’s click handler to the ICommand’s Execute method.

#region Command

/// <summary>
/// Command Attached Dependency Property
/// </summary>
public static readonly DependencyProperty CommandProperty =
    DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(ButtonService),
        new PropertyMetadata(OnCommandChanged));

/// <summary>
/// Gets the Command property.
/// </summary>
public static ICommand GetCommand(DependencyObject d)
{
    return (ICommand)d.GetValue(CommandProperty);
}

/// <summary>
/// Sets the Command property.
/// </summary>
public static void SetCommand(DependencyObject d, ICommand value)
{
    d.SetValue(CommandProperty, value);
}

/// <summary>
/// Handles changes to the Command property.
/// </summary>
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is Button)
    {
        Button b = d as Button;
        ICommand c = e.NewValue as ICommand;
        b.Click += delegate(object sender, RoutedEventArgs arg) { c.Execute(null); };
    }
}

#endregion

In the View Model, then, is the actual handler for the command

public class PageViewModel
{
    public ICommand SayHello
    {
        get
        {
            return new RelayCommand(param => MessageBox.Show("HelloWorld"));
        }
    }
}

Note that I’m using Josh’s RelayCommand helper to wrap the simple lambda.

That feels like not too terribly much infrastructure, although I might have to create separate attached properties to handle different control types (e.g. those that don’t have a Click event).  It would be pretty straightforward to support command parameters in the same way, by creating a CommandParameter attached property and picking up its value in the OnCommandChanged handler…

private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is Button)
    {
        string parameter = d.GetValue(CommandParameterProperty) as string;
        Button b = d as Button;
        ICommand c = e.NewValue as ICommand;
        b.Click += delegate(object sender, RoutedEventArgs arg) { c.Execute(parameter); };
    }
}

The only thing that doesn’t really handle well is the CanExecute method, which in WPF would automatically enable/disable the button based on the result of the ICommand’s CanExecute method.  I tried a couple ways of wiring it up during the OnCommandChanged handler, but couldn’t come up with anything that didn’t look to have nasty side-effect (garbage collection, etc.) or be just ugly.  I’d probably just bind the IsEnable property of the button to a separate boolean on the View Model and deal with it there. 

Update:

Code is here.

Wednesday, 04 March 2009 16:06:59 (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [3]  | 
# Monday, 02 March 2009

Shaun posted a nice concise example of replacing JavaScript code with similar compiled code in Silverlight.  If you have any complex business logic currently written in JavaScript, this would be a great way of turning that into compiled, type-safe C#.

Monday, 02 March 2009 15:08:15 (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |