FallbackValue, TargetNullValue & StringFormat in Silverlight 4

Silverlight 4 introduces some further databinding functionality including:


If there is a problem with performing the binding, for example an incorrect path to a property value, the fallback value will be used in it's place. This allows some meaningful display, rather that the default behaviour of showing nothing.


Allows a value to be used if the bound property is null.


Allows formatting of the bound value using standard formatting expressions.


The following is the output of the XAML below:



<Grid x:Name="LayoutRoot" Background="WhiteSmoke" >
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>

    <TextBlock TextWrapping="Wrap">Invalid binding path with FallbackValue set</TextBlock>
    <TextBlock Text="{Binding Path=badPath, FallbackValue='this is a fallback value'}" Grid.Column="1"></TextBlock>

    <TextBlock TextWrapping="Wrap" Grid.Row="1">Invalid binding path withOUT FallbackValue set</TextBlock>
    <TextBlock Text="{Binding Path=badPath}" Grid.Row="1" Grid.Column="1"></TextBlock>

    <TextBlock TextWrapping="Wrap" Grid.Row="2">Bound property = null with TargetNullValue set</TextBlock>
    <TextBlock Text="{Binding Path=AnIntProperty, TargetNullValue='The int is null'}" Grid.Column="1" Grid.Row="2"></TextBlock>

    <TextBlock TextWrapping="Wrap" Grid.Row="3">Bound property = null withOUT TargetNullValue set</TextBlock>
    <TextBlock Text="{Binding Path=AnIntProperty}" Grid.Column="1" Grid.Row="3"></TextBlock>

    <TextBlock TextWrapping="Wrap" Grid.Row="4">Bound property with StringFormat</TextBlock>
    <TextBlock Text="{Binding Path=AnotherIntProperty, StringFormat='Age is {0} years old.'}" Grid.Column="1" Grid.Row="4"></TextBlock>

    <TextBlock TextWrapping="Wrap" Grid.Row="5">Bound property withOUT StringFormat</TextBlock>
    <TextBlock Text="{Binding Path=AnotherIntProperty}" Grid.Column="1" Grid.Row="5"></TextBlock>


The DataContext is set to an instance of the following class:

public class TestData : DependencyObject
    public int? AnIntProperty
        get { return (int?)GetValue(AnIntPropertyProperty); }
        set { SetValue(AnIntPropertyProperty, value); }

    // Using a DependencyProperty as the backing store for AnIntProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AnIntPropertyProperty =
        DependencyProperty.Register("AnIntProperty", typeof(int?), typeof(TestData),
            new PropertyMetadata(0));

    public int AnotherIntProperty
        get { return (int)GetValue(AnotherIntPropertyProperty); }
        set { SetValue(AnotherIntPropertyProperty, value); }

    // Using a DependencyProperty as the backing store for AnotherIntProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AnotherIntPropertyProperty =
        DependencyProperty.Register("AnotherIntProperty", typeof(int), typeof(TestData), new PropertyMetadata(0));

    public TestData()
        AnIntProperty = null;
        AnotherIntProperty = 44;



Printing Support in Silverlight 4

Basic printing can be accomplished through the PrintDocument class. For example, to print the entire contents of the LayoutRoot grid:

private void btnSimplePrint_Click(object sender, RoutedEventArgs e)
    string docName = "Test SL4 Print";

    PrintDocument doc = new PrintDocument();

    doc.PrintPage += (s, args) =>
        // print the entire contents of our page (i.e. the
        // outer grid called LayoutRoot)
        args.PageVisual = LayoutRoot;

    doc.Print(docName); // automatically shows a print dialog box

