- Posted by Diederik Krols on June 7, 2010
This article explains how to implement optimistic concurrency checking using a SQL Server DateTime or DateTime2 column. It's a follow-up of my previous article on using a TimeStamp column for that same purpose. In most -if not all- concurrency checking cases it actually makes more sense to use a DateTime column instead of a TimeStamp. The DateTime data types occupy the same storage (8 bytes) as a TimeStamp, or even less: DateTime2 with 'low' precision takes only 6 bytes. On top of that: their content makes sense to the end user. Unfortunately the DateTime data types are 'a little bit' less evident to use for concurrency checking: you need to declare a trigger (or a stored procedure) on the table, and you need to hack the entity model.
A sample table
Sample time! Let's start with creating a table to hold some data.
Table definition
Here's how the table looks like (the solution at the end of the article contains a full T-SQL script). The LastModified column will be used for optimistic concurrency checking:
CREATE TABLE [dbo].[Hero](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[Brand] [nvarchar](50) NULL,
[LastModified] [datetime] NULL,
CONSTRAINT [PK_Hero] PRIMARY KEY CLUSTERED
(
[Id] ASC
))
Trigger definition
Unlike an Identity or a TimeStamp value, a DateTime value is not automatically generated and/or updated. So we have to give the database a little help, e.g. by creating a trigger for insert and update on that table:
CREATE TRIGGER [dbo].[trg_iu_Hero]
ON [dbo].[Hero]
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE [dbo].[Hero]
SET LastModified = GETDATE()
WHERE Id IN (SELECT Id FROM inserted)
END
Alternatively, you could insert through a stored procedure.
A sample application
I already prepared for you a small sample application. Here's how the main window looks like:

Cute, isn't it ?
The problem
In the entity model, you have to make sure that the LastModified column has the correct settings (Fixed and Computed):

Run the application with just the generated code. You will observe that when you update a record, the entity's LastModified property will NOT be updated. SQL Server Profiler will reveal that only an update statement is issued. The new value of LastModified is assigned by the trigger but NOT fetched:

The solution
In order to let the Entity Framework fetch the new value of the DateTime column -or whatever column that is modified by a trigger-, you need to hack the model's XML and manually add the following attribute in the SSDL:

Somewhere in Redmond there will certainly be an architect who will provide an excuse for this behavior. To us developers, this sure smells like a bug. Anyway, if you re-run the application with the modified SSDL, the new DateTime value will appear after insert or update. SQL Server profiler reveals the extra select statement:

Source Code
Here's the source code, the whole source code, and nothing but the source code: U2UConsult.EF40.DateTimeConcurrency.Sample.zip (616,27 kb)
Enjoy!
|

