Hey Guys,

A couple of times a faced an issue while working on code. I wanted to check which files I edited since yesterday or since a specific date as in a folder, so i developed an application which which will find the modified files in the selected folder after the specified date and time.

 

Below you can find the installer. Source Code and Executeable for the

 

Download the source code for ModifiedFilesFinder 1.0 @OneDrive or @Google Drive
Download the installer for ModifiedFilesFinder 1.0 @OneDrive or @Google Drive

To run the application you need to download the files above.

  • Go to the folder
ModifiedFilesFinder 1.0

ModifiedFilesFinder 1.0

  • Run the Setup.exe
ModifiedFilesFinder 1.0

ModifiedFilesFinder 1.0

  • Click on install and after the installtion completes the application will open.
ModifiedFilesFinder 1.0

ModifiedFilesFinder 1.0

 

ModifiedFilesFinder 1.0

ModifiedFilesFinder 1.0

  • Once the application scans the selected folder it will prompt you to select the location for the text files which has th elist of all the modified files.
ModifiedFilesFinder 1.0

ModifiedFilesFinder 1.0

  • To remove the application you need to uninstall the application form control Panel. So go to Uninstall programs and find the program by name FindModifiedFiles and uninstall it.
ModifiedFilesFinder 1.0

ModifiedFilesFinder 1.0

 

Any feedback, comments or questions are most welcomw.

 

What do we do and what does IDE do

The C# program can do whatever you want it to but it will take much more than just dragging and dropping the controls in visual studio. Visual studio does provide you with the code but that is just the start point for our application and we need to write C# code for our application to perform the task we want it to do. Let’s see what Visual Studio can do for us.

  • When we create a new Windows Forms Project in visual Studio, it adds an empty form to the project. What IDE does here is creates the files and folder for the project which are created from a predefined template that contains the basic code to create and display a form.
  • When we drag and drop a button onto the form we see some of the C# code for the button property is automatically added by visual studio. What IDE does here is add the code to Form1.Designer.cs which adds the button to the form. When we double click the button then the code to handle the click of the button is added to this file.
  • Visual Studio presents us with the property window in the IDE that we can use to set the various properties of the button. What IDE does here is update these values into the Form1.Designer.cs.

Where programs come from

Actually a C# program just starts out as a few lines of code in a couple of files and finally it runs on a computer. The following steps if how we do it.

  • Program start out as source code – IDE is nothing more just a program that helps us creating, editing and managing our code files and resources. It bundles all these files into a solution by creating a .sln file and a folder that contain other files. The solution file has a list of project files (i.e. .csproj) in the project. The project file contains the files associated with the program.
  • .NET Framework Tools for programming – All the controls that we use in our code are provided as provided as part of the .NET framework. Also there is lot of underlying code for default functionalities like the maximize and the minimize buttons in a button. So C# is just a language using which we access all these controls and their existing functionalities and write new functionalities. The .NET framework is divided into the namespaces which we have already seen. We include the part of .NET framework we need in our application by specifying the using keyword at the top of our code file. Ex – using System.Windows
  • Build the program to create an assembly – When we build our application by using the Build Solution or Build Project option then the IDE runs the C# compiler which compiles our project into a exe or a dll depending on the project type we have selected (class library compiles into a dll and applications compile into exe). We can use this exe to run the program and when press F5 to debug our application then IDE runs this exe and provides additional options to debug the program i.e. pause or add breakpoint to a program.
  • CLR runs the program inside itself – When we run the exe then CLR (Common Language Runtime) kicks in and acts as the layer between our program and Windows. Before C# in your program itself we had to deal with the complexity of communicating with the hardware and low level stuff but with .NET this taken care by CLR. CLR does the translation of our code to machine code so that computer understands it.

How Does the IDE helps us

  • Solution Explorer – It shows us everything that is present in our project. This shows us all the files, folder, references and resources in our project.
Visual Studio Solution Explorer

Visual Studio Solution Explorer

  • Tabbed View – The IDE provides a tabbed view for accessing and editing the various files simultaneously. We can use Ctrl + Tab to switch between the opened tabs in Visual Studio.
