Locations

Blog Stats

Archive for the ‘Silverlight’ Category

Introduction

This post presents an early prototype of ‘LINQ to Visual Tree’ for Silverlight 2 and WPF applications. The ultimate goal is to provide applications with the ability to quickly and easily query the Silverlight 2 or WPF Visual Tree via LINQ to Objects.

The prototype provides this functionality by enabling enumeration of an application’s in-memory Visual Tree through the IEnumerable<T> interface. This is distinct to implementing a custom query provider: the prototype does not implement IQueryable<T> or execute and translate expression trees.

This post demonstrates the basics so far and makes the prototype available for download, it’s aim is to get feedback and ideas on how the simple API can be improved.

Trees in Silverlight and WPF

The one fundamental tree of objects that make up a Silverlight 2 or WPF application is the object tree. WPF provides two conceptual views of the object tree called the logical tree and the visual tree that if combined would expose the full object tree. The two conceptual trees are exposed via the LogicalTreeHelper and VisualTreeHelper static classes respectively. The logical tree is a map of elements in the object tree’s element hierarchy (defined in Xaml or in code) that make up an applications user interface, including inferred elements not explicitly typed by the programmer. The visual tree is a map of elements in the object tree’s element hierarchy that derive from Visual or Visual3D, each element is exploded into it’s constituent visual ingredient elements.

Silverlight does not expose the full object tree, there is more than likely a logical tree behind the scenes but there is currently no LogicalTreeHelper static class to expose it. Silverlight does however expose a visual tree through VisualTreeHelper but the Visual and Visual3D types do not exist in the API. The criteria for an object’s inclusion in the Silverlight visual tree according to MSDN is that the object has a "rendering implication".

LINQ to Visual Tree

So every Silverlight and WPF application has a Visual Tree exposed through VisualTreeHelper. ‘LINQ to Visual Tree’ extends this model by enabling enumeration of the results returned from VisualTreeHelper for an object and it’s descendants. The prototype is exactly two days old – I’m still experimenting at this stage, it currently consists of the following two extension methods:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Windows;

using System.Windows.Media;

namespace LinqToVisualTree.Common