|
Thank you
This article is dedicated to my 3-year old daughter Merel. Last week she briefly turned into a real angel, but then decided to come back.
I want to thank from the bottom of my heart everybody who helped saving her life: her mama, her mammie, the MUG, and the emergency, reanimation, intensive care, and pediatric departments of the uza hospital.
|
- Posted by Diederik Krols on May 27, 2010
This article explains how to implement optimistic concurrency checking in the Entity Framework 4.0, using a SQL Server Timestamp column. But you could have derived that from its title.
What is a Timestamp?
Despite its name, the SQL Server Timestamp data type has nothing to do with time. DateTime2 on the other hand, is DateTime too [sorry, I couldn't resist that]. A timestamp is just an eight-bytes binary number that indicates the relative sequence in which data modifications took place in a database. The value in a column of the type Timestamp is always provided by SQL Server: it is calculated when a row is inserted, and augmented with each update to the row, to a ever increasing value that is unique in the whole database. The Timestamp data type was initially conceived for assisting in recovery operations, and you also use it to synchronize distributed databases: based on the timestamp you can detect the order in which data was added or updated, and replay a sequence of modifications. But the most common usage of timestamp is optimistic concurrency checking: when updating a row you can compare its current timestamp with the one you fetched originally. If the values are different, you know that someone else updated the row behind your back. And you know this without holding any locks on the server while you were busy, so its a very scalable solution. This type of concurrency checking is called 'optimistic': you assume that in most cases you will be able to successfully update without the need for conflict resolution.
A sample of the geeky kind
Let's create a table with such a column (the scripts-folder in the provided solution at the end of this article contains a full script):
CREATE TABLE [dbo].[FerengiRule](
[ID] [int] NOT NULL,
[Text] [nvarchar](100) NOT NULL,
[Source] [nvarchar](100) NOT NULL,
[Timestamp] [timestamp] NOT NULL,
CONSTRAINT [PK_FerengiRule] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
Populate it with your favorite 'Ferengi Rules of Acquisition'. You find all of these here. In a WPF solution, create an entity model, and add the table to it. You see that the timestamp column has
- Fixed as value for the Concurrency Mode property, so the column will appear in the WHERE-clause of any insert, update, or delete query, and
- Computed as value for the StoreGeneratedPattern property, so a new value is expected from the server after insert or update.

Next, build an application with a fancy transparent startup screen, that allows you to open multiple edit windows on the same data. The startup screen could look like this:

The mainwindow of the application contains just an editable grid on the table's contents. It allows you to
- set the concurrency resolution mode,
- upload local modifications to the database,
- get the current server data, and last but not least
- restore the table to its original contents (that's an extremely useful feature in this type of application).
Here's how the window looks like:

Visualizing a Timestamp value
Just like GUIDs and technical keys, you should avoid showing timestamp values on the user interface. This demo is an exceptional to this general rule, so I built a TimestampToDouble converter to translate the eight-byte binary number to something more readable. I don't guarantee a readable output on an old active database where the timestamp value is very high, but it works fine for a demo on a fresh database:
public class SqlTimestampToDoubleConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
{
return null;
}
byte[] bytes = value as byte[];
double result = 0;
double inter = 0;
for (int i = 0; i < bytes.Length; i++)
{
inter = System.Convert.ToDouble(bytes[i]);
inter = inter * Math.Pow(2, ((7 - i) * 8));
result += inter;
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Concurrency
Generated SQL Queries
If you run your SQL Profiler while modifying data through via the main window, you'll see that the Entity Framework query's WHERE-clause contains the timestamp, and that after the update the new value is fetched for you:

If there's no row to be updated, then someone else must have modified (or deleted) it. You can test that very easily with the sample application by opening multiple edit windows and playing around with the data.
Client side conflict resolution
When the entity framework discovers a concurrency violation when saving your changes, it appropriately throws an OptimisticConcurrencyException. It's then time for you to solve the conflict. In most cases, that means fetching the current values, sending these to the GUI, and let the end user decide what should happen. The data access layer code for inserts and updates will look like this:
foreach (var rule in this.rules)
{
try
{
switch (rule.ChangeTracker.State)
{
case ObjectState.Added:
entities.FerengiRules.AddObject(rule);
entities.SaveChanges();
break;
case ObjectState.Modified:
entities.FerengiRules.ApplyChanges(rule);
entities.SaveChanges();
break;
default:
break;
}
}
catch (OptimisticConcurrencyException)
{
// Return Current Values
// ...
}
}
Server side conflict resolution
The Entity Framework also provides automated conflict resolution strategies that might be useful in some scenarios (although to be honest: I can't think of any). There's a Refresh method that you can use to decide whether it's the client version or the server (store) version that should be persisted when there's a conflict. Here's how the catch-block could look like:
catch (OptimisticConcurrencyException)
{
switch (this.conflictResolution)
{
case ConflictResolution.Default:
throw;
case ConflictResolution.ServerWins:
entities.Refresh(RefreshMode.StoreWins, rule);
entities.SaveChanges();
break;
case ConflictResolution.ClientWins:
entities.Refresh(RefreshMode.ClientWins, rule);
entities.SaveChanges();
break;
default:
break;
}
}
Source Code
Oops ... almost forgot: here's the source code of the whole thing: U2UConsult.EF40.OptimisticConcurrency.Sample.zip (470,96 kb)
Enjoy!
- Posted by Diederik Krols on May 19, 2010
This article describes how to localize a WPF application using the WPF Localization Extension project from Codeplex. On one hand, this is a fine tool. On the other hand, it's a crying shame that WPF developers need to rely on external sources for something as basic as localization. As you know, localization support is nicely integrated in Microsoft's other development stacks, like WinForms and ASP.NET. So far for the ranting, let's get to the solution.
Terminology
Globalization is making your application ready to be localized. This boils down to separating culture-specific elements (texts, images, colors, ...) from the code. The globalization code analysis rules may help you to do this.
Localization is tailoring your application toward a specific language and region by providing these culture-specific elements (e.g. in a resource file or a database).
Options for WPF localization
These are a couple of options for localizing a WPF application:
- use the clumsy and error prone LocBaml tool. Don't get me wrong: I really like the idea of skipping the globalization step and then do localization as an afterthought. But just read the intro of this article for a list of reasons NOT to use LocBaml,
- use classic RESX files, or
- use WPF ResourceDictionaries.
More details about the pros and cons of these alternatives can be found here.
The WPF Localization Extension project
The WPF Localization Extension allows you to localize your application using classic .resx files. The project revolves around a custom markup extension that allows you to declaratively (in XAML) bind control properties to localized resources. The library offers a lot of functionality, but more important: it is well-written and well-documented (at least in its source code). I built a small sample application that walks through some of its features. Here's how this application looks like. You find its source code at the end of this article:

The project is decorated with the following resource files:

Declarative Localization
The markup extension and its namespaces are registered by the following declaration on top your XAML file (you might want to change the project's source code to choose a more appropriate namespace):
xmlns:lex="http://schemas.root- project.org/xaml/presentation"
You can now set up a binding from a control's property to a resource, like this:
<TextBlock Text="{lex:LocText Key=Tomato, Dict=Translations, Assembly=U2UConsult.WPF.Localization.Sample}" />
It's possible to ignore the current culture, and force a specific culture for a binding, like this:
<TextBlock Text="{lex:LocText Key=Duck, Dict=Translations, Assembly=U2UConsult.WPF.Localization.Sample, ForceCulture=nl}" />
My sample application only fetches string resources, but WPF Localization Extension> supports the following resource types out of the box:
- Brush,
- Double,
- FlowDirection,
- Image,
- Text, and
- Thickness.
For other data types you'll need to plug in a Converter.
Programmatic Localization
Sometimes we need to localize a control in source code, e.g. when the control is dynamically created. In this case we can set the binding programmatically, like this:
LocTextExtension loc = new LocTextExtension("U2UConsult.WPF.Localization.Sample:Translations:Pumpkin");
loc.SetBinding(this.PumpkinTextBlock, TextBlock.TextProperty);
If data binding is not needed (or not possible), the you can fallback to a lookup in the .resx file using GetLocalizedObject, like this:
string pinguin = LocalizeDictionary.Instance.GetLocalizedObject<string>(
"U2UConsult.WPF.Localization.Sample",
"Translations",
"Pinguin",
CultureInfo.GetCultureInfo("nl-BE"));
this.PinguinTextBlock.Text = pinguin;
Design time support
Localization at run time is one thing, but as a developer we like to see the result without running the application. The LocalizeDictionary.DesignCulture dependency property provides a Culture for Visual Studio's designers. It can be set in XAML, as follows:
lex:LocalizeDictionary.DesignCulture="nl-BE"
[By the way: the design time support only started working on my VS2010 after I recompiled the codeplex source with VS2010.]
On top of that, the markup extension provides a DesignValue property that sets the value in Visual Studio's Designer, regardless of the (Design-)Culture. Here's a sample:
<TextBlock Text="{lex:LocText Key=Tomato, Dict=Translations, Assembly=U2UConsult.WPF.Localization.Sample, DesignValue=#Tomato#}" />
Here's how these two features look like at design time:

Finally, the markup extension also provides a InitialValue for Blend support.
Missing cultures and missing translations
I guess we all agree that our application should never totally crash if a string can not be found in a resource file, or if the user has an unexpected or unsupported locale. Here are some techniques to get around this.
Missing resources
It's not a good idea to just fallback to a default language for missing entries, without a warning to the end user. In the best case this will only create confusion. But just take a look at the following interlingual homographs and consider what would happen if they appear in the middle of a half-translated window:
- coin is french for corner,
- file is dutch for traffic jam, and
- gift is german for poison
So the invariant culture should NOT be English (or whatever 'real' language), but still remain comprehensible. In my app, the invariant resource file looks like this:

When a translation (or the whole culture) falls back to the invariant culture, the user interface looks like this (Tomato and Pumpkin are not translated):

Missing cultures
If a specific culture is not found (e.g. 'fr-NL') then it makes sense to first check if the language exists ('fr'), and only use the invariant culture as a last resort. That's exactly what the following code does. The 'French' and 'Dzongkha' buttons in the sample application test all code paths:
private void SwitchCulture(string culture)
{
CultureInfo ci = CultureInfo.InvariantCulture;
try
{
ci = new CultureInfo(culture);
}
catch (CultureNotFoundException)
{
try
{
// Try language without region
ci = new CultureInfo(culture.Substring(0, 2));
}
catch (Exception)
{
ci = CultureInfo.InvariantCulture;
}
}
finally
{
LocalizeDictionary.Instance.Culture = ci;
this.CultureTextBlock.Text = ci.EnglishName;
}
}
Source code
Last but not least, here's the source code of the small sample project: U2UConsult.WPF.Localization.Sample.zip (2,41 mb)
Enjoy!
- Posted by Diederik Krols on May 18, 2010
This article explains how to extend Self-Tracking Entities (STE) from Entity Framework (EF) 4.0 with validation logic and (tracking) state change notification, with just minimal impact on the T4 files. We'll build a two-tier application that submits local changes in a WPF application via a WCF service to a database table. The STE are extended with validation logic that is reusable on client and server. The client is notified when the change tracker of an entity changes its state. The tracking state is displayed to the end user as an icon. Here's the client application in action:

For more details on the foundations of building N-Tier apps with EF 4.0, please read Peter Himschoots article.
Source Code
For the fans of the source-code-first approach, here it is: U2UConsult.SelfTrackingEntities.Sample.zip (622,23 kb)
The structure of the solution is as follows:

Preparation
Database table
First you need a SQL Server table. The provided source code contains a script to generate a working copy of the SalesReason table in the AdventureWorks2008 sample database. This is its initial content:

Data Access Layer
When you have it, it's time to fire up Visual Studio.NET. Create a WCF web service project with an ADO.NET Entity Model. Add the SalesReason2 table to the model (I renamed the entity and entity set to SalesReason and SalesReasons respectively). While you're in the designer, generate the code for the ObjectContext and the Self-Tracking Entities (right click in the designer, select "Add Code Generation Item", select "ADO.NET Self-Tracking Entity Generator"). Add the canonical service methods to fetch the full list of SalesReasons, and to add, delete, and update an individual SalesReason. Here's an example (I personally like to combine Add and Update operations in a Save method):
public List<SalesReason> GetSalesReasons()
{
using (AdventureWorks2008Entities model = new AdventureWorks2008Entities())
{
List<SalesReason> result = new List<SalesReason>();
result.AddRange(model.SalesReasons);
return result;
}
}
public void DeleteSalesReason(SalesReason reason)
{
using (AdventureWorks2008Entities model = new AdventureWorks2008Entities())
{
model.SalesReasons.Attach(reason);
model.SalesReasons.DeleteObject(reason);
model.SaveChanges();
}
}
public SalesReason SaveSalesReason(SalesReason reason)
{
using (AdventureWorks2008Entities model = new AdventureWorks2008Entities())
{
reason.ModifiedDate = DateTime.Now;
if (reason.ChangeTracker.State == ObjectState.Added)
{
model.SalesReasons.AddObject(reason);
model.SaveChanges();
reason.AcceptChanges();
return reason;
}
else if (reason.ChangeTracker.State == ObjectState.Modified)
{
model.SalesReasons.ApplyChanges(reason);
model.SaveChanges();
return reason;
}
else
{
return null; // or an exception
}
}
}
Self Tracking Entities
Add a new class library to the project, call it STE. Drag the Model.tt T4 template from the DAL to the STE project. Add a reference to serialization in the STE project. Add a reference to the STE in the DAL project. Everything should compile again now.
WPF Client
Add a WPF application to the solution. In this client project, add a reference to the STE, and a service reference to the DAL. Add a ListBox and some buttons, with straightforward code behind:
private void RefreshSalesReasons()
{
this.salesReasons = this.GetSalesReasons();
this.SalesReasonsListBox.ItemsSource = this.salesReasons;
}
private ObservableCollection<SalesReason> GetSalesReasons()
{
using (DAL.SalesReasonServiceClient client = new DAL.SalesReasonServiceClient())
{
ObservableCollection<SalesReason> result = new ObservableCollection<SalesReason>();
foreach (var item in client.GetSalesReasons())
{
result.Add(item);
}
return result;
}
}
private void Update_Click(object sender, RoutedEventArgs e)
{
SalesReason reason = this.SalesReasonsListBox.SelectedItem as SalesReason;
if (reason != null)
{
reason.Name += " (updated)";
}
}
private void Insert_Click(object sender, RoutedEventArgs e)
{
SalesReason reason = new SalesReason()
{
Name = "Inserted Reason",
ReasonType = "Promotion"
};
reason.MarkAsAdded();
this.salesReasons.Add(reason);
this.SalesReasonsListBox.ScrollIntoView(reason);
}
private void Delete_Click(object sender, RoutedEventArgs e)
{
SalesReason reason = this.SalesReasonsListBox.SelectedItem as SalesReason;
if (reason != null)
{
reason.MarkAsDeleted();
}
}
private void Commit_Click(object sender, RoutedEventArgs e)
{
using (DAL.SalesReasonServiceClient client = new DAL.SalesReasonServiceClient())
{
foreach (var item in this.salesReasons)
{
switch (item.ChangeTracker.State)
{
case ObjectState.Unchanged:
break;
case ObjectState.Added:
client.SaveSalesReason(item);
break;
case ObjectState.Modified:
client.SaveSalesReason(item);
break;
case ObjectState.Deleted:
client.DeleteSalesReason(item);
break;
default:
break;
}
}
this.RefreshSalesReasons();
}
}
Now you're ready to extend the STE with some extra functionality.
Validation
It's nice to have some business rules that may be checked on the client (to provide immediate feedback to the user) as well as on the server (to prevent corrupt data in the database). This can be accomplished by letting the self-tracking entities implement the IDataErrorInfo interface. This interface just contains an indexer (this[]) to validate an individual property, and an Error property that returns the validation state of the whole instance. Letting the STE implement this interface can be easily done by adding a partial class file. The following example lets the entity complain if its name gets shorter than 5 characters:
public partial class SalesReason : IDataErrorInfo
{
public string Error
{
get
{
return this["Name"];
}
}
public string this[string columnName]
{
get
{
if (columnName == "Name")
{
if (string.IsNullOrWhiteSpace(this.Name) || this.Name.Length < 5)
{
return "Name should have at least 5 characters.";
}
}
return string.Empty;
}
}
}
If you add a data template to the XAML with ValidatesOnDataErrors=true in the binding, then the GUI will respond immediately if a business rule is broken.
XAML:
<TextBox
Width="180"
Margin="0 0 10 0">
<Binding
Path="Name"
Mode="TwoWay"
UpdateSourceTrigger="PropertyChanged"
NotifyOnSourceUpdated="True"
NotifyOnTargetUpdated="True"
ValidatesOnDataErrors="True"
ValidatesOnExceptions="True"/>
</TextBox>
Result:

The same rule can also be checked on the server side, to prevent persisting invalid data in the underlying table:
public SalesReason SaveSalesReason(SalesReason reason)
{
if (!string.IsNullOrEmpty(reason.Error))
{
return null; // or an exception
}
...
Notification of Tracking State Change
By default, an STE's tracking state can be fetched by instance.ChangeTracker.State. This is NOT a dependency property, and its setter doesn't call PropertyChanged. Clients can hook an event handler to the ObjectStateChanging event that is raised just before the state changes (there is no ObjectStateChanged event out of the box). You're free to register even handlers in your client, but then you need to continuously keep track of which change tracker belongs to which entity: assignment, lazy loading, and (de)serialization will make this a cumbersome and error prone endeavour.
To me, it seems more logical that an entity would expose its state as a direct property, with change notification through INotifyPropertyChanged. This can be achieved -again- by adding a partial class file:
public partial class SalesReason
{
private string trackingState;
[DataMember]
public string TrackingState
{
get
{
return this.trackingState;
}
set
{
if (this.trackingState != value)
{
this.trackingState = value;
this.OnTrackingStateChanged();
}
}
}
partial void SetTrackingState(string newTrackingState)
{
this.TrackingState = newTrackingState;
}
protected virtual void OnTrackingStateChanged()
{
if (_propertyChanged != null)
{
_propertyChanged(this, new PropertyChangedEventArgs("TrackingState"));
}
}
}
The only thing you need to do now, is to make sure that the SetTrackingState method is called at the right moment. The end of the HandleObjectStateChanging looks like a nice candidate. Unfortunately this requires a modification of the code that was generated by the T4 template. For performance reasons I used a partial method for this. This is the extract from the SalesReason.cs file:
// This is a new definition
partial void SetTrackingState(string trackingState);
//
private void HandleObjectStateChanging(object sender, ObjectStateChangingEventArgs e)
{
//
this.SetTrackingState(e.NewState.ToString()); // This is a new line
//
if (e.NewState == ObjectState.Deleted)
{
ClearNavigationProperties();
}
}
Just modifiying the generated code is probably not good enough: if later on you need to update your STE (e.g. after adding a column to the underlying table), the modifications will get overriden again. So you might want to modify the source code of the T4 template (search for the HandleObjectStateChanding method and adapt the source code). Fortunately this is a no-brainer: most of the T4 template is just like a C# source code file, but without IntelliSense. The rest of the file looks more like classic ASP - ugh.
Anyway, you end up with a TrackingStatus property to which you can bind user interface elements, wiith or without a converter in between. In the sample application I bound an image to the tracking state:
<Image
Source="{Binding
Path=TrackingState,
Converter={StaticResource ImageConverter}}"
Width="24" Height="24" />
Here's how it looks like:

In general, I think there are not enough partial methods defined and called in the Entity Framework T4 templates. To be frank: 'not enough' is an understatement: I didn't find a single partial method.
- Posted by Diederik Krols on May 2, 2010
The Windows 7 taskbar comes with nice features like a thumbnail preview with clickable thumb buttons, a progress bar in the taskbar item, and jump list items and task items in its context menu. Access to the shell integration API from the managed world is done through the System.Windows.Shell namespace that comes with .NET 4.0. This namespace decorates Window and Application with some new dependency properties, so you better make use of it.
Here's an overview of the TaskbarItemIfo object model:

The screenshot comes from a small application to demonstrate this object model. Here's how the main form looks like:

The Chart and Pie buttons switch the displayed chart type, the Recalculate button simulates a long running operation (just an excuse for showing the progress bar). Here's the alternative view:

TaskBarItemInfo
When hovering with the mouse over the taskbar item, it shows only the relevant part of the screen in its thumbnail, and operational buttons - just like in the first image above.
Everything is defined in the xaml as follows:
<Window.TaskbarItemInfo>
<TaskbarItemInfo
x:Name="taskBarItemInfo1"
ThumbnailClipMargin="5 95 100 65"
Description="Taskbar Item Info Sample">
<TaskbarItemInfo.ThumbButtonInfos>
<ThumbButtonInfoCollection>
<ThumbButtonInfo
Click="Recalculate_Click"
Description="Recalculate"
ImageSource="/Assets/Images/refresh.png" />
<ThumbButtonInfo
Click="BarChart_Click"
Description="Bar Chart"
ImageSource="/Assets/Images/chart.png" />
<ThumbButtonInfo
Click="Pie_Click"
Description="Pie Chart"
ImageSource="/Assets/Images/pie.png"/>
</ThumbButtonInfoCollection>
</TaskbarItemInfo.ThumbButtonInfos>
</TaskbarItemInfo>
</Window.TaskbarItemInfo>
I hooked the thumb buttons to the same click event as their counterparts on the main form, but everything also works with command bindings. In fact, the taskbar item has more FSI than the original app, that's Functionality per Square Inch.
Overlay
The taskbar icon can be decorated with an extra image to inform the user about the state of the application. This overlay image can be set in XAML (through data binding, if you want), but in a lot of cases you'll want to change the image from source code. Here's how this is done:
this.taskBarItemInfo1.Overlay = new BitmapImage(
new Uri(
@"..\..\Assets\Images\pie.png",
UriKind.Relative));
ProgressBar
The task bar item can be decorated with a progress bar. This is how it's done from C#:
this.taskBarItemInfo1.ProgressState = TaskbarItemProgressState.Normal;
for (double d = 0; d < 80; d++)
{
this.taskBarItemInfo1.ProgressValue = d / 100;
Thread.Sleep(50);
}
this.taskBarItemInfo1.ProgressState = TaskbarItemProgressState.Paused;
Thread.Sleep(2000);
this.taskBarItemInfo1.ProgressState = TaskbarItemProgressState.Error;
for (double d = 80; d > 0; d--)
{
this.taskBarItemInfo1.ProgressValue = d / 100;
Thread.Sleep(50);
}
this.taskBarItemInfo1.ProgressState = TaskbarItemProgressState.None;
Here's the progress bar in action:

ProgressValue is a value between 0 and 1, while ProgressState is one of the following:
- None: well - no progress bar,
- Normal: a green bar,
- Paused: a yellow bar,
- Error: a red bar,
- Indeteminate: a zigzagging green bar (very nice in combination with a wait cursor on the form)
Source Code
As always you get the full source code (VS 2010): U2UConsult.Windows7.Sample.zip (864,23 kb)
Enjoy!
- Posted by Diederik Krols on April 19, 2010
WCF Data Services 4.0 (formerly known as ADO.NET Data Services, formerly known as Astoria) is one of the ways to expose an Entity Data Model from Entity Framework 4.0 in a RESTful / OData way. This article explains how to create such a data service and how to consume it with a browser and with a WPF client.
The Data Service
Start with an empty ASP.NET Application:

Add a WCF Data Service to it:

Also add an Entity Data Model to the ASP.NET project:

Follow the Model Wizard to create a model containing entities on top of the Employee and Person tables from the AdventureWorks2008 database:
In the designer, you should have something like this:

A lot of code was generated, let's add our own 50ct in the service's code behind. First let it inherit from DataService<AdventureWorks2008Entities>:
public class WcfDataService : DataService<AdventureWorks2008Entities>
{ .. }
Then modify the InitializeService method as follows. This exposes all operations and grants all access rights (not really a production setting):
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
Believe it or not, we're done (for the first part): the entity model is now exposed in a RESTful way. At the root URL you get an overview of the exposed entities. In the attached sample the root URL is "http://localhost:1544/WcfDataService.svc", but you may of course end up with another port number:

At the "/Employees" address you find all employees:

In your browser this list of employees may appear like this:

This means it's time to -at least temporarily- disable your rss feed reading view. Here's how to do this in IE:
To reach an individual entity, just type its primary key value in parentheses at the end of the URL, like "http://localhost:1544/WcFDataService.svc/Employees(1)":

You can navigate via the relationships between entities. This is how to reach the Person entity, connected to the first Employee. The URL is "http://localhost:1544/WcfDataService.svc/Employees(1)/Person":

Other OData URI options options can be found here, including:
- Filtering: http://localhost:1544/WcfDataService.svc/Employees?$filter=JobTitle eq 'Chief Executive Officer'
- Projection: http://localhost:1544/WcfDataService.svc/Employees?$select=JobTitle,Gender
- Client side paging: http://localhost:1544/WcfDataService.svc/Employees?$skip=5&$top=2
Version 4.0 also includes support for server side paging. This gives you some control over the resources. Add the following line in the InitializeService method:
config.SetEntitySetPageSize("Employees", 3);
Only 3 employees will be returned now, even if the client requested all:

A Client
Enough XML for now. WCF Data Services also expose a client side model that allows you to use LINQ.
Create a new WPF application:

Add a Service Reference to the WFC Data Service:

Decorate the Window with two buttons and a listbox. It should look more or less like this:

The ListBox will display Employee entities through a data template (OK, that's XML again):
<ListBox
Name="employeesListBox"
ItemTemplate="{StaticResource EmployeeTemplate}"
Margin="4"
Grid.Row="1"/>
Here's the template. It not only binds to Employee properties, but also to Person attributes:
<DataTemplate
x:Key="EmployeeTemplate">
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock
Text="{Binding Path=Person.FirstName}"
FontWeight="Bold"
Padding="0 0 2 0"/>
<TextBlock
Text="{Binding Path=Person.LastName}"
FontWeight="Bold"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock
Text="{Binding Path=JobTitle}"
Width="180"/>
<TextBlock
Text="{Binding Path=VacationHours}"
Width="60"
TextAlignment="Right" />
<TextBlock
Text=" vacation hours taken." />
</StackPanel>
</StackPanel>
</DataTemplate>
The Populate-Button fetches some Employee entities together with their related Person entity, and binds the collection to the ListBox (in version 4.0 two-way bindings are supported for WPF):
private void Populate_Click(object sender, RoutedEventArgs e)
{
AdventureWorks2008Entities svc =
new AdventureWorks2008Entities(
new Uri("http://localhost:1544/WcfDataService.svc"));
this.employeesListBox.ItemsSource =
svc.Employees.Expand("Person").Where(emp => emp.BusinessEntityID < 100);
}
Here's the result:

The Update-Button updates the number of vacation hours of the company's CEO. It fetches the Employee, updates its VacationHours property, then tells the state manager to update the employee's state, and eventually persists the data:
private void Update_Click(object sender, RoutedEventArgs e)
{
AdventureWorks2008Entities svc =
new AdventureWorks2008Entities(
new Uri("http://localhost:1544/WcfDataService.svc"));
Employee employee =
svc.Employees.Where(emp => emp.BusinessEntityID == 1).First();
employee.VacationHours++;
svc.UpdateObject(employee);
svc.SaveChanges();
}
If you now repopulate the listbox, you will see the increased value:

Source Code
Here's the full source code of this sample (just requires VS2010 with no extra downloads): U2UConsult.WcfDataServices.Sample.zip (96,59 kb)
Enjoy!
- Posted by Diederik Krols on April 11, 2010
Welcome to the lean, mean, no Vicodin, U2U Consult PRISM machine. (595 seconds left.) CompositeWPF, or Composite Application Guidance (CAG) including Composite Application Library (CAL) is still commonly referred to as PRISM. The software component -CAL- extends Windows Presentation Foundation (WPF) with Modularity, Dependency Injection, Loosely Coupled Events, Distributed Commanding, and Run-Time Module Discovery, while leveraging the classic WPF principles and design concepts such as Dependency Properties, Routed Events, Commanding, Data Binding and Data Templates. In a composite application, functionality is embedded in small parts called modules. Each module is an autonomous, dynamically discoverable and loadable piece, containing its own view, logic and services. A module is preferably designed and implemented according to the MVP-pattern. The main application contains one or more shells: empty windows with regions that contain the placeholders for the module's views. This article walks through a small sample CAL-based solution. Here's how the GUI looks like, in sober black and white:
If you would build it as a single monolithic application, it would take you 10 minutes to develop. The CAL-based implementation is actually composed of 6 (six) independent projects with hardly any references to one another:

And now 10 minutes is maybe even too long to explain how everything works. Anyway, I'm going to give it a try!
Shells and Regions
A Composite WPF application starts as a regular WPF application with references to all of the CAL-assemblies (the ones starting with Microsoft in the next screen shot):

The CompositeWPF namespace is imported into the XAML of the Main Window:
xmlns:cal="http://www.codeplex.com/CompositeWPF"
Regions are added in the XAML by creating ItemControl and ContentControl instances with a RegionName. This dependency property exposes the region's name to CAL's region manager:
<ItemsControl
x:Name="MainRegion"
cal:RegionManager.RegionName="MainRegion" />
Modules and Dependency Injection
The AboutModule is kind of a "Hello World" module: it just statically displays some company's logo. A module generally doesn't need to call the whole CAL-shebang, so it can get away with less references:

The module itself is a class that implements the IModule interface. It is decorated with the Module atttribute to allow dynamic discovery:
[Module(ModuleName = "AboutModule")]
public class AboutModule : IModule
{
// ...
}
The graphical part of the module is implemented as a WPF UserControl and saved in a Views subfolder. It needs no special references or interfaces:

The IRegionManager parameter in the module's constructor will be discovered and populated by CAL's Dependency Injection Container (Unity, that is). It gives the module and the view access to the shell's region manager:
public AboutModule(IRegionManager regionManager)
{
this.regionManager = regionManager;
}
CAL will call the module's constructor, and then its Initialize method, where the view is registered in the named region:
public void Initialize()
{
this.regionManager.RegisterViewWithRegion(
"MainRegion",
typeof(Views.U2UConsultLogo));
}
Bootstrapping the Application
The main project contains a bootstrapper. It makes sure that CAL's components are properly initialized before anything else happens:
internal class Bootstrapper : UnityBootstrapper
{
// ...
}
The OnStartUp of the application is overridden:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Bootstrapper bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
Since the bootstrapper will do the initialization, the StartupUri is removed from app.xaml:
<Application x:Class="U2UConsult.CAL.Sample.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!--StartupUri="Shell.xaml"-->
</Application>
Back in the bootstrapper, the CreateShell() method is overridden to make sure that the shell gets loaded and displayed:
protected override DependencyObject CreateShell()
{
Shell shell = new Shell();
shell.Show();
return shell;
}
The GetModuleCatalog() method is also overridden. It returns the collection of discovered modules. There are different types of module catalog subclasses that can inspect directories, configuration files, or even XAML files. The following code is an example of using the ModuleCatalog base class itself. This way of statically loading modules requires a reference from the shell project to the module project(s), so it's only used while developing/debugging:
protected override IModuleCatalog GetModuleCatalog()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule(typeof(AboutModule.AboutModule));
return catalog;
}
Model View Presenter
The region at the bottom of the main window's shell displays the application's status. XAML-wise it's just a textblock. When it is is implemented using a (lightweight) MVP-pattern and packaged as a CAL module, it looks rather impressive:

The view contains a textblock which is bound to a property in the PresentationModel:
<TextBlock
TextWrapping="NoWrap"
Text="{Binding StatusMessage}"/>
The StatusModule requires more of the CAL feature set than the AboutModule, so it has more injected stuff (i.e. parameters in its constructor):
public StatusModule(
IUnityContainer container,
IRegionManager regionManager,
IEventAggregator eventAggregator)
{
this.container = container;
this.regionManager = regionManager;
this.eventAggregator = eventAggregator;
}
The registration of the views and services that are provided by the module, is nicely factored out to a seperate method:
public void RegisterViewsAndServices()
{
this.container.RegisterType<Views.IStatusView, Views.StatusView>(
new ContainerControlledLifetimeManager());
this.container.RegisterType<PresentationModels.IStatusPresentationModel, PresentationModels.StatusPresentationModel>(
new ContainerControlledLifetimeManager());
}
And here's the module's Initialize-method:
public void Initialize()
{
this.RegisterViewsAndServices();
PresentationModels.IStatusPresentationModel model =
this.container.Resolve<PresentationModels.StatusPresentationModel>();
IRegion statusRegion = this.regionManager.Regions["StatusRegion"];
statusRegion.Add(model.View);
}
The PresentationModel gets its view from Dependency Injection, again through a parameter in its constructor. So here's where the model and its view are connected:
public StatusPresentationModel(Views.IStatusView view)
{
this.view = view;
view.Model = this;
this.StatusMessage = "The status module is operational.";
}
Distributed Events
The SelectionModule allows the end user to select an option, after which it will update the application's status. This status is displayed in the status region at the bottom of the shell:

Some corners were cut here: the project only contains a Module and a View. Anyway, the SelectionModule needs to communicate with the StatusModule. Both modules share an event -an instance of CompositePresentationEvent- through CAL's event aggregator, a mechanism for distributed events. The reference to this event aggregator comes from ... Dependency Injection indeed: the constructors of SelectionModule, SelectionView, StatusModule, and StatusPresentationModel take an IEventAggrator parameter.
A global StatusReported event is declared in the application. The SelectionModule raises this event via a call to Publish():
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
this.selectedOption = e.Source as RadioButton;
string status = string.Format(
"You selected '{0}'.",
this.selectedOption.Content.ToString());
this.eventAggregator.GetEvent<Infrastructure.StatusReportedEvent>().Publish(status);
}
The StatusModule has a local event handler for the same event:
private void OnAppStatusChanged(string message)
{
this.StatusMessage = message;
}
It registers that handler with CAL through a Subscribe-call:
this.eventAggregator.GetEvent<Infrastructure.StatusReportedEvent>()
.Subscribe(this.OnAppStatusChanged, ThreadOption.UIThread, true);
The handler itself is straightforward - data binding will update the view:
private void OnAppStatusChanged(string message)
{
this.StatusMessage = message;
}
As you observed, the reference to the event is not by name (like for a region), but it is made by type. Both modules, as well as all other modules that want to notify status changes, need to know the event type:
public class StatusReportedEvent : CompositePresentationEvent<string> { }
The type is defined is a so-called Infrastructure project to which multiple modules -and probably even the shell- will have a reference. To call a spade a bloody shovel: GlobalVariables would be a more appropriate name for this assembly. But that name seems to upset software architects.
Composite Commands
In WPF we like to communicate through Commands, not Events. So here's the next use case. The shell has a toolbar region on top. This will host the toolbar buttons of each individual module, but also some global commands. A global "Clear" button clears any registered view, and updates the status:

The global command itself is an instance of CAL's CompositeCommand class - a command that can have child commands. It is defined in the Infrastructure project, together with a proxy to it that can be overridden for unit testing:
namespace Infrastructure
{
using Microsoft.Practices.Composite.Presentation.Commands;
public static class GlobalCommands
{
public static CompositeCommand ClearCommand = new CompositeCommand();
}
public class ClearCommandProxy
{
public virtual CompositeCommand ClearCommand
{
get
{
return GlobalCommands.ClearCommand;
}
}
}
}
The button with the large "X" is linked to the global command through its XAML:
<UserControl
x:Class="GlobalCommandsModule.Views.SelectionCommandView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:inf="clr-namespace:Infrastructure;assembly=Infrastructure" >
<Button Command="{x:Static inf:GlobalCommands.ClearCommand}" ... />
</UserControl>
When the SelectionView is loaded, it hooks a DelegateCommand to the global ClearCommand:
public SelectionView(
IEventAggregator eventAggregator,
ClearCommandProxy commandProxy)
{
InitializeComponent();
this.eventAggregator = eventAggregator;
this.clearCommand = new DelegateCommand<object>(this.Clear, this.CanClear);
commandProxy.ClearCommand.RegisterCommand(this.clearCommand);
}
DelegateCommand is yet another CAL-class. It lets you directly specify the ICommand-code for Execute and CanExecute as delegates.
Dynamic Module Lookup
During development it makes sense to keep a reference from the host application to each module, and load it statically into the module catalog. At the end of the day, it's better to cut that reference and go for dynamic lookup. So all modules are compiled and their dll's gathered in a "Modules"-folder:

The "production"-bootstrapper makes use of one of the more specialized catalog modules:
protected override IModuleCatalog GetModuleCatalog()
{
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog();
catalog.ModulePath = "../../Modules";
return catalog;
}
Source Code
Here's the full source code of the sample application: U2UConsult.CAL.Sample.zip (1,79 mb)
Enjoy!
- Posted by Diederik Krols on March 22, 2010
Here is (yet another) WPF circular busy indicator control based on Sacha Barber's Circular Progress Bar. This type of control is useful to indicate that a part of your user interface is waiting for the result of an asynchronous call. The user control is hosts a Canvas in which 9 circles are displayed, with decreasing opacity. A rotation transformation produces the spinning effect. Here's its default look:

The canvas is embedded in a Viewbox for easy resizing. To keep the circles round, the control is kept square (you might want to read this again ;-). This is done by binding its Width to its Height. It's a two-way binding, so you can set either property to set the control's size:
Width="{Binding RelativeSource={RelativeSource Self}, Path=Height, Mode=TwoWay}"
The CPU-consuming rotation is only triggered when the Visibility is set to Visible. The control keeps a low GUI profile: it is by default invisible, its background is transparent, it even has a zero opacity:
Visibility="Hidden"
IsVisibleChanged="HandleVisibleChanged"
Opacity="0"
Background="Transparent"
Here's the code that is executed when the Visibility changes:
/// <summary>
/// Visibility property was changed: start or stop spinning.
/// </summary>
/// <param name="sender">Sender of the event.</param>
/// <param name="e">Event arguments.</param>
private void HandleVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
// Don't give the developer a headache.
if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
return;
}
bool isVisible = (bool)e.NewValue;
if (isVisible)
{
this.StartDelay();
}
else
{
this.StopSpinning();
}
}
The Fill property of the ellipses is bound to the control's Foreground property, through a Style. This is very intuitive, and requires no extra dependency properties:
<Style
TargetType="Ellipse">
<Setter Property="Width" Value="20" />
<Setter Property="Height" Value="20" />
<Setter Property="Stretch" Value="Fill" />
<Setter Property="Fill">
<Setter.Value>
<Binding Path="Foreground">
<Binding.RelativeSource>
<RelativeSource
Mode="FindAncestor"
AncestorType="{x:Type local:CircularProgressBar}" />
</Binding.RelativeSource>
</Binding>
</Setter.Value>
</Setter>
</Style>
Remember that the Foreground property is more than just a color, it can be any type of Brush. Here are some examples:
|

|

|

|
| SolidBrush |
RadialGradientBrush |
ImageBrush |
To give you control over the spinning speed, I created a dependency property called RotationsPerMinute:
/// <summary>
/// Spinning Speed. Default is 60, that's one rotation per second.
/// </summary>
public static readonly DependencyProperty RotationsPerMinuteProperty =
DependencyProperty.Register(
"RotationsPerMinute",
typeof(double),
typeof(CircularProgressBar),
new PropertyMetadata(60.0));
There is a similar dependency property that allows to to specify the delay before the control becomes visible: StartupDelay. This is actually why I needed to start with a zero Opacity. When the control becomes visible, we wait for a short while before setting its Opacity to 1. This keeps the user interface nice and easy without too briefly flashing indicators. I (re-)used the animation timer to implement the delay. This way we are sure not to freeze the user interface. To show the user that something was started, we show a wait cursor while ... waiting. When the control becomes really visible, we reset the cursor to its original image:
/// <summary>
/// Startup Delay.
/// </summary>
private void StartDelay()
{
this.originalCursor = Mouse.OverrideCursor;
Mouse.OverrideCursor = Cursors.Wait;
// Startup
this.animationTimer.Interval = new TimeSpan(0, 0, 0, 0, this.StartupDelay);
this.animationTimer.Tick += this.StartSpinning;
this.animationTimer.Start();
}
/// <summary>
/// Start Spinning.
/// </summary>
/// <param name="sender">Sender of the event.</param>
/// <param name="e">Event Arguments.</param>
private void StartSpinning(object sender, EventArgs e)
{
this.animationTimer.Stop();
this.animationTimer.Tick -= this.StartSpinning;
// 60 secs per minute, 1000 millisecs per sec, 10 rotations per full circle:
this.animationTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)(6000 / this.RotationsPerMinute));
this.animationTimer.Tick += this.HandleAnimationTick;
this.animationTimer.Start();
this.Opacity = 1;
Mouse.OverrideCursor = originalCursor;
}
Here's how you use the control (all properties have a default value, so it could be shorter):
<local:CircularProgressBar
StartupDelay="500"
Foreground="SteelBlue"
RotationsPerMinute="120"
Width="200" />
I also built a sample client, so you can experiment with the settings. Here's how it looks like:

Here's the full source code: U2UConsult.CircularProgressBar.Sample.zip (42,66 kb)
Enjoy !
- Posted by Diederik Krols on March 12, 2010
Did you ever want to embed a browser in a WPF application, to host a help file or to access an intranet site? Did you ever want to impress your girl friend by building a fancy browser yourself, like YouCube? If so, your obvious choice would be to drag and drop a native WebBrowser Control into your application. Well, hold your horses (or rather: hold your mouse). The standard WPF WebBrowser control that sits in your Visual Studio toolbox is just an ultra-thin wrapper around Microsoft's Internet Explorer ActiveX. This wrapper is so thin that it's not even aware of such celebrated WPF features as transformations and styles. If you use the control in any container that is just a little bit dynamic, then it will simply go berserk. Here's an example. I wrapped a native WebBrowser control in a ScrollViewer, then applied some gentle transformations. The browser just walks happily over the entire GUI:

So if you're planning to build a user experience like in the following screenshot (which is the already mentioned YouCube), then forget about Internet Explorer, and start looking for an alternative:

Ingredients
The alternative solution basically requires 3 ingredients:
- a browser, obviously,
- an SDK to get programmatic access to the browser's core functionality, and
- a WPF wrapper that does more than just adding a WindowsFormsHost element.
A Browser
An interesting alternative comes from an unexpected source:Google. Chromium is the open source browser on which Google Chrome is based. It's unbranded, it doesn't automatically update, and it doesn't send crash reports and usage statistics to the Googleplex (all details here). Cool, that's just what we want in our application!
An SDK
Awesomium is a platform independent C++ software library that allows developers to embed Chromium in their own applications. Older versions were released as open source, but the code is currently being productized.
A real WPF wrapper
Chris Cavanagh built WPF Chromium, which exposes Awesomium as a .NET and WPF control. Feel free to check the Sources and References.
To use WPF Chromium's WebBrowser control in your own application, add a reference to the .NET dll's:

You also need to make sure that the (non-.NET) Awesomium dll's end up next to your executable:

Finally, don't forget to compile in 32-bit mode:

My guess: we now have a serious challenger for IE.
Battle of the Browsers
I built a little torture chamber
to see how far we can stretch the native IE browser and WPF Chromium. The sample application straps a browser in a ScrollViewer and tries to shake it around with transformations. It also implements scrollwheel-zooming and left-button panning, and last but not least: it tries to override the scrollbar style. Here are some observations:
Functionality
Both browsers behave ... like a browser. Both were tested against search engines, sites with long pages -like this blog-, sites with lots of images, and sites with silverlight, flash, or Ajax. Chromium is better and faster on sites with complex javascripts (e.g. Ajax sites). An illustration: IE continuously throws errors in your face if you visit this site:

On the other hand, IE is a much better Silverlight host. When you navigate to this beautiful but technically rather simple Silverlight site, WPF Chromium -or the underlying Awesomium- experiences problems in tracking the mouse position:

This is as good as it gets for the Internet Explorer ActiveX. For the rest of the article, you may ignore it: the control browses but don't expect anything else from it. And by the way: there's no improvement on the horizon: WPF 4.0 still has the same IE ActiveX wrapper.
Transformations
A small test with some slider controls rapidly reveals that transformations are not an issue for WPF Chromium. Here's an example:

Zooming via a slider control is not so sexy; so I implemented zooming through the scrollwheel. Works fine. And now that we're talking about the scrollwheel: both browsers support scrollwheel panning. Unfortunately Chromium doesn't show the cursors (that's a weird user experience). So just for fun I implemented left-button panning. By holding the left button and moving the cursor, you can drag the underlying bitmap around. It's a nice replacement of scrolling, but the first symptoms of overstressing the control appeared: you need to specify a fixed size for the displayed page (continue reading for more details).
Styling
There's not much to style in a Browser control: it just renders a bitmap, right ? Wrong ! To offer you the pleasure of scrolling, a browser calculates the estimated size of the rendered page. It then displays its own set of native Windows GDI scroll bars
. You can't override these scrollbars, but you can hide them, and wrap the browser control in a -stylable- WPF ScrollViewer control. You need to know the estimated size of the underlying (virtual) bitmap, which unfortunately is not accessible. As a work around set it to fixed size. If you set it too small, you can only scroll through a part of the site, but setting it too large will horribly slow down the scrolling experience. Here's an example of styled scrollbars (remember: de gustibus et coloribus non est disputandum also applies to styles):

Source Code
Here it is, a demo of Chromium and Awesomium, by U2UConsultium
: U2UConsult.ChromiumBrowser.Sample.zip (9,09 mb)
Enjoy !
- Posted by Diederik Krols on February 28, 2010
The accordion is a musical instrument invented in Europe in the beginning of the 19th century. It produces music (or rather noise) by expanding and collapsing it while pressing buttons. This metaphor is applied to software: you may know the Accordion user interface control from Microsoft Outlook's navigation bar. In the last couple of years the control appeared in an ASP.NET AJAX implementation and a SilverLight implementation. Recently, the latter was ported to WPF and published as part of the February 2010 release of the WPF Toolkit. This article describes how to use this great WPF control.
Introduction
The Accordion is an ItemsControl that allows you to provide multiple panes and expand them one at a time (well, by default). The items shown are instances of AccordionItem. Clicking on a header will expand (actually 'select') or collapse the item's content. The Accordion class carries the usual responsibilities of an ItemsControl, like providing templates for header and content, and managing the selected items (plural, that is). On top of that, it supports the following extra properties:
- SelectionMode: One, OneOrMore, ZeroOrOne, or ZeroOrMore
- ExpandDirection: Left, Right, Up, or Down
- SelectionSequence: Simultaneous or CollapseBeforeExpand [I'm pretty sure that this one doesn't work in the WPF version]
Hello World
Let's go for a first test-drive. Download the toolkit, create a new WPF project, and add the following two references:

Register the namespace in your xaml:
xmlns:layoutToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Layout.Toolkit"
Then drop the following code in the window:
<layoutToolkit:Accordion>
<layoutToolkit:AccordionItem Header="Red">
<Rectangle Fill="Red" Height="120" Width="200" />
</layoutToolkit:AccordionItem>
<layoutToolkit:AccordionItem Header="Orange">
<Rectangle Fill="Orange" Height="120" Width="200" />
</layoutToolkit:AccordionItem>
<layoutToolkit:AccordionItem Header="Yellow">
<Rectangle Fill="Yellow" Height="120" Width="200" />
</layoutToolkit:AccordionItem>
<layoutToolkit:AccordionItem Header="Green">
<Rectangle Fill="Green" Height="120" Width="200" />
</layoutToolkit:AccordionItem>
<layoutToolkit:AccordionItem Header="Blue">
<Rectangle Fill="Blue" Height="120" Width="200" />
</layoutToolkit:AccordionItem>
<layoutToolkit:AccordionItem Header="Indigo">
<Rectangle Fill="Indigo" Height="120" Width="200" />
</layoutToolkit:AccordionItem>
<layoutToolkit:AccordionItem Header="Violet">
<Rectangle Fill="Violet" Height="120" Width="200" />
</layoutToolkit:AccordionItem>
</layoutToolkit:Accordion>
You end up with sir Isaac Newton's 7 colors of the rainbow:

The ExpandDirection property -unsurprisingly- changes the direction in which the items expand. Under the hood, a rotation transformation is applied to the header, so be careful when using images. This code:
<layoutToolkit:Accordion ExpandDirection="Right">
will transform our accordion like this:

In some applications you may want to open an item just by hovering over its header, instead of clicking. This behavior doesn't come out of the box, but it's easy to implement: just register a handler for the MouseEnter event for each AccordionItem:
C#
private void AccordionItem_MouseEnter(object sender, MouseEventArgs e)
{
AccordionItem item = sender as AccordionItem;
item.IsSelected = true;
}
XAML
<layoutToolkit:Accordion ExpandDirection="Right">
<layoutToolkit:Accordion.Resources>
<Style TargetType="{x:Type layoutToolkit:AccordionItem}">
<EventSetter Event="MouseEnter" Handler="AccordionItem_MouseEnter" />
</Style>
</layoutToolkit:Accordion.Resources>
<layoutToolkit:AccordionItem Header="Red">
Deeper dive
I decided to build a test application (or torture chamber) to figure out whether or not the control is ready to be used in a production application. An Accordion is used a main navigation control, displaying more than just rectangles: a TextBox, a picture library inspired by the rainbow accordion, a control with a variable height (a TreeView), and a control that behaves badly in any WPF application (the WPF WebBrowser is just a thin wrapper around the IE ActiveX). Here are a couple of screenshots:

Sizing
In their default style, the accordion and its items only occupy the space they need, so smaller content also shrinks the headers:

That's why the main navigation accordion has its HorizontalAlignment set to Stretch. While the width of the main navigation accordion is fixed, its height will remain unpredictable - specifically if multiple items can be selected/expanded. A good old scrollbar will do:

By the way, the size of an item doesn't change dynamically. In our sample application, the expansion of treeview items will just add a scrollbar, not push down the accordion's headers:

Only when the same item is unselected and then reselected, the new height is applied:

The picture library needs a more predictable behavior (fixed height and width), otherwise you end up with unacceptable looks - like a shrunk accordion, or headers being pushed out of sight:

Here's how to deal with this:
<Style TargetType="Image">
<Setter Property="Stretch" Value="UniformToFill" />
<Setter Property="Height" Value="280" />
<Setter Property="Width" Value="400" />
</Style>
Styling
The application is styled through the very popular WPF Themes, yet another port from SilverLight. Unfortunately the libraries don't contain styles for Toolkit controls (yet). The default styles for the Accordion are not really innovative - the selected item gets the same style as the selected date in a Calendar control:

So download the WPF Toolkit's source code, and copy-paste the relevant styles into a resource dictionary:

These are the relevant styles:
- AccordionButton: displays the animated arrow in the header,
- ExpandableContentControl: displays the item's content,
- Accordion: displays the container,
- AccordionItem: displays the item, basically a 2x2 grid, and
- TransitioningContentControl: starts the animation when content changes.
Now you have access to the whole look and feel of the control. Just don't forget to register the resource dictionary in your XAML:
<Grid.Resources>
<ResourceDictionary Source="Themes\CustomAccordion.xaml" />
</Grid.Resources>
Source Code
Here's the full source code of the sample project: U2UConsult.WPFToolkit.Accordion.Sample.zip (1,98 mb).
Enjoy !