Visual Studio Tabbed View

Visual Studio Tabbed View

  • IDE helps write code – The Visual Studio IDE has a feature known as IntelliSence that helps developers writing the code. While we are typing code in the VS IDE we can see small Windows popping up. It shows us the various options we can select.
Visual Studio Intellisence

Visual Studio Intellisence

It also provides the various inbuilt code snippets to auto type the code for us. For example if we want to add the code for a MessageBox we can type mbox and press tab twice and we will be able to see something like below.

Visual Studio Code Snippets

Visual Studio Code Snippets

 

  • IDE helps in tracing errors – When we build our code using the IDE we see the list of compiler errors along with the details and the location of the error.  Also when we debug our program the IDE firsts saves the changes in the project and then shows the compile time error if any.

Changing in IDE means changing the Code

Whenever we are changing anything in the properties window or the design the application all these changes are also reflected in the code. It might seem easier to drag drop controls onto our form but the IDE generates the code in the background.

Dissecting a Program

All the C# programs consist of namespaces, classes and methods which makes our life easier. Whenever we are writing a new class or a form the namespace need to be specified so that the code is separated from the .NET framework libraries. A Class is some code which consists of methods and properties to get the work done.

  • The first part of our program is the one that specifies the .NET classes we need in our program. This is done by using statements as shown below. We can also refer other classes as well which are present in other namespaces. If we do not want to use the using statements we can use the FullyQualified namespace for any class to use it.
Visual Studio Using Statements

Visual Studio Using Statements

  • The C# program is divided into classes. Generally most classes to one thing to keep them logically separated on the basis of what they do. So everything inside the first and last curly braces is part of Chapter02 namespace and the content between the second and second last curly braces is part of the class Form1. So to look for the content of a particular class or namespace we look for the matching curly braces. This class was created by the IDE when we asked it to create a Windows Form application for us.
Visual Studio Classes

Visual Studio Classes

  • Classes contain methods that perform the actions as specified. A method takes some input and performs some action and might produce some output called as the return value. The class we saw makes call to a method called InitializeComponent().
  • A statement is a single line of code. Like in the image above we can see we have added a statement as MessageBox.Show(“Test”); When programs calls a method then statements in that method are executed in sequence. Then method returns to where the method was called from when it either encounters a return or no more statements are available to execute.
  • All programs in C# start at one and only Main method. When we created the Windows Forms application the IDE automatically added the Program.cs file which contains the Main method. This is the entry point of this application and is the first method that will run.
C# Main Class

C# Main Class

It’s not necessary that we keep this Main method as the entry point for our application. We write another Main method in a differ class and make it as the entry point for our application.

  • We can have multiple classes in the same namespace. When a class is public all the other classes in the program can access it. A namespace can span multiple files. So can a class but we need to use the partial keyword for a class to split across multiple files.
  • A variable is something in which our program stores all the data whether it is a document, image or a message. We can declare the variable as shown below. When we declare a variable we mention its type and name. When the program is compiled the compiler check if have assigned value of correct type to the variable. The values of the variable might vary at different times in the program.
C# Variables

C# Variables

The assignment of values to the variable is done in the following way.

C# Variables

C# Variables

  • The C# program is familiar with the maths operators like +, -, *, /, etc. Let’s see what different combination of these means
    • = means assignment of a value to a variable
    • += means adding the value to the variable and then assigning it to the same variable. -=, *= and /= have similar meanings as you might guess.
    • ++ means incrementing the variable by 1 and – means decrementing the variable by 1.
    • != means not equal to.
    • == means comparison
    • We can use the debugger to see the values of the various variables at runtime by placing a watch on the variable on whose value we are interested in. So if you want see the value of variable sin a line of code while debugging the code we can do that by placing a breakpoint at that location by pressing F9 and remove it by pressing F9 again.
    • Loop will perform an action over and over. Different loop in C# are
      • For – As we can see in the example below the action inside the for loop will be performed till the evaluation of i<10. We need to be really careful while using loops because if the condition becomes false the loop might run indefinitely.

Example

for (int I = 0; i< 10; i++)

