Category Archives: WPF

Windows Presentation Foundation

Coming around to MVVM

This is a copy-and-paste from an email to a friend, but has a few observations worth sharing publicly

A couple discussions on knockout.js, angular.js and backbone.js:

http://stackoverflow.com/questions/11083316/angular-js-or-knockout-js-integration-with-other-ui-libraries

http://stackoverflow.com/questions/5112899/knockout-js-vs-backbone-js?rq=1

Previously, I didn’t pay much attention to any of these. But am changing my tune. Why? I finally found a way to use the MVVM pattern that really makes sense and plan to follow that when it makes sense with web programming too. Props to Microsoft evangelist Jerry Nixon for his walkthrough video: http://blog.jerrynixon.com/2012/08/most-people-are-doing-mvvm-all-wrong.html, which in particular had some binding tips for Visual Studio I didn’t even know existed and a nice DelegateCommand class.

My initial experience with MVVM was miserable. For one thing, it is incorrectly named…should be MVMV (as in Model – View Model – View). But then, so is MVC, which should be Model – Controller – View. Because in both cases, the View Model or Controller is the code that sits between a UI View and the task-related code, e.g. a method that grabs a bunch of image URLs based on a search term. The MVVM framework I chose to use was complicated and couldn’t handle everything. Lots of hacks went into Ballistica. So, ironically, the promise of better maintainability was so broken that I’ve never found the time to update the app.

I also found that there is a lot of strict adherence to one model per view model. Really a model is just a class file. So if, for example, you need one class that handles status messages and another that build outlines there’s no reason why a single View Model can’t talk to them both. Now that I have that straight and have learned how to use my IDE more effectively, it has made much more sense. My current project has 111 lines of XAML in the main Window (including whitespace), but just 12 lines in its code-behind C# file (including whitespace and curly brackets)…and all it does is launch the window:

using System.Windows;

namespace HorizontalBuilder2
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}

All the controlling logic resides either in the View Model class file or in the model classes.

Here’s an example of XAML that helps explain why Microsoft saw fit to not use SVG:

<MenuItem Command="{Binding BuildOutlinesCommand, Mode=OneWay}" Header="_Build Outlines" InputGestureText="CTRL+B" IsEnabled="{Binding Done, Mode=OneWay}">

<MenuItem.Icon>

<icons:IconGeom />

</MenuItem.Icon>

</MenuItem>

First of all, they could create things like application menus. Then bind various attributes to logical code. In this example, for instance, selecting “Build Outlines” from the menu triggers the BuildOutlinesCommand method. The underscore in front of the Header text allows the user to use ALT-key shortcuts, although I’ve never enjoyed that bit of Windows UI. It’s always just seemed easier to remember something like CTRL-B, which cuts out at least one step, so that’s included. The command is enabled depending on various states of the application. While you can name an item and refer to it in code, e.g. myMenuItem.Enabled = true, one advantage of this way is the menu item is now just a “subscriber” to the Done value. If I had, say, another item on screen like a big “Start” button it to could just use the same snippet. The alternative would be to have to keep track in code of all the items that need to be enabled or not. Also, the programmer can look at the XAML and know where to look in code for what effects the change.

Soon I’ll be posting a nice example of an MVVM app using async Tasks with real-time UI updating…and no freezing the rest of the UI.

Using .NET 4.5 Task Async and Await with WPF and SQL Server

Most of the examples I’ve seen of  using the new async, await and Task methods in .NET 4.5 have been aimed at Windows 8 (Metro or “UI Style”) apps. This is understandable, given Microsoft’s push towards both a new OS and to populate the Windows 8 Store. But for some (many?) developers there is also a need to support both Windows 7 and Windows 8 Desktop. Notably missing from the WinRT scenario is the ability to directly connect to SQL Server. I (mostly) get the reasons for that, although it seems against Microsoft’s interests to cede that space to SQLite instead of a sandboxed, light version of SQL Server.

Anyway, I put together a sample WPF application (download below) that supports asynchronous connections to SQL Server. You can cancel or restart the demo query, which populates a ListView with data from the AdventureWorks DB Production.WorkOrder table, which had a decent number of records for testing. I really wanted to simulate some real world conditions, such as server-side delays, so that’s included too. One of my beefs with many of the samples I come across is that they never include decent error handling, especially to accomodate network latency or timeouts. This sample also includes the Microsoft.Data.ConnectionUI SQL Server connection dialog box.

One advantage of making a WPF app asynchronous is it no longer locks up while running a process. Try dragging the window around while the ListView is being populated with data. Yay, no UI-thread blocking!

Clicking the Start button triggers the StartTest method. Notice that in the query, I’ve embedded an artificial server-side delay of 3 seconds – WAITFOR DELAY ’00:00:03′; – which will simulate a slow server return. Also, a queryTimeout has been set to 120 seconds. If you set the WAITFOR delay longer than that, you will see an error occurs and is handled. I did my best to include specific SQL Server error handling so we get actual error details, rather than just “some crap happened and that’s all we know.”