{

publicstaticclassVisualEnumerable

{

///<summary>

/// Gets the Visual Tree filtered by Type for a DependencyObject with that DependencyObject as the root.

Although there are currently only two extension methods, they provide an abundance of scope for querying the Visual Tree in Silverlight or WPF. Let’s take a look at some usage scenarios from the code download to see how ‘LINQ to Visual Tree’ can be used in practice to query the Visual Tree of a Silverlight 2 application consisting of the following simple Xaml:

Xaml similar to the above is also used for the test WPF application in the code download, for testing it’s really the hierarchy of the elements in the Xaml that is important – this can be visualized as follows:

The code download defines seven tasks that demonstrate how to use the ‘LINQ to Visual Tree’ API, starting off with basic queries and progressing to slightly more involved ones. Each task shows the code to produce the required result using both Extension Method syntax and LINQ syntax. Each task is represented by a method called from the Page_Loaded event handler defined in the above Xaml:

///<summary>

/// Task 1: Get the Visual Tree of this UserControl

///</summary>

privatevoid Task1()

{

// Extension Method syntax

var pageTree1 = this.GetVisualTree();

// Linq syntax

var pageTree2 = from v inthis.GetVisualTree()

select v;

Debug.Assert(pageTree1.SequenceEqual(pageTree2));

}

Silverlight Result

WPF Result

///<summary>

/// Task 2: Get all the TextBox controls in this UserControl's Visual Tree

Feel free to download the code and run the tasks to see how the API is used from both Silverlight and WPF. As I say I’m still experimenting with this so I’d love to hear your suggestions and get feedback and ideas on how the simple API can be improved.

The ItemsControl in Silverlight 2 is the base type for a number of list based UI controls:

It’s at a place in it’s class hierarchy that means it provides just enough to get you going with list output. Controls further down the inheritance hierarchy from ItemsControl tend to specialise it’s functionality by providing the ability to select or edit items in the list in slightly distinct ways. The items in an ItemsControl can be defined in Xaml or generated dynamically from the ItemsSource property in code.

Every aspect of the ItemsControl’s appearance from the exterior of the control, the panel that surrounds it’s items and the items themselves can be customized based on a pre-defined pattern or ‘template’ that you specify. Three properties on the ItemsControl allow you to specify three different types of template to describe three different aspects of the appearance of the final list:

Property Name

Type

Default Content

Template

System.Windows.Controls.ControlTemplate

ItemsPresenter containing StackPanel

ItemsPanel

System.Windows.Controls.ItemsPanelTemplate

StackPanel containing ContentPresenter per item

ItemTemplate

System.Windows.DataTemplate

ContentPresenter containing Grid

These defaults can be visualised in the following control hierarchy:

The ‘Template’ property is inherited from Control and appropriately allows you to specify a ControlTemplate to define the appearance of everything about the ItemsControl outside it’s ItemsPresenter. The other two properties ‘ItemsPanel’ and ‘ItemTemplate’ are defined by the ItemsControl class itself and are concerned with the appearance of items inside the ItemsControl. More specifically the ‘ItemsPanel’ property controls the appearance of the panel that surrounds all the item’s ContentPresenters, the ‘ItemTemplate’ property customizes the appearance of the contents of each ContentPresenter.

Customizing the Default Templates

The following example shows how to customize the value of each of these three properties to produce a different control hierarchy. The sample application attached to this post makes use of the ItemsControl to position images not vertically in a StackPanel but at specific coordinates within a Canvas. The Xaml from the sample application is reproduced below along with the subsequent control hierarchy:

The contents of the three custom templates are defined in the Resources section of the UserControl and bound to the relevant properties of the instance of ItemsControl. Firstly the ControlTemplate specified in the Template property has been used to surround the ItemsPresenter with a blank Border. Secondly the ItemsPanelTemplate specified in the ItemsPanel property means the ItemsPresenter now has a Grid as it’s content rather than a StackPanel. Finally the DataTemplate specified in the ItemTemplate property has completely replaced the default Grid with a Canvas containing an Image and a StackPanel. The contents of the DataTemplate are interspersed with Binding expressions to extract data from each item in the ItemsControl, in this case instances of the simple Country class shown below:

Note even though the Images are in an ItemsControl they are positioned at the coordinates shown by setting the value of the Left and Top attached properties of their parent Canvas to the value of the X and Y coordinates from the custom Location property via the Bindings specified in the DataTemplate assigned to the ItemsControl’s ItemTemplate property.

The images used in the sample application are from this article on WikiMedia and the control hierarchy images were produced from screenshots of the excellent Silverlight Spy 2 which I highly recommend.

This post presents a solution to a question on Stack Overflow which I found interesting, this is a question I’ve seen crop up a few times now in one form or another:

"I have an ObservableCollection feeding a DataGrid that is updating nicely. The point: I want to filter (collapse) the rows without removing them from the collection. Is there a way to do this?"

You can remove rows from a DataGrid by removing items from the ObservableCollection<T> that the grid’s ItemsSource property is bound to, but the question asks is there a way to avoid this. The way I see it a solution to this question will firstly offer a way to filter the rows displayed in a DataGrid without affecting the Count of the original ObservableCollection<T> and secondly provide a way to easily discern which rows are currently filtered and which are displayed after the filter has been applied. The intent is also to provide a solution general enough to be reused with any type T in an ObservableCollection<T>.

The solution structure of the simple demo solution available for download above looks as follows:

The Xaml contains two DataGrids, a NumericUpDown control from the Silverlight Toolkit and a standard Button control. When the ‘Apply Filter’ button is clicked the people (or rows) shown in the FilteredPeople grid are filtered, the row count in the AllPeople grid remains unchanged. The filter excludes people whose Age property does not equal the current value of the NumericUpDown control.

The Page class has an ObservableCollection<Person> called ‘people’ containing 6 instances of the Person class. The Person class is a simple class that implements the INotifyPropertyChanged interface and has properties called FirstName, Age and IsVisible.

When an instance of the Page UserControl is loaded the ItemsSource property of both DataGrids is bound to the people collection resulting in the screenshot shown earlier.

When the ‘Apply Filter’ button is clicked we store the current value of the NumericUpDown control in the selectedAge variable and set the ItemsSource of the FilteredPeople grid to the result of calling the ApplyMutateFilter<T> extension method:

This method takes one predicate and two actions. A ‘predicate’ in this case just means a function that takes a parameter of type TSource and returns true or false. Similarly an ‘action’ is just a function that takes a parameter of type TSource and returns void.

In the call to ApplyMutateFilter<T> in the event handler for the button’s Click event above, the predicate function is designed to return the result of the comparison between a Person object’s Age property and the value of selectedAge. The two action functions are designed to set the value of the IsVisible property on a Person object to either true or false.

The ApplyMutateFilter<T> extension method body applies one of these actions to every item in the sequence, which action depends on the evaluation of the predicate. If the predicate returns true the positive action is executed otherwise the negative action is executed resulting in the value of the IsVisible property changing.

Finally only the elements in the sequence that matched the predicate are returned with the call to the Where<T> extension method, thus the filter is applied.

It’s important to remember that setting the IsVisible property does not make the row disappear from the DataGrid; it’s the call to Where<T> that filters the sequence. The IsVisible property is merely a convenient way of later finding which elements have been affected by the current filter in code, for example if you wanted to know what rows are currently being shown in the DataGrid after a filter has been applied.

Here is a screen shot after clicking the ‘Apply Filter’ button with a selected age of 21:

The FilteredPeople DataGrid now only displays people aged 21. The grid is now bound to the filtered sequence returned from the call to ApplyMutateFilter<T> with a predicate comparing each Person object’s Age property to the selectedAge of 21.

The screenshot shows the rows have been filtered in the first DataGrid without affecting the Count of the original ObservableCollection<T> which the second DataGrid’s is still bound to, thus satisfying the first task we set out to achieve.

Finally it’s clear to see the second requirement has been fulfilled from the state of the IsVisible properties. The value of this property makes it easy to discern which rows in the original ObservableCollection<T> are currently filtered and which are displayed after the filter has been applied.

Altering the predicate is all that’s required to apply a filter to a different property/column or a combination of several properties/columns.

Introduction

This post attempts to highlight some of the intricacies involved in connecting a WPF Client to the existing Silverlight 2 Polling Duplex demo previously published on this blog. To recap, the demo consists of a WCF service designed to push Stock data to previously connected Silverlight 2 clients over Http. In a similar scenario to a chat application, the Silverlight 2 clients can also send ‘Note’ messages back to the server and have them propagated to other connected clients.

The aim of this post is to make the demo capable of also supporting connections from WPF clients. Success is defined by enabling WPF clients to connect to the same WCF service, receive the same Stock updates at the same time as the Silverlight 2 clients and having Notes synchronized across all connected clients regardless of their underlying technology. Below is a link to a screenshot of the final version of this demo running, shown is the Console Application hosting the WCF service with two Silverlight clients and one WPF client connected:

PollingDuplexHttpBinding and WPF clients

Up until this point the demo application has solely supported pushing data to Silverlight 2 clients, defining a PollingDuplexHttpBinding endpoint on the server side and creating a channel factory as part of the Silverlight 2 client as shown below:

However, attempting to use PollingDuplexHttpBinding for this purpose in a WPF application (as in the code above) currently results in a NotSupportedException exception being raised with a full explanation and even some architectural advice:

PollingDuplexHttpBinding cannot currently be used in non-Silverlight clients without running into this exception. In order to extend the demo to support pushing Stock data to a WPF client through Http the guidance from the above exception is to consider WSDualHttpBinding. This binding predates Silverlight and is the closest alternative for achieving equivalent results to PollingDuplexHttpBinding in a non-Silverlight client application. A look at the BindingElement objects each binding encapsulates reveals WSDualHttpBinding is actually a much more mature binding than PollingDuplexHttpBinding:

WSDualHttpBinding

PollingDuplexHttpBinding

TransactionFlowBindingElement

PollingDuplexBindingElement

ReliableSessionBindingElement

TextMessageEncodingBindingElement

SymmetricSecurityBindingElement

HttpTransportBindingElement

CompositeDuplexBindingElement

OneWayBindingElement

TextMessageEncodingBindingElement

HttpTransportBindingElement

The WSDualHttpBinding Endpoint

The outcome of acting on the aforementioned advice in the demo application is the addition of a new endpoint to the WCF service exposed from the StockServer Console Application. This could easily be specified entirely in a configuration file (see this post for how to configure the Silverlight policy and duplex endpoints) but in the download is achieved in code as shown below:

Although the WSDualHttpBinding endpoint is registered using a different URI, the endpoint is simply just another entry point into the same WCF service called by the existing Silverlight 2 clients using PollingDuplexHttpBinding. Before you can push data from a WCF duplex service to a client, the client must initiate the session by calling the service. The Register method serves this purpose in the demo application and the only change to the code in the WCF service itself (although there are no method signature changes) is in this method as shown below:

The change is minor but essential: extracting the MessageVersion from the initial message sent by the client and passing it to the constructor of the StockClient object along with a reference to the channel back to that client. The variety of MessageVersion used by each of the bindings in the demo application is as follows:

Binding

MessageVersion

WSDualHttpBinding

MessageVersion.Soap12WSAddressing10

PollingDuplexHttpBinding

MessageVersion.Soap11

Messages sent between WSDualHttpBinding endpoints use the SOAP 1.2 protocol; between PollingDuplexHttpBinding endpoints the SOAP 1.1 protocol is employed. There is a clue in the name of MessageVersion. Soap12WSAddressing10 that WSDualHttpBinding also requires addressing headers to support reliable messaging sessions via ReliableSessionBindingElement. In the case of these two bindings, attempting to use a mismatch of MessageVersion and binding, for example MessageVersion.Soap11 for messages sent to a WSDualHttpBinding endpoint, results in an InvalidOperationException as shown below:

Storing the message version along with the channel reference in an instance of the StockClient class (see code download) ensures the reply messages are pushed back to the client in the format the relevant binding expects. The rest of the WCF service remains the same: a new instance of StockService is created per session regardless of the endpoint used. Each session registers it’s interest in the DeltaReceived event of the singleton StockGenerator class. This event is raised approx every 250 milliseconds and each session’s handler (OnDeltaReceived) sends the same generated delta to its respective client via the stored channel reference using the appropriate message protocol.

The WPF Client Application

In a good advertisement for how nearly all of what you write in Silverlight 2 can be used without modification in WPF, the code in the WPF client application is extremely similar to that contained in the Silverlight 2 client project. The markup in StockWindow.xaml and code in StockWindow.xaml.cs is virtually identical to Page.xaml and Page.xaml.cs in the Silverlight 2 project.

One difference between the WPF and Silverlight client code is the WPF DataGrid which is from the October 2008 Release of the WPF Toolkit available from codeplex. Another difference already highlighted is that PollingDuplexHttpBinding cannot be used in a non-Silverlight client application. In its place we use WSDualHttpBinding on the WPF client side also and due to this binding’s maturity the code in StockTicker.cs is less verbose as shown below:

using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Windows.Threading;
using Common;
namespace WpfStockClient
{
public sealed class StockTicker : IStockClient
{
// Reference to layout instance that created the StockTicker
private readonly Dispatcher owner = null;
// Serializes instances of the Stock type before they are sent on the wire
private readonly DataContractSerializer stockSerializer = new DataContractSerializer(typeof(Stock));
// Proxy for communication to WCF service
private IStockService proxy;
// List of stocks designed to be bound to a UI control
private readonly StockList stockList = new StockList();
public StockList StockList
{
get { return stockList; }
}
public StockTicker(Dispatcher owner)
{
if (owner == null)
{
throw new ArgumentNullException("owner");
}
this.owner = owner;
}
public void SubscribeDeltas()
{
EndpointAddress endPoint = new EndpointAddress("http://localhost:10201/WpfStockService");
proxy = new DuplexChannelFactory<IStockService>(this,
new WSDualHttpBinding(WSDualHttpSecurityMode.None),
endPoint).CreateChannel();
proxy.Register(Message.CreateMessage(MessageVersion.Soap12WSAddressing10, "StockClient/IStockService/Register"));
}
public void Receive(Message message)
{
Stock stock = message.GetBody<Stock>();
// Queue a call to UpdateStockList on the Dispatcher of the thread that created this instance
Action<Stock> action = UpdateStockList;
owner.BeginInvoke(action, stock);
}
public void Sync(Stock stock)
{
// Create a message with the appropriate SOAPAction and asynchronously send it via the proxy with the serialized Stock as the body of the envelope
Message message = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, "StockClient/IStockService/Sync", stock, stockSerializer);
proxy.Sync(message);
}
private void UpdateStockList(Stock delta)
{
// NOTE : CheckAccess is there but intellisense doesn't see it because of the [EditorBrowsable(EditorBrowsableState.Never)] attribute
if (!owner.CheckAccess())
{
throw new InvalidOperationException("The calling thread cannot access this method because a different thread owns it.");
}
// Check if this Stock is already in the collection
Stock existing = stockList.FirstOrDefault(s => s.Symbol == delta.Symbol);
if (existing == default(Stock))
{
// This delta is a new Stock
stockList.Add(new StockHighlight(delta));
}
else
{
// This delta is an existing Stock
existing.Ask = delta.Ask;
existing.Bid = delta.Bid;
if (!String.IsNullOrEmpty(delta.Notes))
{
existing.Notes = delta.Notes;
}
}
}
}
}

There are many similarities between the above code and the Silverlight 2 version; the changes are all centred on the body of the SubscribeDeltas method. This is where the client instance of the WSDualHttpBinding class is instantiated and used to establish a composite duplex channel (two one-way channels) with the new endpoint at the address exposed in the WCF service. The first parameter passed to the DuplexChannelFactory<IStockService> constructor specifies ‘this’ as the instance of the IStockService interface to receive the pushed messages from the WCF service in the Receive method. After the channel is created the initial message is sent using the correct MessageVersion as described earlier.

Linked Common Files

Those class files that are identical across both client projects are added to the Common Solution folder and are referenced using links from the respective projects where they are used:

The highlighted classes are written in one place and as such are assured of being the same structure throughout the solution (and where relevant on both sides of the wire as a consequence). As the files are linked, the code they contain will be compiled into IL that targets the respective version of the CLR implied by the type of project the classes are linked from. For the WPF project the linked classes will be compiled into an assembly that targets the desktop CLR, for the Silverlight project the linked classes will be compiled into an assembly that targets the more compact CoreCLR. Linking common files in this manner is one solution to the problem normally solved by using a class library when a common CLR is targeted by all projects.

Animating the Stock Price changes

Illustrating changes to Stock price instances displayed in the DataGrid by creating the illusion that the DataGrid cell background is changing color takes less code in WPF than in Silverlight. The code for this animation for both WPF and Silverlight 2 is contained in the StockHighlight class. The entire contents of the StockHighlight.cs file is shown below, the code between the #if and #endif directives is compiled only if the SILVERLIGHT symbol is defined as it is in the Build tab of project properties on all default Silverlight 2 projects:

The targets of the animation are the two public SolidColorBrush properties, AskHighlight and BidHighlight. The Color dependency property of these brushes is animated using color key frame animation from green for a positive change or red for a negative change. The animation for both WPF and Silverlight begins with a call to the BeginHighlight method when the corresponding Ask or Bid price property changes. The SILVERLIGHT debug symbol makes it clear to see the extra Storyboard objects and extra initialization required in the InitializeAnimation method to achieve the desired effect in Silverlight 2. You can see the references to these AskHighlight and BidHighlight properties in the WPF XAML below, also notice the xmlns:data for the DataGrid from the WPF Toolkit:

Surprisingly this is not supported by default in the release version of Silverlight 2 due to the absence of the required configuration-related classes needed to expose the Polling Duplex binding and binding element to the WCF configuration system. However, thanks to the great extensibility model of WCF it is possible to enable this scenario and bridge the gap by registering a custom binding extension.

The aim is to render the StockServiceHost class (defined in code above) redundant and instead replace it’s functionality entirely in a configuration file, in this case App.config. As you can see in the InitializeRuntime method the StockServiceHost class actually registers two endpoints: in addition to the PollingDuplexHttpBinding endpoint there is the WebHttpBinding endpoint to account for the Silverlight 2 cross-domain policy requirements. It would defeat the aim to succeed in defining one of these endpoints in the configuration file without the other, so the measure of success is to be able to define both in App.config. How this aim can be achieved is shown below:

Notice under the <bindingExtensions> element that the pollingDuplexHttpBinding item relies on the following two configuration-related classes (demonstrated in use as part of the sample application or available separately for download above) in the PollingDuplexConfig.cs file:

To configure Polling Duplex in Silverlight 2 solely via the .config file the PollingDuplexHttpBindingCollectionElement class including the relevant namespace and assembly, need to be referenced in the type attribute of the pollingDuplexHttpBinding item under the <bindingExtensions> element as shown in the configuration markup above.

As this is a standard way to create and register a custom binding extension, once the configuration classes and markup are in place as shown and the project successfully builds, you can edit the binding in the same way as the built-in WCF bindings by opening the produced .config file (StockServer.exe.config in this case) in SvcConfigEditor.exe while the service is running:

The samples and links to demos on this blog have been updated to be compatible with the release of Silverlight 2. These projects are typically the result of my curiosity or a desire to unearth benefit from a newly available feature in Silverlight 2. If they are useful for others so much the better, if not there are certainly lots of other Silverlight 2 samples available elsewhere.

It has always been my intention to make these demos available without any restriction with the release of Silverlight 2, feel free to make use of them however it may benefit you:

The upgrade process was largely painless for me, the main change that sticks in my mind is accounting for the change in case of the GridLinesVisibility property on the DataGrid. The pie chart live-demos have been updated but are hosted on Silverlight Streaming which does not yet fully support the released version of Silverlight 2, I expect this to change in the near future.

PollTimeout setting on the server side (PollingDuplexHttpBinding and PollingDuplexBindingElement) has been renamed to ServerPollTimeout

PollTimeout setting on the PollingDuplexBindingElement (client side) has been renamed to ClientPollTimeout.

PollTimeout setting on the PollingDuplexHttpBinding (client side) has been cut. In most scenarios, it should not be necessary to change this. If a change is necessary, it can be achieved through the ClientPollTimeout on the PollingDuplexBindingElement.

Client-side support has been cut from the non-Silverlight (server-side) polling duplex assembly (i.e. BuildChannelFactory will throw a NotSupportedException). That is, in RTM, the client side for polling duplex must be Silverlight (and the server side must be the regular .NET Framework, but this restriction was already in place in Beta2).

Default timeouts have been changed for the Duplex channel. For most common scenarios, the new out-of-the-box defaults should be appropriate and there is no need to change them.

An error (404) on a polling request will cause the duplex channel to fault.

Various invalid messages used to be ignored by the Duplex stack but will now be rejected.

If any HTTP error (404,500,…) is encountered during a SOAP call, a CommunicationException is now thrown instead of a ProtocolException.

Earlier this month I put together a series of posts representing somewhat of a deep-dive into the WCF Polling Duplex support in Silverlight 2 Beta 2. The series is in three parts covering Architecture, The Server and The Client and will still be largely relevant. The source code for a Beta 2 sample application discussed across parts two and three is available for download.

I will be on vacation over the next week-and-a-bit and won’t be able to respond to emails/queries immediately but I do fully intend to update the polling duplex sample application to account for these breaking changes when I return. Applications built with Beta 2 will not run on final runtime builds so I will also update the other samples available on this blog including the pie/doughnut chart and Sockets samples in the near future.

This post takes a brief look at the options for capturing localhost HTTP traffic in the superb Fiddler2 tool but in particular demonstrates how this can be achieved using the less-renowned ipv4.fiddler keyword in a Silverlight 2 polling duplex debugging session.

HTTP traffic sent to or originating from http://localhost or http://127.0.0.1 by Internet Explorer and the .NET Framework is not captured in Fiddler2 by default because the requests and responses do not pass through the WinInet proxy that it registers. A few simple workarounds do exist to commonly facilitate the capture of this traffic (without customizing Fiddler’s rules) however:

Using 127.0.0.1 with a dot suffix

Using the Machine Name

Using ipv4.fiddler

The rest of this post shows the results of using each of these methods in an attempt to achieve a complete trace of all HTTP traffic being sent and received between my sample Silverlight 2 Beta 2 polling duplex client and server application, the results were quite interesting. The sample application consists of three projects:

The Silverlight 2 Beta 2 client polling duplex application

The Web Application hosting the Silverlight client

The WCF polling duplex service hosted in a Console Application

The server manually handles the Silverlight client access policy requirements and messages are sent in both directions by both parties. Capturing all the traffic between the client and server in Fiddler2 requires the base http://localhost url to be manipulated at design time according to the appropriate workaround in each of the three projects. Let’s take a look at the process using each workaround in turn and the ensuing results:

1. Using 127.0.0.1 with a dot suffix

I first read about this technique here and it does work in a number of more common scenarios, let’s see how it fares in this scenario:

A. Silverlight Client

Firstly the manipulation of the default http://localhost url used to connect to the server duplex service from the Silverlight 2 client project:

// From this
EndpointAddress endPoint = new EndpointAddress("http://localhost:10201/StockService");
// To this - Note the period after localhost
EndpointAddress endPoint = new EndpointAddress(http://127.0.0.1.:10201/StockService);

B. Hosting Web Application

Secondly the same change to the Start URL for the web application that hosts the Silverlight 2 client:

C. WCF Service Console Application

Lastly a change to the base address of the WCF polling duplex service in the server’s configuration file:

D. Results in Fiddler

The screenshot above shows the results of our efforts using this workaround. The session gets as far as the GET request for the built-in clientaccesspolicy.xml file. Due to our manually added suffix a HTTP 400 Bad Request – Invalid Hostname response is returned. This HTTP response is eventually translated into the following exception in the Silverlight client:

2. Using the Machine Name

This is a technique listed in the relevant help section on the Fiddler2 website, lets see what results this workaround yields:

A. Silverlight Client

Again we start with the manipulation of the default http://localhost url used to connect to the server duplex service from the Silverlight 2 client project:

// From this
EndpointAddress endPoint = new EndpointAddress("http://localhost:10201/StockService");
// To this (i.e. Environment.MachineName)
EndpointAddress endPoint = new EndpointAddress(http://vgnar21s:10201/StockService);

B. Hosting Web Application

Again, the same change to the Start URL for the web application that hosts the Silverlight 2 client:

C. WCF Service Console Application

Lastly a change to the base address of the WCF polling duplex service in the server’s configuration file:

D. Results in Fiddler

The screenshot above shows the results of our efforts using this workaround. The session does not get past the request for the aspx page that hosts the Silverlight application and a HTTP 502 Connection Failed response is returned. This HTTP response message eventually appears as the following error in Internet Explorer:

3. Use ipv4.fiddler keyword

At this stage the two previous workarounds have both proven unsuccessful, let’s try the same process this time with another technique listed in the relevant help section on the Fiddler2 website – use of the ipv4.fiddler keyword. The ipv4.fiddler keyword requires Fiddler v2.1.8 or later to be running, I should also mention the ipv6.fiddler keyword (not covered in this post) for IPV6 debugging.

A. Silverlight Client

Firstly the manipulation of the default http://localhost url used to connect to the server duplex service in the Silverlight 2 client project:

// From this
EndpointAddress endPoint = new EndpointAddress("http://localhost:10201/StockService");
// To this (Fiddler keyword)
EndpointAddress endPoint = new EndpointAddress(http://ipv4.fiddler:10201/StockService);

B. Hosting Web Application

Secondly the same change to the Start URL for the web application that hosts the Silverlight 2 client:

C. WCF Service Console Application

Lastly a change to the base address of the WCF polling duplex service in the server’s configuration file:

D. Results in Fiddler

Success – this workaround accomplishes exactly what we set out to achieve, the screenshot above shows the capture of all HTTP traffic going between the client and server. It shows everything from the initial request for the hosting aspx page, downloading the .xap file, the request and custom self-hosted response for the clientaccesspolicy.xml file and finally the actual polling duplex activity on the wire. Note the content of the User-defined column, this is as a result of turning on ‘Show Time-to-Last-Byte’ and ‘Show Response Timestamp’ under the Rules > Performance menu in Fiddler2.

For a deep-dive into exactly what these polling duplex requests and responses contain, please see the ‘Anatomy of a Bi-Directional Message Exchange’ heading in Part 1 – Architecture of my series of posts on polling duplex in Silverlight 2.

Introduction

This is the third and final post in my current series on the support for duplex communication with a WCF service added to Silverlight 2 Beta 2. I should point out that this technology in its current form has been deemed by Microsoft as not yet fit for production applications and is therefore currently for evaluation only. In this post I introduce the client part of a sample application available for download (the download includes the server discussed in the previous post also) that uses the bi-directional communication discussed in part one. The sample application as a whole represents a simple client and server application that illustrates polling duplex communication in both directions. The client displays stock prices in a grid and animates updates received from the server. The user of the client application can also enter notes against a stock and have those notes propagate to all other connected clients via the server using polling duplex communication in the other direction. Here is a screenshot of the sample application running with the server and two connected clients, the same stock price updates are being displayed by both clients and the notes entered in Internet Explorer have been pushed to another instance of the client running in Firefox:

The Client

The layout of the Visual Studio 2008 solution is as follows:

There are three projects in the PollingDuplexDemo solution, the first is the Silverlight Application project StockClient that references the client-side version of System.ServiceModel.PollingDuplex.dll. The .xap file produced by building this project is referenced by the Silverlight ASP.NET server control in the StockClientTestPage.aspx file as part of the hosting StockClientHost Web Application project. The StockServer project is a Console Application project that self-hosts the polling duplex WCF service. As you can see from the image there are multiple startup projects, the first to start is the StockServer project along with the StockClientHost project shortly after.

Page.xaml and Page.xaml.cs

The markup in Page.xaml (see code download) defines the StocksGrid Silverlight DataGrid along with the rest of the UI elements, the code in Page.xaml.cs adds some initialisation code to the default constructor and handlers for some UI events. When the Silverlight Application loads and assigns an instance of the Page class defined across these files to the RootVisual property of the Application class, the constructor shown below is executed:

The StockTicker Class

It’s apparent from the code above that the instance of the StockTicker class is central to everything happening in the client application and indeed it’s the code in this class that implements the client-side PollingDuplex support:

namespace StockClient
{
public sealed class StockTicker
{
// Reference to layout instance that created the StockTicker
private readonly Dispatcher owner = null;
// Object used to let ThreadPool know to stop waiting and proceed
private readonly AutoResetEvent waitObject = new AutoResetEvent(false);
// Asynchronously begins an open operation on an ICommunicationObject with code to call EndOpen when it completes
private static readonly Action<ICommunicationObject> Open =
ico => ico.BeginOpen(iar => ico.EndOpen(iar), ico);
// Asynchronously begins a send operation on an IDuplexSessionChannel with code to call EndSend when it completes
private static readonly Action<IDuplexSessionChannel, Message> Send =
(idc, msg) => idc.BeginSend(msg, iar => idc.EndSend(iar), idc);
// Asynchronously begins a receive operation on an IDuplexSessionChannel with code to call an Action<Message> when it completes
private static readonly Action<IDuplexSessionChannel, Action<Message>> Receive =
(idc, act) => idc.BeginReceive(iar => act(idc.EndReceive(iar)), idc);
// Serializes instances of the Stock type before they are sent on the wire
private readonly DataContractSerializer stockSerializer = new DataContractSerializer(typeof(Stock));
// Channel for communication to WCF service
private IDuplexSessionChannel channel;
// List of stocks designed to be bound to a UI control
private readonly StockList stockList = new StockList();
public StockList StockList
{
get { return stockList; }
}
public StockTicker(Dispatcher owner)
{
if (owner == null)
{
throw new ArgumentNullException("owner");
}
this.owner = owner;
}
public void SubscribeDeltas()
{
// Create a channel factory capable of producing a channel of type IDuplexSessionChannel
IChannelFactory<IDuplexSessionChannel> factory =
new PollingDuplexHttpBinding().BuildChannelFactory<IDuplexSessionChannel>();
Open(factory);
// Address of the polling duplex server and creation of the channel to that endpoint
EndpointAddress endPoint = new EndpointAddress("http://localhost:10201/StockService");
channel = factory.CreateChannel(endPoint);
Open(channel);
// Create a message with the appropriate SOAPAction and asynchronously send it on the channel
Message message =
Message.CreateMessage(MessageVersion.Soap11, "Silverlight/IStockService/Register");
Send(channel, message);
// Use the thread pool to start only one asynchronous request to Receive messages from the server
// Only start another asynchronous request when a signal is received that the first thread pool thread has received something
ThreadPool.RegisterWaitForSingleObject(waitObject,
delegate { Receive(channel, CompleteReceive); },
null,
Timeout.Infinite,
false);
waitObject.Set();
}
public void Sync(Stock stock)
{
// Create a message with the appropriate SOAPAction and asynchronously send it on the channel with the serialized Stock as the body of the envelope
Message message =
Message.CreateMessage(MessageVersion.Soap11, "Silverlight/IStockService/Sync", stock, stockSerializer);
Send(channel, message);
}
private void CompleteReceive(Message message)
{
// Deserialize the body of the SOAP message into a Stock object
Stock stock = message.GetBody<Stock>();
// Queue a call to UpdateStockList on the Dispatcher of the thread that created this instance
Action<Stock> action = UpdateStockList;
owner.BeginInvoke(action, stock);
// Signal the thread pool to start another single asynchronous request to Receive messages from the server
waitObject.Set();
}
private void UpdateStockList(Stock delta)
{
// NOTE : CheckAccess is there but intellisense doesn't see it because of the [EditorBrowsable(EditorBrowsableState.Never)] attribute
if (!owner.CheckAccess())
{
throw new InvalidOperationException("The calling thread cannot access this method because a different thread owns it.");
}
// Check if this Stock is already in the collection
Stock existing = stockList.FirstOrDefault(s => s.Symbol == delta.Symbol);
if (existing == default(Stock))
{
// This delta is a new Stock
stockList.Add(new StockHighlight(delta));
}
else
{
// This delta is an existing Stock
existing.Ask = delta.Ask;
existing.Bid = delta.Bid;
if (!String.IsNullOrEmpty(delta.Notes))
{
existing.Notes = delta.Notes;
}
}
}
}
}

In order to create an instance of the StockTicker class a reference to an instance of the System.Threading.Dispatcher class is required. In the initialisation of the StockTicker instance in the Page class constructor the Dispatcher property inherited all the way from System.Windows.DependencyObject is used. This provides StockTicker with a queue to add tasks to for execution on the UI thread. It is essential to update collections that may be bound to UI controls (such as the StockList property) from the UI thread to avoid an invalid cross-thread access (UnauthorizedAccessException) exception; this restriction also applies to the animation of individual stock prices using Storyboards managed by the StockHighlight class. The stored Dispatcher reference is later used to queue calls to UpdateStockList to be executed on the UI thread from the CompleteReceive method and to check the correct thread has called UpdateStockList before updating the collection or the Stock properties that cause animation Storyboards to begin.

After the instance of StockTicker has been created in the constructor of the Page class the SubscribeDeltas method is called. This method performs all of the client setup necessary to begin a polling duplex session with the WCF service. The method body begins by creating an instance of the client-side version of PollingDuplexHttpBinding (see part one) and extracting an instance of a channel factory of type IDuplexSessionChannel from that binding. The factory is then opened asynchronously and the channel is created, the client then initiates communication by asynchronously opening the channel to the WCF service specified in EndpointAddress. The method progresses to create a SOAP 1.1 Message instance specifying the One Way Register method discussed in the previous post in the SOAPAction; the instance of this message is then sent asynchronously along the channel to the server. Finally the method uses an AutoResetEvent to signal a ThreadPool thread to begin one asynchronous request to receive messages pushed from the server. When a message is eventually received the CompleteReceive callback method is executed to queue a call back to the UI thread with the received Stock object before signaling the wait handle; this signal in turn prompts the thread pool to release another single asynchronous request to receive another message.

The Sync method creates a new SOAP 1.1 Message with a different SOAPAction and with the Stock parameter (containing the Notes entered by the user) as the body of the envelope serialised via the DataContractSerializer. The method then uses the same channel opened in SubscribeDeltas to asynchronously send the message to the server for propagation to all connected clients. The code for the WCF service methods being called here is discussed in part two, the make up of these asynchronous calls and their responses on the wire is discussed under the ‘Anatomy Of A Message Exchange’ heading In part one.

The UpdateStockList method checks the current thread as previously described and then searches the StockList collection for the current Stock object comparing Symbol properties. A new instance of the StockHighlight class is created to add to StockList if the received stock does not exist in the collection. As StockList is an ObservableCollection this insert will notify the DataGrid that it’s ItemsSource has changed and to update itself to honour the addition in the UI. If the stock already exists then only the relevant price and notes properties on the existing StockHighlight instance are updated, triggering the relevant animations. These updates in turn cause the PropertyChanged event from INotifyPropertyChanged implemented by the Stock class (see code download) to fire again causing the DataGrid to update the UI.

The StockHighlight Class

This class extends the basic Stock class overriding the Ask and Bid properties and exposing two public properties of type Brush:

Each cell in the Bid and Ask columns of the DataGrid declared in Page.xaml contains a StackPanel whose Background property is bound to the respective Brush property. This way each cell is able to play it’s own unique animation specific to the Stock displayed. These Brush properties need to be part of each individual Stock object rather than global resources so the whole column does not change colour when one stock changes price. The InitializeAnimation method associates animations of type ColorAnimationUsingKeyFrames with each of these Brushes for both positive and negative changes. The appropriate Storyboard to play is chosen in the Bid and Ask property setters based on the new value.

The most salient parts of the client code are now covered, download the solution, press F5 to start the server and one client automatically, you can then browse to StockClientTestPage.aspx using the same address from multiple clients in separate browsers once the service is running.

In the future it looks likely that the client side Silverlight 2 Polling Duplex API will be simplified to enable a less verbose method of connecting to and receiving pushed messages from a WCF service. This post talks more about the possibility of a DuplexReceiver<T> class for simple client scenarios in the future; it’s always prudent to know what such a class will be doing for you behind the scenes.

Further Reading

A few links on polling duplex support in Silverlight 2 Beta 2 you might find useful:

Introduction

This is the second in a series of posts on the support for duplex communication with a WCF service added to Silverlight 2 Beta 2. I should point out that this technology in its current form has been deemed by Microsoft as not yet fit for production applications and is therefore currently for evaluation only. In this post I introduce the server part of a sample application available for download (the download includes the client also) that uses the bi-directional communication discussed in part one. The sample application as a whole represents a simple client and server application that illustrates polling duplex communication in both directions. The client displays stock prices in a grid and animates updates received from the server. The user of the client application can also enter notes against a stock and have those notes propagate to all other connected clients via the server using polling duplex communication in the other direction. Here is a screenshot of the sample application running with the server and two connected clients, the same stock price updates are being displayed by both clients and the notes entered in Internet Explorer have been pushed to another instance of the client running in Firefox:

The Server

The layout of the Visual Studio 2008 solution is as follows:

There are three projects in the PollingDuplexDemo solution, the first is the Silverlight Application project StockClient. The .xap file produced by building this project is referenced by the Silverlight ASP.NET server control in the StockClientTestPage.aspx file as part of the hosting StockClientHost Web Application project. The StockServer project is a Console Application that self-hosts the polling duplex WCF service and represents the server. You can see from the Visual Studio 2008 solution that there are multiple startup projects, the first to start is the StockServer project along with the StockClientHost project shortly after.

Preliminaries

In order to self-host a WCF service in a Console Application the server needs to register itself as the HTTP handler for a certain URI; this is also termed as registering a portion of the local HTTP namespace. In order to do this the application needs to run as a local Administrator or the current non-administrative user needs to have been assigned to the ACL for a particular URI, you can read more about this here. If the server Console Application does not have the appropriate permissions a System.ServiceModel.AddressAccessDeniedException exception is raised with the message "HTTP could not register URL http://+:10201/StockService/. Your process does not have access rights to this namespace."

If you are using Visual Studio 2008 as an Administrator or using Windows XP you won’t run into this problem and I have accounted for it on Windows Vista by creating a UAC manifest (see the app.manifest file) that requires the server to be run as an Administrator. As a result of this configuration you may encounter the following message the first time you press F5:

Selecting ‘Restart under different credentials’ re-starts Visual Studio as a local Administrator resulting in the server being able to register and listen at the HTTP address it has been configured with.

The WCF Service Interfaces

The StockServer project references the server-side System.ServiceModel.PollingDuplex.dll assembly and defines one WCF service called StockService. Here are the ServiceContract interfaces defined in the StockServer namespace:

Three interfaces are defined in all: IStockService, IStockClient and IPolicyProvider. IStockService defines the two methods Register and Sync specified as One Way operations, hence the method signatures cannot specify anything other than void as the return type. Setting IsOneWay to true has the effect that clients will not block waiting for a return message after having called the service as they would with a default request response operation. A client configured for polling duplex will rather poll asynchronously and pick up messages pushed to them from the service as discussed in part one. You may also recall these two operations from the value of SOAPAction in the traced HTTP requests in the previous article. The IStockClient type is specified via the CallbackContract property as the type that will callback to the client from instances of services that implement IStockService.

IStockClient defines the Receive operation as an asynchronous operation by setting AsyncPattern to true and defining Begin and End methods matching the required pattern. This method is specified as asynchronous to cater for a problem I was encountering when one client aborted or faulted while many other clients were connected. In this scenario a synchronous method call back to the faulted client resulted in the server thread blocking until the PollTimeout period elapsed for that client with the exception shown in the previous post. This is fine for the faulted client but the blocking stopped the other connected clients receiving their updates. The asynchronous version handles the reply using the thread pool so that in the same situation the faulted client will block and timeout on a thread pool thread while the other connected clients still receive their updates as normal.

The IPolicyProvider interface sets up a creative solution (thanks to this post) to the problem of serving up policy requirements to Silverlight 2 clients when using a self-hosted WCF service. The only change I had to make was to include http-request-headers="*" in the response to ensure compatibility with the Silverlight 2 Beta 2 policy requirements instead of Beta 1. The declaration above specifies that the ProvidePolicy method should be called in the event of a GET request whose URI includes the relative string specified in UriTemplate. I have not included support for Flash compatible crossdomain.xml files but this could be easily added using the same method. WebGet was introduced as part of WCF 3.5, its interesting (though not relevant to Silverlight self-hosted policy requirements) to note that the UriTemplate can also contain curly bracket placeholders that resolve to method parameters for use with REST requests, similar functionality is provided in ASP.NET MVCrouting.

The WCF Service Class

The following shows how the previously discussed interfaces are used throughout the declaration of the StockService class. The StockService class implements only two of the interfaces: IStockService and IPolicyProvider, the usage of the IStockClient interface is shown in the Register method:

The StockService does not specify a ServiceBehavior attribute as part of it’s declaration so the defaults apply, the most relevant being InstanceContext.PerSession and ConcurrenyMode.Single. As such, a new instance of the StockService WCF service is created for every client that connects although it is also possible to configure the service as a singleton using the code download with very few changes if that is something you are interested in.

The Register method is called by clients when they first connect to the service, the Message parameter although required by the underlying framework is not used in the method body. The body firstly creates a new instance of the StockClient class (see code download) passing two parameters to the constructor: a reference to the channel back to the client along with the SOAPAction to use when sending a return message. Note this SOAPAction string does not mention the IStockClient interface but rather the IStockService interface and contains the name of the synchronous version of the Receive method which is not defined anywhere in user code. The rest of the method and indeed the class is fairly self-explanatory and centres around subscribing the current instance of StockService to receive deltas from the singleton StockGenerator class (see code download) when a client connects and unsubscribing when a fault occurs attempting to communicate with that client.

The Sync method does make use of the Message parameter sent from the client to extract the Stock (see code download) object and the notes entered against it. This is again passed on to the singleton StockGenerator class to update it’s state and raise a notification to all other subscribed clients. The implementation of the ProvidePolicy method simply returns a stream containing the contents of the ClientAccessPolicy.xml file (which is copied to the output directory of the executable) to satisfy the policy requirements required to allow Silverlight clients to connect to this self-hosted service cross-domain.

Hosting the WCF Service

The hosting information for the StockService service is split between the App.config file…

This is where the server instance of PollingDuplexHttpBinding is instantiated and published as a service endpoint on the base address retrieved from the configuration file. Two other endpoints are defined for this service, one is the Metadata Exchange endpoint which you can navigate to in a browser when the server is running; the other is the endpoint for the policy response bound to the root of the base address. The constructors included simply defer to the base constructors of ServiceHost, the first one allows this class to be optionally used as a host of a singleton polling duplex service instance. When the Console Application starts it simply creates an instance of the StockServiceHost class and opens the communication channel to accept clients:

The same stock prices are sent to all client channels at approximately the same time in each StockService instance’s handler for the singleton StockGenerator class’s DeltaReceived event via the StockClient instance. The full code for the definitions of the StockGenerator and StockClient classes is available in the code download. Currently new deltas are generated every 250.0 milliseconds using the ThreadPool, obviously the more this interval is reduced the more noticeable the performance degradation; especially below 100.0 milliseconds on my machine with two clients in separate browsers or tabs things eventually get out of sync. Comparing this solution to a similar solution I’ve published using Sockets which can keep clients in sync at 1.0 millisecond intervals it’s clear to see there is work to be done on performance and it’s good to see the Silverlight Webservices Team acknowledge this themselves.