{

//Action to be performed

}

  • While – As we can see in the example below the operation between the parenthesis will be performed over and over again till the evaluation of i>5 in true.

Example

While (i>5)

{

I = I -1;

}

  • If/else statements makes the decisions. As we can see in the example below the MessageBox will show the value if the variable yourValue is 3. The == sign that we see is for the evaluation and not assignment.

Example

If( yourValue == 3)

{

MessageBox.Show(“You were right”);

}

 

 

WPF being a fairly new technology might need to communicate with the components that are made in other technologies so in this section we will have a look as to how we can communicate with other systems that are built in Windows Forms or Activex.

Mixed UI Technologies

So if our WPF application needs to use controls that were developed earlier or just merely in different technology or we need to integrate with legacy plug ins or maybe there is some stuff which is available in WPF or we are moving our application to WPF but module by module. In all these cases our application will be hybrid of WPF and other applications.

WPF and HWNDs

The only major issue in WPF is that WPF is designed differently from Win32. The major difference is in the composition of the Window i.e how different elements combine to form a Window. In a classic Win32 app the composition works by partitioning the window into different elements. It UI elements gets the ownership of the window. This portioning is tied to the Window Handle or HWND. HWND is the type that represents Window handle in User 32. So each Win32 control has its own HWND owns all the pixels in some region of the screen, whereas in WPF the composition works in different way. WPF treats the entire window as one big canvas and all the components get to paint on that. So the individual WPF components don’t get to won a region individually. SO WPF creates just one HWND to fill the entire window. If we run the tool designed to explore the window handle then we can see that WPF window has one HWND.

As you see in the image below I have run Microsoft Spy++ and as you could see the WPFInteropSample application has a HWND wrapper. So we can see that WPF has just one big HWND for the application. However Pop ups have their own HWND as they are separate top level windows.

 

WPF and HWNDs

WPF and HWNDs

Interop Not Free

You might think that using the existing components might be cheaper but that’s not the case with interop in the long run.

  • The development cost if more as you are using a mixture of technologies.
  • There might be design compromises due the limitation of using multiple technologies in application.
  • During the runtime the application memory usage will increase by using both Windows Forms and WPF in one application.
  • There can CPU costs as well.
  • Also the WPF and Winforms control only almost look alike and the difference becomes more obvious

So we should use hybrid applications with discretion.

Limitations of Interop

When WPF was being designed it was not planned to be run on older version of windows bu after lot a demand Microsoft changed that and made it available to run on Windows Server 2003 and Windows XP which was great. But to get this accomplished there were changes that were made and those led to a few limitations. The major issues are as below:

Airspace issue

This is the major issue. Just like two aircrafts cannot occupy the same airspace similarly two different technologies cannot occupy the same pixel space. The WPF window needs to partitioned so that each area can be used by WPF, Win32 or Directx. We cannot have more than one technologies rendering on the same pixel.

The directx limitation might seem strange as we know that WPF uses directx but the reason is that WPF does not want to share its directx services. In .NET 3.5 SP1 we can take the output of directx and use it as a brush in WPF. So it is possible to get the directx output into a region of the window. But still the control is with WPF and the HWND control handled by WPF

Example

Transforms

The transforms applied in WPF will not apply to other technologies even though the component of other technology may be a child of WPF content.

Events

Event bubbling does not work across technology boundaries either.

Multi-level hybrid Nesting

There are limitations on how deeply we can nest the content. We cannot host a Windows Forms Controls inside a WPF Control  that is hosted inside a Windows forms controls that is the child of the WPF window.

Airspace Issues in WPF

  • Clipping
  • Z-Order
  • Animated Objects
  • Opacity
  • Pseudo Transparency

Multiple Top Level Windows

A simple solution to all the airspace problem is to use multiple top level windows as all the airspace issues occur when Win32 and WPF components share the same window. Airspace limitations do not apply to the desktop level. So a simple solution to the Z-order problem is to put all the content that needs to go on top in a different window. This is the same way in which pop up works. It shows up on top of all the other windows and content. We can make use of layered windows introduced by windows 2000 as after that it has been possible for multiple windows to share pixel screen. Also the WPF application can make use of transparent windows (Window.AllowsTransparency).

