Creating (and restarting) a single-instance WPF application with SingleInstance.cs

Standard

My current project presented a unique challenge. I have a need to:

  1. allow only one instance of the application to run at each workstation,
  2. notify the user that an instance is already running if a second instance is started, and
  3. be able to programmatically restart the application.

Thankfully, Microsoft has provided the SingleInstance.cs to serve these needs. Following this article on CodeProject.com was a great start. The author Arik Poznanski did an excellent job explaining the steps necessary to implement the first two requirements. I combined his techniques with information found in this article on StackOverflow.com to fully satisfy all three requirements – an application that will only allow one instance, that will notify the user that an instance is already running, and that can easily be restarted programmatically. Continue reading

Implement WebClient’s asynchronous download with cancellation capability

Standard

When I wrote my article regarding use of the BackgroundWorker to keep the UI responsive, I used the WebClient’s DownloadString method as an example of a long-running process. I used this as an example in explaining how to use the BackgroundWorker, which simply allows for thread-blocking code to be run in a separate thread.

As it turns out, this is a terrible idea. Not the whole thread-blocking code in a separate thread, but the use of a WebClient in a BackgroundWorker. You see, the WebClient class implements a DownloadStringAsync() method. This allows the calling code to continue to run, and the asynchronous process will eventually return a string. But since it’s asynchronous, our UI thread will never get blocked by a long-running process. And since it too supports asynchronous cancellation, there’s no reason to embed it inside a BackgroundWorker. Continue reading

Implement cancellation ability on BackgroundWorker

Standard

As I mentioned in my article on implementing the BackgroundWorker to keep your WPF user interface responsive, the BackgroundWorker class supports cancellation. I will illustrate here how easy it is to accomplish.

I’ll build this example by continuing the example in the previous article. First, let’s add a BackgroundWorker property to our DataModel class. Continue reading

Easily create a WPF splash screen with status updates via MVVM

Standard

I was in search of an easy implementation of a splash screen for my current project. I wanted to be able to show a splash screen and update it with current status information as my application initialized.

The standard SplashScreen class provided by Microsoft does not support showing dynamic content on the SplashScreen. For this reason, I was not able to use the supplied class. Instead I decided to create my own.

The splash screen I created is simply a regular window bound to a view model. I’ve created a SplashScreenHelper static class that we’ll use to send status updates to the splash screen. Continue reading

Purge DataContext ChangeSet without reinstantiating

Standard

I’m currently working with Linq-to-SQL, and have used attribute mapping to map my classes to database tables. In doing so, I’ve created a Database context that derives from DataContext (and takes my encrypted connection string stored in settings as a default parameter). To create a database connection, I simply use typical code as illustrated below.

Note that the following terms are referred to below, but not included for brevity:

  • ViewModelBase – provides INotifyPropertyChanged implementation
  • Customer – a typical class representing a Customer object

Continue reading

Creating a flexible custom WPF dialog

Standard

In my current project, we had a need to create a custom WPF dialog box. Writing our own provides us the ability to easily skin the window with our application’s theme as well as gives us the ability to generate any buttons we wanted.

We wanted our custom dialog box to be able to:

  1. Display a message to the user
  2. Provide various button options (OK, OK/Cancel, Yes/No, Yes/No/Cancel, etc)
  3. Return the button clicked by the user
  4. Display an optional CheckBox
    • Display text next to the optional CheckBox
    • Accept a boolean property for the default IsChecked state of the optional CheckBox
    • Provide the IsChecked value of the optional CheckBox as an out parameter

Continue reading

Closing a WPF Window using MVVM and minimal code-behind

Standard

The other day I started moving all my event handlers in my application from the View’s code-behind file to the ViewModel. I accomplished this using command binding. This was all easy enough – until I came to my Close method.

You see, in the MVVM (Model – View – View Model) design pattern, the ViewModel – a class that typically contains the values you want to display in your View – shouldn’t know anything about the View. It’s OK (and quite necessary!) for the View to be aware of the ViewModel, however.

So let’s take a look at the Close button’s event handler as it originally existed in code-behind:

private void Close_Click(object sender, RoutedEventArgs e)
{
    this.Close();
}

Continue reading

My ultimate INotifyPropertyChanged implementation

Standard

In the Model-View-ViewModel design pattern, we make frequent use of the INotifyPropertyChanged interface. It is the Interface that defines the necessary methods to Notify the UI when a Property has Changed. As you can see, its a very well-named Interface. 🙂

I’ve collected a few variations of the implementation and placed them all into a single ViewModelBase class. I didn’t write any of these myself – rather, I found them strewn about the internet. I’ve documented where I got some of them; others were (and probably still are) readily available from a multitude of sites. I’m making my collection available here, and I’ll give a few examples of how to use it. I’ll also explain the “evolution” my use of this interface has undergone.

To keep things organized, I usually create a folder named MVVM in my solution to house this class. You’ll want to update the namespace in this class to match your project; eventually I’m sure I’ll just compile it into a DLL once its evolution has ceased. Continue reading

Implementing the .NET DispatcherTimer

Standard

One of the issues with multi-threading in WPF is the inability for processes on a separate thread from the user interface to directly access objects in the UI. The .NET Timer object does not run in the same thread as WPF’s UI, so it therefore cannot directly update the UI. Instead, the Timer must post UI updates to the dispatcher of the UI thread, using the Invoke or BeginInvoke methods. However, an easier method exists for implementing a Timer that updates the UI – the DispatcherTimer.

The DispatcherTimer runs on the same thread as the UI. Therefore, using the DispatcherTimer instead of the traditional Timer object allows UI updating without the need for the Invoke or BeginInvoke methods.

The DispatcherTimer works in almost the same way as the traditional Timer:

  1. Create an instance of the DispatcherTimer
  2. Assign a TimeSpan to the DispatcherTimer’s Interval property
  3. Assign an event handler to the DispatcherTimer’s Tick event
  4. Start the timer

It really is that easy! Let’s take a look at some sample code. All of the following code can be placed in your DataModel. Continue reading

Keep your UI responsive with the BackgroundWorker

Standard

I recently completed an application that made use of the WebClient object’s DownloadString method to obtain a JSON string. In my development environment retrieval of this data often took upwards of 30 seconds. If you’ve ever incorporated a time-consuming process in your application, you may have noticed that your user interface becomes unresponsive while the process is running.

Why does this happen? Because without special consideration, this time-consuming process is running on the same thread that handles updating of the UI. “How do I keep my UI responsive during a time-consuming process?”, you may ask. This can be easily accomplished through the use of the BackgroundWorker object. In this article, we’ll discuss the BackgroundWorker object, some of its available event handlers, and one of its methods. Continue reading