Archive for the 'WPF' Category

Multi-threading in WPF part II: Code Sample

In the first part of this post series I briefly explains WPF threading concept and options you have to enable asynchronous operation in your application. On this post, I’ll show you the techniques you can use.

In my earlier blog post, I’ve created a WPF application that connects to MSN Live Search service. If you run the application you will find it hangs for a few seconds after Search() method is called. The first search request will take a while before the response comes back. During that time, the application becomes unresponsive. My attempt here is to execute this long-running search operation asynchronously on separate thread.

Using Dispatcher (the wrong way)

Using Dispatcher the wrong way
Using Dispatcher the wrong way

As you can see from the code, what I’m doing here is simply create a new thread with some UI updating logic attached as delegate. Now after I call Start() method on the new thread, SendSearchRequestWrong method will be executed. Things will go fine until the search result is returned. The thread will try to update UI in ClearCurrentDisplayResultmethod.

This code is destined to fail because it breaks the thread affinity as I mentioned in part I. This new thread won’t be able to find the UI thread since it’s executing in a different context. The exception will be raised and its error message says it all: The calling thread cannot access this object because a different thread owns it“. Nuff’ said.

Exception

Using Dispatcher (the right way)

Now let’s see how to get this to work.

Using Dispatcher the right way
Using Dispatcher the right way

The key to make it work here is wrapping the UI update logic inside a delegate and execute it with Dispatcher.BeginInvoke method. This will make sure that the code is executing on the right context. You can also specify the DispatcherPriority level as well. It’s recommended to give UI update code Normal priority and save other higher priorities for a more critical execution.

When you run the sample code, you’ll see that application interface is responsive during the searching. You will be able to type in the search query text box. This is because the long running operation is moved from the main UI thread to another thread.

Search result
The search result

BackgroundWorker

The BackgroundWorker class was introduced in .NET 2.0. Using BackgroundWorker ensures that the long running task is executed on a separate thread. BackgroundWorker uses Dispatcher and events while abstracts away marshaling issues, leaving you with the asynchronous goodness.

The other neat thing is that BackgroundWorker also supports two events: progress changed and cancellation. Both events provide a way for long running thread to interact with the UI. You also do not have to worry about execution context, it’s all taken care of for you.

Creating BackgroundWorker

The normal way is you create BackgroundWorker instance in the code and configure the events. You can also declare the BackgroundWorker in XAML file. I prefer the latter. By doing so, you can use attributes to wire the event handlers.

First, you will have to import System.ComponentModel namespace to the XAML. Next, declare an instance of BackgroundWoker in Windows.Resources section of the XAML. Since BackgroundWorker is not a UI element, you have to declare it as a resource.

Declaring BackgroundWorker in XAML
Declaring BackgroundWoker in XAML

As you can see, declaring BackgroundWorker in XAML allows you to declare event handlers for RunWorkerCompleted, DoWork, and ProgressChanged events right in the markup.

Using the BackgroundWorker

In the code, you can access and use the declared BackgroundWorker instance by

  1. Add application logic to event handlers for this BackgroundWoker
  2. Calling FindResource("<instance name>") method to access the instance
  3. Call RunWorkAsync method to start execution

Retrieving declared BackgroundWorker instance
Retrieving declared BackgroundWorker instance


Declaring BackgroundWorker event handlers
Once the BackgroundWoker is fired, DoWork method will be called. RunWorkerCompleted event is called when execution is finished. Meanwhile, if you declare WorkReportProgress attribute to be true, you can use ReportProgress(double) to update the UI. When ReportProgress method is called, BackgroundWorker.ProgressChanged event will be fired.

Note that I call BackgroundWorker.ReportProgress method inside DoWork. Since this MSN Live search API calls cannot really be broken down to percentage completed, I will simply assign 10% completion when request input is retrieved, 20% when the search is initiated, and 70% when the search result is returned.

Call RunWorkerAsync method to fire BackgroundWorker
Fire BackgroundWorker by calling RunWorkerAsyncMethod

Finally, when the code runs, you can see that the percentage completion is reported and display back in the interface. This is because I update the completion percentage text block every time ProgressChanged event is fired.


Updating UI for completion percentage

The completion percentage report text block is hidden when the result is ready and rendered to the UI.

Search completed
Last word

So, from this blog post series you can see that multi-threading in WPF is not difficult to achieve. Keep in mind that although it’s a lot like multi-threading in WinForm, but you have to be aware of some WPF-specific threading issues. IMHO, using BackgroundWorker can help you achieve this quite easily. Otherwise, you can go direct to use Dispatcher or threading as well.

You can download the code sample HERE

No Comments »

Teera on February 22nd 2008 in Software Development, WPF, .NET

Multi-threading in WPF part I: Dispatcher, DispatcherObject, and BackgroundWorker