Input Differences

Another issue in WPF interop is handling the user input as event bubbling and tunneling is tied into WPF visual tree. So if the mouse goes into the other technology elements then events won’t bubble out of it. So the properties like IsMouseOver, IsFocusWithin, etc will not return what we are looking for.

Interop Combinations

The following table show how easy or difficult the various Interop combinations are. The easiest interop to do is with Windows forms. It is slightly harder to interop with Win32 components because we are dealing with C++ code. Hosting an activeX control inside WPF is easy but vice versa is difficult. If we want to host WPF content inside HTML then it’s easy but user restrictions are applied to WPF xbap inside the browser.

Technology WPF   Inside WPF   Outside
Windows   Forms Easy Easy
Win32 Fairly Easy Fairly Easy
ActiveX Hard Easy
HTML Easy (With Limitations) Easy

 

WPF in Win32

The most important thing to do is to host the WPF content inside the Win32 because without this we would not be able to display the WPF content at all. This service is provided by the HwndSource class as it connects the WPF visual tree to an Hwnd. We can do this as shown in the code below. We just need to pass the parameters inside the constructor and then set the WPF visual tree as the root visual.

 

WPF in Win32

WPF in Win32

All the WPF content uses an HwndSource and we can retrieve this by the following code. We can get hold of the Hwdn in which the WPF content is displayed and this is useful as Win32 components require us to know Hwnd.

 

WPF in Win32

WPF in Win32

Win32 in WPF

To host the Win32 content inside the WPF we can use HwnHost and derive from it. Then overriding the methods to create, destroy window and for handling its windows messages.

 

Win32 in WPF

Win32 in WPF

HwndHost Keyboard Handling

HwndHost host has some optional overrides for dealing with keyboard inputs. If we want the keyboard accelerators to work perfectly whether inside WPF content or Win32 content then we need to override these methods.

  • TranslateAccelerator
  • TabInto
  • OnMnemonic

Message Pumps

If we are hosting WPF content in a Win32 application then we need to modify the Message Loop to provide the WPF Dispatcher with the opportunity it needs to manage the window messages. The Class ComponenetDispatcher that offers various static methods that we should call for message handling when a message arrives or when it’s going idle. Also WPF needs to know when you have entered the model state so that WPF can stop responding to UI inputs.

Note that we don’t need to do this when we are integrating Windows forms and WPF. WPF and Windows Forms collaborate to provide our application with message handling.

WPF inside Windows Forms

In the code below we can see WPF content inside a Windows Forms container. There is a class called ElementHost that derives from WindowsFormsControl class so that we can edit any windows forms user interface. Buts cild property is of type FramworkElement that allows us to host any WPF element.

Create a WPF Control Library and add the following code to the UserControl.

 

WPF inside Windows Forms

WPF inside Windows Forms

Now add a Windows Forms application to the solution and refer this control library in that project.

 

WPF inside Windows Forms

WPF inside Windows Forms

When we select the main form we see that theUserControl1 is available for us to use.

 

WPF inside Windows Forms

WPF inside Windows Forms

Just drag it on to the windows form and run the application and we can see the WPF control inside the Windows Forms application.

 

WPF inside Windows Forms

WPF inside Windows Forms

Windows Form inside WPF

Hosting Windows forms content inside a WPF application is almost identical. Instead of ElementHost we have WindowsFormsHost and this derives from framework element and we can add it to any WPF UI and its child property accepts a Windows Forms Control.

 

Windows Form inside WPF

Windows Form inside WPF

Windows Forms and Layout

While using the ElementHost or WindowFormsHost WPF does its best to bridge between the two layout engines and overall it works fine (Docking, Anchoring and Auto-Sizing). Even the scaling transform works for WindowsForm inside WPF.

Ambient Property in Windows Forms

These are like WPF inherited properties. Windows forms uses these to make sure that the foreground color, background color and mouse cursor are propagated to child controls.

WindowsFormHost and ElementHost both have a PropertyMap which they use to manage the transition back and forth between the inherited properties and Ambient properties and it works fine most of times.

If want to modify this then we can register a callback that will be called while propagation of any property across the interop boundary.

 