Various properties are avaible on the PrintPageEventArgs that are passed to the PrintPage event handle ('args' in the above example); args.HasMorePages allows you to control multi-page printing and args.PrintableArea allows you to get the printable page area you have available to you (which will depend on the settings chosen in the print dialog box that is shown automatically for you.

It is up to the developer to handle more complex scenarios such as overflowing contents, knowing if there are more pages required, etc. In an enterprise situation other PDF-scentric options may be a better choice, especially if there are complex report layouts required, etc. For example, using iText.NET, FOP, or an enterprise solution such as Thunderhead, xPression, etc. 


C# 4.0 Optional Parameters

C# 4.0 introduces the concepts of Optional Parameters and the related Named Parameters language features. Essentially by giving parameters a default value, callers can omit values for those parameters. The example code below produces the following output:

 name: Peter age: 44 height: 200

The code that produces this output:

class Program
    static void Main(string[] args)
        // Supply all parameters explicity (passing false)
        Console.WriteLine(CreateString("Peter", 44, 200, false, false));

        // Supply all parameters explicity (passing true)
        Console.WriteLine(CreateString("Peter", 44, 200, true, true));

        // Supply only minimum required parameters,
        // the defaults (true) for useUpperCase & appendUnitText will be used
        Console.WriteLine(CreateString("Peter", 44, 200));

        // Supply the first optional parameter only
        Console.WriteLine(CreateString("Peter", 44, 200, true));

        // If we want to use the default for the first optional parameter (useUpperCase),
        // but we want to supply a value for the second optional parameter we
        // can use Named Parameters using the appendUnitText:false syntax
        Console.WriteLine(CreateString("Peter", 44, 200, appendUnitText:false));

        Console.Read(); // wait for enter key to be pressed

    static string CreateString(string name,
                                int age, int height,
                                bool useUpperCase = true,
                                bool appendUnitText = true)
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("name: {0} ", name);

        sb.AppendFormat("age: {0} ", age);
        if (appendUnitText)
            sb.Append("years ");

        sb.AppendFormat("height: {0} ", height);
        if (appendUnitText)
            sb.Append("cm ");

        if (useUpperCase)
            return sb.ToString().ToUpper();
            return sb.ToString();               


Testing Events Using Rhino Mocks

There are possible more 'elegant' methods for the below but these are fairly well understandable by someone new to Rhino Mocks or mocking in general.

Testing Event Subscription

Sometimes we want to ensure that a given event has been subscribed to. The following example is essentially testing that when a new ViewModel is instantiated (the constructor accepts an IWorkPackageCoordinator as a dependency), that the events declared on the IWorkPackageCoordinator instance have been subscribed to (by the ViewModel instance). In other words: does the ViewModel subscribe to the IWorkPackageCoordinatorevents.

To test this we create a ViewModel and pass it a mock object that has been created for us by Rhino Mocks.


            MockRepository mocks = new MockRepository();
            IWorkPackageCoordinator mockWPC = (IWorkPackageCoordinator)mocks.StrictMock(typeof(IWorkPackageCoordinator));

            // Tell Rhino Mocks that we expect the following events to be subscriped to
            //  - we don't care about the actual delegate that is attached hence the
            // LastCall.IgnoreArguments();
            mockWPC.Downloading += null;

            mockWPC.Loading += null;   

            mockWPC.Processing += null;

            mockWPC.Saving += null;


            new ViewModel(mockWPC);


Testing Event Raising\Handling

Another test that is useful is that the object we are testing performs some action when another object raises an event that it is subscribed to.

In the example below we want to test that when an IWorkPackageCoordinator raises it's Downloading event that the ViewModel in turn raises it's PropertyChanged event. We use a boolean eventRaised, and (using lambda syntax) create an anonymous event handler for the PropertyChanged event which sets eventRaised to true if the event is fired. We then tell out Rhino Mock object to raise the Downloading event (in this example with non specific event arguments 'EventArgs.Empty')

            var mockWPC = MockRepository.GenerateMock<IWorkPackageCoordinator>();
            var SUT = new ViewModel(mockWPC);

            bool eventRaised = false;

            SUT.PropertyChanged += (s, e) => { eventRaised = true; };

            // tell mock to raise event
            mockWPC.Raise(x => x.Downloading += null, this, EventArgs.Empty);




Scholar Open Source Project

Scholar is now up on Codeplex. Scholar is a new open source project that will provide a starting point for developers to create distributed data processing such as the SETI@home project. It will use Azure to enable scalability and allow independent developers to get started without needed there own data centres. It's hoped that eventually it might be used to enable large medical and scientific data to be processed.



Developing a Windows 7 Phone App That Connects To Azure (a quick overview)


Download and install VS 2010 RC (phone tools below don't currently work with RTM ver of VS 2010):


Download and install vs 2010 express for windows phone ctp:




Open VS 2010 RC

New --> Project

Double Click Enable Windows Azure Tools and follow instructions to install Azure tools ( once install starts you will  have to quit VS2010)



Reopen VS2010

Create new proj Cloud --> Windows Azure Cloud Service

Add WCF Service Web Role

R click Service1 Refactor --> Rename to HelloWorldService

R Click definition for Iservice1 Refactor --> Rename to IHelloWorldService

Change interface and service class to:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WCFServiceWebRole1
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    public interface IHelloWorldService

        string SayHello(string name);     


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WCFServiceWebRole1
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class HelloWorldService : IHelloWorldService

        public string SayHello(string name)
            return String.Format("Hello {0}.", name);


Add a Windows Phone Application project to the solution.

Create a user interface that looks similar to this (notice how the UI elements are pre-styled to the Win 7 phone look and feel codename 'Metro':

Here's where it gets a bit messy. VS2010 RC phone app project doesn't have an Add Service Reference, so: Save All, then r click Service1.svc --> Preview In Browser, then copy the URL - leave IE open

Open VS 2010 Express, open the solution (there might be some errors, but click ok to them), when the solution opens, add service reference to the Windows Mobile application and paste the URL into the add service box and click ok. Save all and close VS 2010 Express.

Go back to VS 2010 RC and click reload solution if you get prompted.

Now we can double click our button to go to the code behind and type:

        private void button1_Click(object sender, RoutedEventArgs e)
            ServiceReference1.HelloWorldServiceClient proxy = new ServiceReference1.HelloWorldServiceClient();

            // declare callback as statement lambda
            proxy.SayHelloCompleted += (s2, e2) =>
                txtGreeting.Text = e2.Result;

            // call 'Azure' service


Now hit f5 and wait for the Windows Phone Emulator to start (it may take a little time...) then if u click on the button a keyboard will pop up:

Type you name then click the Say Hello button, you should then see the "Hello ...." result displayed that was returned from the Azure service:

It's pretty amazing that a sole developer can now create a worldwide Win 7 phone app which connects to scalable set of services in Azure all from within VS2010.


Global.asax Application_Error "File does not exist" Exception

This can sometime also manifest as a "Session state is not available in this context" exception. If you get either of these in your Application_Error event where you are using Response.Redirect and you have breakpoints set, simply remove the breakpoints and test again.


Failed to encrypt the section [name] using provider RsaProtectedConfigurationProvider. Error message from the provider: Object already exists.

If you're running aspnet_regiis to encrypt a section in your web.config, e.g.

 aspnet_regiis -pef mytestsection .

(assuming your current directory contains the web.config and the section is called 'mytestsection')

And you get a message ...   Object already exists  trying running the Visual Studio command prompt as an administrator.


Modify And Save an EF EntityDataSource Bound Entity From Code Behind

If you're using databound controls (e.g. FormView) and binding them to an EntityDataSource you might want to be able to modify (and save) the underlying entity from code. For example, if you have a Question entity bound to a FormView via an EntityDataSource you might want a button to allow the use to vote up or down the question (like StackOverflow for example). To be able to do this without extra trips to the database, the first thing we need to do is get hold of the EF ObjectContext that the EntityDataSource is using.

        // Context that we can use for code-behind operations
        ObjectContext questionObjectContext = null;

        protected void QuestionEntityDataSource_ContextCreated(object sender, EntityDataSourceContextCreatedEventArgs e)
            questionObjectContext = e.Context;

When the QuestionEntityDataSource creates it's context, we take a reference to it in our private field questionObjectContext.

Now in the button click we can up-vote the question:


        protected void btnVoteUp_Click(object sender, EventArgs e)
            // force a databind to ensure we have a DataItem in the FormView        

            // Get the actual entity represented by the FormView
            Question questionToUpdate = FormView1.DataItem.WrappedEntity<Question>();

            // Vote-up
            // using our 'copy' of the EntityDataSource ObjectContext, save the changes
            // Force rebind of FormView to ensure newest data displayed

This method feels like a bit of a hack, but ideally you would provide a client-side AJAX version, only if JavaScript is disabled on the client do we use this server-side up-vote.


Introduction To jTemplates - A jQuery and JavaScript Template Engine

jTemplates is a great lightweight template engine for jQuery and JavaScript. It allows you to process data (e.g. JSON data returned from an AJAX call) and feed it ito a template definition rather than manually building your html elements.

jTemplates supports foreach, for, if..elseif..else constructs in additional to parameters, nested templates etc.

The example below defines a template to display a list of orders and for each order the list of items that belong to that order. It shows how nested foreach can be used. The project documentation goes into more detail.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="js/jquery-jtemplates0.7.8.js" type="text/javascript"></script>
    <title>jTemplates Demo</title>
    <script type="text/javascript" language="javascript">
        // define some sample data orders
        var sampleOrder1 = {
            orderID: 'OR0001',
            orderItems: [
                { product: 'Apple', quantity: 23 },
                { product: 'Kiwi', quantity: 13 },
                { product: 'Orange', quantity: 2 },
                { product: 'Mango', quantity: 99 }
        var sampleOrder2 = {
            orderID: 'OR0002',

            orderItems: [
                { product: 'Pear', quantity: 2 },
                { product: 'Mango', quantity: 400 }

        // define a list of (2) sample orders
        var sampleOrdersList = {
            orders : [sampleOrder1, sampleOrder2]       

        // When the DOM is ready apply the jTemplate
        $(document).ready(function() {
            // Tell jTemplates we want the div with the ID of renderedContentWillGoHere
            // to be filled with the templated

            // Combine the data in sampleOrdersList with the templateand render
    <script type="text/html" id="ordersListTemplateDefinition">
        <!-- iterate over all the orders that were passed in as data
             and as each order is processed we give it an alias of currentOrder -->
        {#foreach $T as currentOrder}
            <!-- Output the orderID for the currentOrder we are iterating -->
            <h1> Order ID: {$T.currentOrder.orderID} </h1>
            <!-- Now we have a nested loop where we output the orderItems for the currentOrder -->
            <h4>Order Items</h4>           
                {#foreach $T.currentOrder.orderItems as currentOrderItem}
                    <li>{$T.currentOrderItem.product} {$T.currentOrderItem.quantity}</li>

    <div id="renderedContentWillGoHere"></div>