private async void StartTest(object sender, RoutedEventArgs e)
{
try
{
 if (_connectionString == String.Empty)
 {
 var scsb = new SqlConnectionStringBuilder(Settings.Default.DBConnString);

_connectionString = scsb.ConnectionString;

if (_connectionString == String.Empty)
 {
 throw new Exception("Please use Change DB to first select a server and database.");
 }
 }

if (DbInfo.DbName == String.Empty)
 {
 throw new Exception("Please use Change DB to first select a database from the server.");
 }

// Note: If the start test button was disabled, this would be unnecessary
 _cts.Cancel();

// Re-initialize this. Otherwise, StartTest won't work.
 _cts = new CancellationTokenSource();

DataItemsList.Clear();

// Note the simulated delay, which will happen on the DB server. You can vary this to see its effect.
 // Try dragging the window around after hitting the start test button.
 const string query =
 @"WAITFOR DELAY '00:00:03'; SELECT * FROM [Production].[WorkOrder];";

// Note that setting the WAITFOR delay to exceed this, eg. 00:02:01, will trigger an exception
 int queryTimeout = 120;

RequestStatus = "started";

await ProcessQueryCancelleable(_connectionString, query, queryTimeout, _cts.Token);
}
catch (Exception ex)
{
 MessageBox.Show(ex.Message + " (from StartTest)");

Debug.WriteLine(ex.Message);
}
}

The ProcessQueryCancelleable method. Note the use of the CancellationToken…’cause users might actually want to cancel a long-running query. Inside this method is another simulated delay (await Task.Delay(TimeSpan.FromMilliseconds(1));):

/// <summary>
/// Runs a cancelleable query
/// </summary>
/// <param name="connectionString">SQL Server connection string</param>
/// <param name="query">SQL query</param>
/// <param name="timeout">SqlDataReader timeout (maximum time in seconds allowed to run query). Note: Try varying this in conjunction
/// with the WAITFOR DELAY in the SQL query, e.g. make it shorter than the WAITFOR or maybe a second longer</param>
/// <param name="cancellationToken">Allows cancellation of this operation</param>
/// <returns></returns>
private async Task ProcessQueryCancelleable(string connectionString, string query, int timeout,
 CancellationToken cancellationToken)
{
 // await Task.Delay(TimeSpan.FromSeconds(5));

try
 {
 // Keep sqlConnection wrapped in using statement so disposal is handled automatically
 using (var sqlConnection = new SqlConnection(connectionString))
 {
 await sqlConnection.OpenAsync(cancellationToken);

using (SqlCommand cmd = sqlConnection.CreateCommand())
 {
 cmd.CommandTimeout = timeout;

cmd.CommandText = query;

using (SqlDataReader dataReader = await cmd.ExecuteReaderAsync(cancellationToken))
 {
 while (!dataReader.IsClosed)
 {
 // While the dataReader has not reached its end keep adding rows to the DataItemsList
 while (await dataReader.ReadAsync(cancellationToken))
 {
 // Process dataReader row
 WorkOrder workOrder = GetWorkOrderFromReader(dataReader);

DataItemsList.Add(workOrder);

// Another simulated delay...this one internal
 await Task.Delay(TimeSpan.FromMilliseconds(1));
 }

if (!dataReader.NextResult())
 {
 dataReader.Close();
 }
 }

Debug.WriteLine("done with reader");

RequestStatus = "finished";
 }
 }
 }
 }
 catch (SqlException sqlEx)
 {
 Debug.WriteLine(sqlEx.Message);
 }
}

Download C# Project (an MDF with just the WorkOrders table is included)

Fun with ClickOnce and XML files…and Prerequisites

I have a recent WPF project that is published using ClickOnce. However, the application has some XML templates that weren’t being copied over to the install directory. It was strange because they were being published to the deployment package. What I found was that in Visual Studio, you need to open Properties > Publish and click on the Application Files button.

Find the files that aren’t being copied over and change the Publish Status to “Include”. Mine were originally set to “Data (Auto)” and that didn’t cut it:

Incidentally, within the Solution Explorer, each file has its Build Action set to Content and Copy to Output Directory is set to Copy always.

An update: Don’t forget to deal with prerequisites – in my case, .NET 4.5 and the Visual C++ 2010 Runtime – x64. We had three developer machines where installation worked fine and client machines where it didn’t. I installed a fresh copy of Win7 in a VM and was able to fairly quickly determine this. To Microsoft’s credit, you can create a setup program to install prerequisites. However, IIRC, you get to download and install them even if they’re already installed. Still, better than beating your head against it all day. Cable broadband is a lot cheaper than my mental bandwidth.