Any questions, comments or feedback are most welcome.

The code for this post can be found here.

 

In this section look into multithreading in WPF and how we can send long running task to a different thread than the UI thread. We will look at how the threading model of WPF works. We will also look into how we can load data in a different long running thread and then utilize that data through data binding. Also we will see how we can communicate with WCF from WPF.

WPF Threading Model

Responsive UI and Distributed Systems

In our application if we are dealing with data which is coming from remote system then we cannot deny the fact there can be network delays because of various reasons (Network congestion, Busy Servers, Packet Loss, higher round trip times, etc) and that could render our UI unresponsive. Other reasons for UI unresponsiveness could be long running IO tasks or slow CPU. So we should take care of this while designing the application and make sure the UI does not freeze in such conditions.

Dispatcher

The WPF threading model revolves around an object called as dispatcher. It can be considered as the object that owns the message loop for a particular thread. In any windows application all the mouse and keyboard inputs are sent via message sent to the thread associated with the target window. In WPF receives these messages and decides what to do with them. All WPF elements are associated with the Dispatcher. We can see this in the DispatcherObject base class. This is the base of DependencyObject which is root of WPF class hierarchy.

WPF Dispatcher

WPF Dispatcher

As we have seen that DependencyObject object is the base class for most WPF types and it in turn derives from DispatcherObject which derives from System.Object, the base class for all .NET objects. The DispatcherObject provides access to the object to which the Dispatcher is associated and it provides functions to check whether we are on the right thread or not. The Dispatcher is always associated with a particular thread and in most cases we need to be on that thread when we make any changes to the object on that thread. WPF makes use of these methods to make sure we are performing operations on the right thread.

  • CheckAccess – This will return false if we are on the wrong thread.
  • VerifyAccess – This will throw an exception if we are on the wrong thread.

So this is in accordance with STA model. The reason why WPF uses this model is to work with COM based API’s like clipboard, etc.

However it is technically possible for an application to have multiple dispatchers each on a different thread but each top level window needs to be on a single dispatcher. However its very common to have only one dispatcher for one WPF application. And also generally a WPF application has one UI thread but that’s not a constraint. So we cannot modify anything on the UI elements from the wrong thread means non UI thread directly. As all the user inputs are handled by the dispatcher so when we do any other task on that thread then the dispatcher will not be to handle the user input. So we should not block the UI thread to the functions that take long time to complete.

So how do we follow both the things I just said above because one says do all the work on UI thread to avoid exceptions and the second one says do no work on UI so that the UI is responsive.

Async Work

The answer is to perform slow work asynchronously either by using multithreading or some API’s. If we want to update the UI in between these tasks then we can use the Dispatcher to come back on the right thread for updating the UI. We can do this by calling the Dispatcher.BeginInvoke method and passing the method delegate to it. This will end up as a message in the message queue of the dispatcher and when the dispatcher processes this message in its queue it will invoke the specified method and make eth updates to the UI thread. This will make sure that the UI updates will happen always on the right thread no matter what thread we are on.

We can see how to do this in the image below. We have some slow work to do. As you can see this work has been put in an anonymous delegate and this is invoked by a thread in a thread pool. So we have delegated the slow work to some other thread so that the UI is responsive and when the slow work is completed and the UI needs to be updated then we have called Dispather.BeginInvoke to our UI update.

ThreadStart threadStart = somedelegate // We can use any type of delegate

{

DoSomeLongRunningWork();

Dispatcher.BeginInvoke(DispatcherPriority.Normal, (EventHandler) delegate

{

UpdateTheUI();

}, null, null);

};

threadStart.BeginInvoke(delegate(IAsyncResult asyncRes) { threadStart.EndInvoke(asyncRes); }, null);

Let’s see this action. Add a class in with the following code in your application to do the time consuming task.

 

WPF Async Work

WPF Async Work

Now add the following code to the xaml of the application.

 

WPF Async Work

WPF Async Work

Add the following code to the code behind.

 

WPF Async Work

WPF Async Work