Multi-threading and asynchronous operations can give WPF application a more responsive user interface. At a glance, it looks very similar to the way you would do on WinForm or ASP.NET applications. But it’s there are a few things about WPF threading model you should understand before jump right into it. On the first part of this two posts series I’ll try to show you what I find interesting, then I’ll rewrite my WPFLiveSearch sample application to allow asynchronous operation (so if you want to get right to the code, click HERE).

Single-threaded apartment model

WPF uses single-threaded apartment threading model, same as WinForm. The key characteristics about this model are

Thread affinity: every WPF objects (in a window) have thread affinity. A child thread is owned by a parent thread that creates it. Once created, any other threads cannot access this child thread directly. It can only be accessed via its parent thread. As you might have guess from this concept, there is one thread that runs the entire application when it starts. This main thread also owns all elements.

DispatcherObject: most of WPF elements associate with thread affinity are derived from DispatcherObject.

UIElement and DispatcherObject class heirarchy

In the early design of WPF, the Thread rental model was also considered. Thread rental model basically opens access to UI objects from any threads. However, this model adds complexity for context aware single-threaded application.

DispatcherObject

Every visual elements in WPF derive from DispatcherObject. When it comes to threading, DispatcherObject maintains thread affinity context. It ensures that the execution context is on the right thread to access the object. DispatcherObject contains three members

Dispatcher: provide access to dispatcher for this object

CheckAccess(): return true if the code is on the right thread to access the object

VerifyAccess(): throws an InvalidOperationException if the code is NOT on the right thread, otherwise allows execution on the object.

If you decide to create a class or a control deriving from DispatcherObject, you should make sure that every methods calling to UI thread either calls VerifyAccess() before or execute code only if CheckAccess() returns true.

Dispatcher

Dispatcher manages the priority queue of work items and owns application thread. It fetches work to UI thread for processing. A dispatcher is created when you create an instance of DispatcherObject (or derived class) on a new thread. This is necessary to meet the thread affinity demands. However, the UI thread is blocked whenever it executes work routed through Dispatcher. So, the best practice is to keep the work that Dispatcher does small.

Current thread’s dispatcher can be accessed through static property Dispatcher.CurrentDispatcher. You can access WPF element’s Dispatcher directly as its property (as mentioned above, WPF UI elements are derived from DispatcherObject!) .

What about plain old System.Threading.Thread?

You can certainly create a new System.Threading.Thread object, supply the code to be executed, and fire it off with Thread.Start() method. However, you must be aware that you have to manage locks and shared critical region access yourself. As mentioned above, you must be extremely careful if the code executed within this new thread tries to access UI element.

BackgroundWorker

IMHO, BackgroundWorker is the best solution for executing long running task on a separate thread. BackgroundWorker uses Dispatcher along with SynchronizationContext, AsyncOperation, and AsyncOperationManager. Even better, most of these complicate tasks are abstracted away under the hood.

Another thing I like about BackgroundWorker is that it also provides progress changed and cancellation events. These two events can be channeled to interact with the UI as well.

Sample code

In part II of this post, I’ll go through an example of how to add multi-threading capability to your WPF application through each of the methods describing above.

For more information about multi-threading in WPF check out:

No Comments »

Teera on February 22nd 2008 in Software Development, WPF, .NET

Search it Live! with MSN Live Search

I googled around the web for something fun to do over the weekend and found myself at Microsoft Windows Live page. It has a really cool API that allow you to integrate MSN Live Search into your web site or application. The Live team go into a great length to make this API easy to use. They have a small utility that spits out HTML snippet that add MSN Search Box on your web site; simply copy and paste the code on your page and it’s done. What is more interesting though is they also open up the Search API via web service. After playing around with it, I was able to get the search feature running on sample WPF application in less than an hour! So on this post I will show you how easy it is to bring powerful search capability to your desktop application with MSN Live Search web service.

WPFLiveSearch: Web Search
WPFLiveSearch in action: Web search

WPFLiveSearch: Image search
WPFLiveSearch in action: image search

Get your Application ID

First thing first, you have to sign up for your Application ID at http://search.msn.com/developer. After logging in with your .NET passport, you’ll be asked to enter your application name. In this sample, I name my application “WPFLiveSearch”. You will also be given AppID that you can use, copy the ID onto the text editor.

Add Service reference to your application

Connecting to MSN Live web service is easy. Simply right click at your Visual Studio project > Add Service Reference (or Add Web Reference) then enter the service url http://soap.search.msn.com/webservices.asmx?wsdl.

Then before clicking OK, give this service end point a namespace. In this project, I call this service “MSNLiveSearchProxy”. Now if you go look at App.config or Web.config file, you will see that the service endpoint is added to the configuration.

Adding MSN Live Search service reference

Using the MSN Live Search service

If you get to this point, it’s quite easy to use the service. The API is rich. However, if you want to perform simple search query, you are more likely to be using only the following classes:

MSNSearchPortTypeClient (implements MSNSearchPortType class)

MSN Live service end point class containing Search method.

SourceRequest