When we run this code we will notice that during the time our time consuming task runs the ui is responsive and if we have a look at the Thread ids we will notice that we ran the Time consuming task on a different thread then the other tasks and in the end we used Dispatcher object to Update the UI.

 

WPF Async Work

WPF Async Work

Dispatcher Priorities

As we have seen the previous section that we specified DispatcherPriority.Normal in the Dispathcer.BeginInvoke method. The different dispatcher priorities are as below and these are increasing order of priority. For example the DataBinding has higher priority than rendering. This is how it should be. Say we have an application that databinds all the elements on a page and suppose the data binding for all the elements is updated then we do not want call render for each element separately. So we just get one painting of the UI.

  • System Idle
  • Application Idle
  • Context Idle
  • Background
  • Input
  • Loaded
  • Render
  • DataBind
  • Normal
  • Send

DispatcherOperation

This is returned by Dispatcher.BeginInvoke and can be used to track the progress of the work.

  • Status Property – It has the status property which tells us whether the operation is still pending in the queue or executing or finished or aborted.
  • Result Property – It also has a result property that can be used to get the outcome of the operation if there was any.
  • Priority Property – The objects also provide access to the operations priority as well.
  • Completed Event – Called when the operation completes.
  • Aborted Event – Called when the operation aborts.
  • Wait Operation – This method block until the operation completes and if the operation has already completed before we have called wait then wait returns immediately. You need to be cautious while using Wait because you are blocking the worker thread till the UI operation is completed and this might lead to a deadlock as the UI thread might be waiting for the Worker thread to finish up.
  • Abort Operation – This operation aborts the operation if the operation is still waiting in the queue. If the operation has already started or finished the Abort does nothing.

Synchronization Context

Instead of using the Dispatcher.BeginInvoke we can use the SynchronizationContext.Post method to make the updates to the UI. This was introduced in the version 2.0 of .NET and also works for Windows Forms and ASP.NET. A dummy implementation for this is shown in below.

SynchronizationContext synchronizationContext = SynchronizationContext.Current;

ThreadStart threadStart = delegate 
{
    DoLongRunningWork(); 
    synchronizationContext.Post(delegate 
    {
        UpdateUI();
    }, null);
}; 
threadStart.BeginInvoke(delegate(IAsyncResult asyncResult)
{ 
    threadStart.EndInvoke(asyncResult);
}, null);

 

Asynchronous Options

Let’s have a look at the various asynchronous options available with .NET.

.NET v 1 asynchronous pattern

Whenever we see two methods, one called Begin___ and the other called End___ we know that we are using .NET v1 Async pattern. The Begin___ method needs to return result of type IAsyncResult and should also allow you pass a Callback function that will notify the completion of the method. The types that support this pattern are as below:

  • All delegates support this pattern
  • All networking classes implement it
  • All web service proxy classes implement this including WCF

The major advantage of using this pattern is that we gain a lot on the efficiency of the pattern. Just like the concurrent threads work in the Windows Operating system, the same the way this implementation needs the CPU time at the start and end of the operation explicitly and the remaining work is done concurrently. Like if it’s an IO task then it’s handled asynchronously by specialized hardware. So the major advantage of this pattern is its efficiency and we manage thousands of network operations with a few threads.

But this might not be very useful for a WPF application as the main use of threading in a WPF application if just maintain the responsiveness of the UI.

.NET v2.0 event-based asynchronous pattern

This pattern was introduced with .NET 2.0 and is more suited for user interface development.

In this pattern we will find methods of type ___Async and CancelAsync or ___AsyncCancel. So this pattern supports cancellation in scenarios where it can be done.

Another feature that we see in this pattern is that an event will fire when the operation completes and also when the progress of the task is changed.

And the most important thing to notice is that these events are raised on the user interface threads. This is a mandatory requirement for the components implementing this pattern. This is generally done by SyncronizationContext or AsyncOperationManager to make sure the events are raised on the thread on which the operation was invoked.

The advantages of this pattern are that it offers cancellation and is simple to use. The major advantage of this pattern is that presents a Single threaded API for multithreaded operations. So when are using a component that implements this pattern we don’t see anything other than the dispatcher thread for Async operations. So we call the Async work from the UI thread and we get the completed notifications back on the UI thread.

We have seen an example of this implementation in the Printing section. The XPSDocumentWriter offers the WriteAsync and CancelAsync methods.

So this method seems perfect for WPF but the couple of cons for this pattern are that it is not widely supported and it does not support the WaitHandle available in the V1 Pattern.

Thread Pool

Some components offer nothing but a synchronous blocking API. We saw this in the section where I showed you the TimeConsumingTask. So we need to go and manage the blocking and unblocking of the thread.

We could use a Thread Pool for it. .NET always provides pool of thread to do random work on random threads. .NET dynamically creates and destroys thread to meets the applications workload and this is really helpful in synchronizing the unhelpful synchronous components. You should remember that anytime we are using a delegate asynchronously we are using the thread pool internally.

The V1 and V2 of .NET asynchronous also use the thread pool in some implementations like the background worker class.

The only problem in working with thread pool is to get back to the UI thread when the work is done.

Create your own thread

Finally the last option is create our own worker thread. The major advantage of creating your thread is to have less concurrency. Yes it’s an advantage in terms of WPF because the only reason for asynchronous work is to ensure the responsiveness of the WPF UI.

The best way to go for a WPF application is to have one worker thread and one UI thread. And having only 2 threads will simplify the concurrency issues as we know what work is being done on what thread.

The only disadvantage with this is that there is no direct support for this approach in .NET library so we have built up our own mechanism to pass the messages between the worker thread and the UI thread. It’s not a lot of work as we just need a queue and some synchronization. But we should not be hesitant for the approach a little work upfront will give a lot of flexibility.

Databinding and Threading

In the previous sections we have seen how we can update the UI coming back from the worker thread. Now we will see how we can update the UI if we are using data binding. This is useful in the cases our data source is producing the change notifications. Add the following class and code to you application. This class will provide datasource which provides slow data. As we can see in the code the get accessor is fast but the set accessor is fetching the updates. The FetchNewData method simulates the slow operation. We are using the thread pool to get the work done and then we are sleeping on the thread for 5 seconds and then the property is updated. Also you can see that this class implements the INotifyPropertyChange to implement the change notifications.

 

WPF Databinding and Threading

WPF Databinding and Threading

This is used as the source for the UI as we can see in the code below. This source becomes the DataContext of the Window.

 

WPF Databinding and Threading

WPF Databinding and Threading

And we go to the xaml we will see that the textblock’s text property is bound to the data property of the DataContext.

 

WPF Databinding and Threading

WPF Databinding and Threading

WPF will take care of this as you can see by running the application.

 

WPF Databinding and Threading

WPF Databinding and Threading

However this is supported only in case of properties for the current version of WPF. If we are using a list and using data binding on the list with multithreading then we will get an error. So WPF actually offers only partial support for Async updates. Maybe the future versions might offer it as currently WPF does not offer a CollectionView that support changes to its collection from a thread different from a dispatcher thread.

We can change our approach to get this done. For example we can create our ObjectDataProvider (ObjectDataProvider.IsAsychronous) on the worker thread instead of the UI thread. And we can also set the binding on a particular element to be Async (Binding.IsAync).

I do not recommend this approach because xaml is not the place to handle the threading issues. So we are usually better off handling these issues in the DataSource.

WCF and WPF

WCF and v1 Async Pattern

If we are using WCF along with WPF then we can use the Async proxy class generated by WCF to perform work asynchronously. This can be done in two ways

  • While generating the Async class via command line we can affix /async at the last of the svcutil.exe command
  • Or in Visual studio while adding the service reference we can configure it work Async.

This setting will make the generated proxy to implement the .NET v1 Async pattern. This does not require any implementation form the server as this is just the way we want WCF to present the proxy.

svcutil.exe http://services.msdn.microsoft.com/ContentServices/ContentService.asmx?wsdl /language,C# /async
 