This class represents the information source. You can customize your search result by setting a few properties for this class. The important ones are Count (number of returning result), Source (information resource type enumeration), FileType (valid result file types), ResultFileds (required result information e.g. url, link description, image display). These properties are essential for making search request. There are other properties that you can set for a more sophisticate search query.

SearchRequest

As the name indicated, this class instance wraps around SourceRequest array and to be passed on to MSNLiveSearch’s Search() method.

SourceResponse

The search results are returned as an array of SourceRequest objects. This array can be access from SourceResponse’s Results property. Each returned SourceResponse instance corresponds to the SourceRequest array that was sent for searching.

SearchResponse

Similar to SearchRequest object, SearchResponse wraps the array of SourceResponse returning from Live Search web service call.

To create a search request, you follow this step

  1. Create and configure SearchSource objects array
  2. Wrap this array with an instance of SearchRequest
  3. Call Search method on MSNLiveService instance, pass the SearchRequest instance as a parameter

If the search completes successfully, the Search method will return an instance of SearchResponse. Search method can raise two possible exceptions: SoapException and WebException. You can catch these exceptions and take a look at their inner exception and message to find out about the error.

The Code Sample

I create a simple WPF application that performs the search with user input query. When the result returns, the application adds UI controls to the display grid dynamically.

You can download the code sample HERE.

Apart from MSN Live Search, Windows Live also have other cool services and API you can use for free, namely MS Virtual Earth, Live Expo, Spsace, and Gadgets. IMHO, the Live team has done a great work to make these services very easy to use. Just a quick look through the web and I already found a lot of people utilize these services to build great apps and many build their business around them. You should give it a try.

No Comments »

Teera on February 18th 2008 in Software Development, WPF, .NET

Debugging SQL 2005 Stored Procecedure

At Plexia, our system makes extensive use of SQL stored procedure; yet, I’ve never been in a situation that would require debugging right into the SQL code. Actually you should not have to do so. If the application is well designed, complex business logics should be abstracted out from database to its own layer. Only until recently that I ran into a piece of legacy code that calls to a 100+ LOC stored proc. Visual Studio has a feature that allows smooth stored proc debugging and I found it to be quite handy. So on this post, I will share with you how to debug SQL 2005 stored procedure from Visual Studio 2008.

Tools

I use Visual Studio 2008 on MS SQL 2005 server. I’m pretty sure that you can do this with VS 2005 as well but I havn’t tried it yet.

Setting up the environment

When debugging T-SQL on SQL 2005 server, you may run into a problem with hardware or software firewalls. You can simply select “unblock” on any pop-up warning dialogs to allow VS and SQL server to communicate.

You also have to make sure that VS has enough privilege to access SQL server. You can do this by using Windows ‘Administrator’ account and run Visual Studio as administrator, both on the SQL server machine. You can also give additional accounts to SQL server’s sysadmin pivilege by using sp_addsrvrolemember '<Domain>\<Account Name>', 'sysadmin' command.

If you use SQL 2005 NT authentication model, make sure to give the account permissions to run sp_enable_sql_debug stored procedure. You can do so by running this script:

CREATE USER '<username>' FOR LOGIN '<Domain>\<Account name>'
GRANT EXECUTE ON sp_enable_sql_debug TO '<username>'

After you run this script, a new user account will be created for '<Domain>\<Account name>' Windows user with permission to debug SQL.

Warning!

You should NEVER do this on production server. It’s best to do this on local machines with everything installed.

1. Create test database and stored procedure

First I start by create a simple database called ‘Test’ with only ‘Products’ table.

Create Products table

Then I create a simple stored procedure called ’sp_getAllProducts’ to query for product on this table. Note that I use declared variable @count only for debugging purpose.

Simple Stored Procedure

At this point, if you have set up privilege for Visual Studio correctly, you will already be able to debug stored procedure! You can do this by simply open VS Server Explorer, create connection to the database, select the stored procedure, right-click, and choose ‘Step Into Stored Procedure’.

If this stored procedure has input parameters, you will be asked to provide them. Yet, it’ll be even better if you can step into this stored procedure right from the application code!

3. Creating WPF client application

Next, I fire up Visual Studio 2008 and create a very simple WPF project. Let’s call this project ‘ProductBrowser’. I create a window with a ListBox to display items from database.

In the Window.xaml.cs code-behind file, I create a simple method that connect to the stored procedure. The returning data records are bound to the ListBox. Notice that I set the breakpoint when SqlCommand executes stored procedure.


4. Enable SQL debugging from the project

Next, go to Server Explorer window, right-click the test database connection, and select ‘Application Debugging’. This will allow application to step into SQL database programmability.

Set up stored procedure application debugging

Right-click on the client application project in Solution Explorer, go to ‘Debug’ tab and select ‘Enable SQL Server Debugging’

5. Run the application in Debug mode

That’s it! Now, you can try setting breakpoint in the stored procedure and run your application in Debug mode. You will be able to step right into the stored procedure code right from your application.

And that’s all you need to do, easy right?

No Comments »

Teera on February 12th 2008 in Software Development, WPF, .NET