[ServiceContract(Namespace="urn:msdn-com,public-content-syndication", ConfigurationName="ContentServicePortType")]
public interface ContentServicePortType { 
[OperationContract(AsyncPattern=true, Action."urnmsdn-com:public-content-syndication/GetContent", ReplyAction."*")]
IAsyncResult BeginGetContent(GetContentRequest request, AsyncCallback callback, object asyncState); 

GetContentResponseEndGetContent(IAsyncResult asyncResult);

WCF and DataBinding

WCF also offers some help for the databinding as well. The svcutil has the option which will implement the INotifyPropertyChange on the types generated form the schema.

This is useful when the WPF application using a simple visual layout only directly over WCF service.

 

Any questions, comments or feedback are most important.

The code for this post can be found here.

 

Styles

Styles give our applications and elements consistent look and feel. In this section we will see how style hooks up to the resource system and property system in WPF. We will also see how to specify triggers in styles and how to specify default and custom styles.

A style is a named group of settings that will define the elements will appear. As you can see in the image below the basic structure of style contains a list of setter elements which specify a target property and a value. A style provides a way to set properties of a type of element and in WPF these properties are Dependency properties.

 

WPF Styles

WPF Styles

Applying Style

All the elements in WPF have style property. Generally we use a resource reference in the elements style property however we can also set it inline. The main motive behind defining a style is that the same style will apply to multiple elements and will give consistent look and feel to the application. We can define style at the

  • Element scope
  • Window Scope
  • Application scope

We provide the x:key attribute to the style so that the elements can refer that resource.

 

WPF Applying Styles

WPF Applying Styles

We can also define the style as shown below by specifying the TargetType of the style and this style will automatically apply to all the elements that are of that type unless specified otherwise.

 

WPF Applying Styles

WPF Applying Styles

We can use this property of the styles to skin our applications by the use of resource dictionaries. We can put the styles defining target types in both the resource dictionaries and switch between then to change the theme of the application.

Extending Styles

In WPF we can define new styles that are using other styles as the starting point. This can be done by using the BasedOn property of a style. We can change or add the needed properties. You should remember that we cannot apply multiple custom styles to an element so this BasedOn property helps us.

 

WPF Extending Styles

WPF Extending Styles

Styles vs. Local Properties

When we set a property using a style it works the same way as setting the property any other way.

But there is something that only style can do and not properties. In a style we can add properties that do not match the target type as shown below. In this case the WPF elements will apply the property that makes sense and will ignore the rest of the properties.

 

WPF Styles vs. Local Properties

WPF Styles vs. Local Properties

 

Triggers

The styles support same range of triggers as control templates. However the targets of the trigger in style are the target elements whereas in the ControlTemplate the targets are the named elements.

 

WPF Triggers

WPF Triggers

Animation Property Trigger

As we have seen in the graphics section that the only trigger we set on an element is the Event trigger. We cannot set a Property trigger on an element directly so we can use style for this. That style can be inline or resource style.

 

Animation Property Trigger

Animation Property Trigger

Animation Event Triggers

As we can see in the image below we can also put event triggers in the style.

 

Animation Event Triggers

Animation Event Triggers

Items Container Style

When we are working with ItemsControls like the ListBox or a TreeView we generally define the DataTemplates for the ListBoxItem or a TreeViewItem to make use of DataBinding. When are not proving these specified conatiners to the items then WPF is doing that for us. This means WPF wraps the contents of DataTemplate in a ListBoxItem for a ListBox and in a TreeViewItem for a TreeView. Now, if we apply properties to these will not work well while working with Data Binding. So what we need to do is define the style of type ItemContainerStyle.

 

Items Container Style

Items Container Style

 

Items Container Style

Items Container Style

Styles, Templates and Controls

Styles enable controls to be visible by default. As we have seen in the previous sections that the controls depend on templates for their appearance. Also the controls get their templates form the themes\generic.xaml or theme specific resource dictionary. These default styles set much more than a template. We should hard code as less as possible about a control in the template. The default styles sets properties like default background, font, etc. As you can see in the image below we have applied a local style to a button but we have just set the font size where does the button get the other properties form?

 

WPF Styles, Templates and Controls

WPF Styles, Templates and Controls

So what’s happening is that the local style for the button is setting the font size for the button and default style sets all the other properties for this button. So both the styles are merged and used in the button.

Any questions comments or feedback is most welcome.

The Code for this post can be found here.