Monday, 31 May 2010

UriMapper not working

When using the navigation framework in Silverlight I found the URI mapping was not working. Interestingly, the Tim Heuer example on the Microsoft Silverlight web site didn’t work either.

A UriMapper something like the following was declared in App.xaml:

    <navcore:UriMapper x:Key="UriMapper">
        <navcore:UriMapping Uri="Uri1" MappedUri="/Views/Page1.xaml" />
        <navcore:UriMapping Uri="Uri2" MappedUri="/Views/Page2.xaml" />

Hyperlinks were declared in the MainPage.xaml looking something like this:

<StackPanel x:Name="LeftNav" Width="150" Orientation="Vertical"/>
    <HyperlinkButton Tag="Uri1" Content="Page 1" Click="HyperlinkButton_Click" />
    <HyperlinkButton Tag="Uri2" Content="Page 2" Click="HyperlinkButton_Click" />

The navigation frame was declared in the MainPage.xaml something like this:

<navigation:Frame x:Name="Frame" />

Code in the HyperlinkButton_Click event handler looked something like this:

private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
    var link = sender as HyperlinkButton;
    var tag = link.Tag as string;
    Frame.Navigate(new Uri(tag, UriKind.Relative));

Clicking on a link produced no effect in the Silverlight application (i.e. no navigation). In IE8 a JavaScript error was reported on the page. Details of the error were along the lines of:

Message: Unhandled Error in Silverlight Application Navigation is only supported to relative URIs that are fragments, or begin with '/', or which contain ';component/'.
Parameter name: uri at System.Windows.Navigation.NavigationService.NavigateCore(Uri uri, NavigationMode mode, Boolean suppressJournalAdd)
    at System.Windows.Navigation.NavigationService.Navigate(Uri source)
    at System.Windows.Controls.Frame.Navigate(Uri source)
    at System.Windows.Controls.Frame.Frame_Loaded(Object sender, RoutedEventArgs e)
    at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)

... snip ...

The problem turned out to be that the UriMapper declared in App.xaml was not known to the navigation frame. The solution was to map the UriMapper on the frame in the MainPage.xaml:

<navigation:Frame x:Name="Frame" UriMapper="{StaticResource UriMapper}" />

Tuesday, 18 May 2010

Sunday, 16 May 2010

Career path to date

This post is intended to help me keep track of my career path to date.

There follow some timelines depicting the companies I have worked for and the positions I have held, the main programming languages and tools I have used in a commercial setting, and the principal commercial engagements I have had.

Employment timeline

Above – Companies and Positions, Languages and Tools

Employment timeline - Engagements

Above – Principal Engagements

Wednesday, 12 May 2010

Silverlight and the ObservableCollection<T> class

The ObservableCollection<T> class can be used to represent dynamic data collections. It provides notifications when items are added or removed from the collection as well as when the entire collection is refreshed.

This class can be used in data binding scenarios so that insertions or deletions in the collection can update the UI automatically.

The dynamic behaviour is achieved through the implementation of the INotifyEventChanged interface that exposes a CollectionChanged event.

Note there are potential issues with thread safety:

“Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.” -

Your domain classes need to implement the INotifyPropertyChanged interface. This interface requires the implementing class raise a PropertyChanged event whenever the state of the object changes. Note this applies to WFP as well as Silverlight.

See also:

INotifyPropertyChanged -

Monday, 10 May 2010

GO command and semicolons in SQL Server

The GO Command

The batch terminator. The GO command is not part of the Transact-SQL language but is used by the SQLCMD, OSQL and ISQL utilities that can also be used within Query Analyzer and the Query Editor window.

A batch is a set of T-SQL statements that are submitted for execution as a group. A script is a file containing set of T-SQL statements. One script can contain many batches.

Note: if you declare variables in a script and issue a GO command the variables will ne destroyed.

The GO command is sometimes required (e.g. when defining a stored procedure – the CREATE PROCEDURE statement must be the first statement in the query batch so any preceding statements must be followed by GO).





The Semicolon

The semicolon character is a statement terminator.

It is a part of the ANSI SQL-92 standard but was never used within Transact-SQL.

There are two situations in which you must use the semicolon:

  • Where you use a Common Table Expression (CTE), and the CTE is not the first statement in the batch.
  • Where you issue a Service Broker statement and the Service Broker statement is not the first statement in the batch.

See also:

Common Table Expressions (CTEs)

Common Table Expressions (CTEs) were introduced in SQL Server 2005. They are view/derived tale-like construct.

“A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query.” - (MSDN SQL Server 2008 documentation)

CTEs offers the advantage of improved readability and ease in maintenance of complex queries.

The basic structure of a CTE is:

WITH expression_name [ ( column_name [,...n] ) ]
( CTE_query_definition )

You can then query the CTE as you would a table/view.


USE AdventureWorks;
-- Define the CTE
WITH Sales_CTE (SalesPersonID, NumberOfOrders, MaxDate)
    SELECT SalesPersonID, COUNT(*), MAX(OrderDate)
    FROM Sales.SalesOrderHeader
    GROUP BY SalesPersonID

-- Query using the CTE
SELECT E.EmployeeID, OS.NumberOfOrders, OS.MaxDate,
       E.ManagerID, OM.NumberOfOrders, OM.MaxDate
FROM HumanResources.Employee AS E
    JOIN Sales_CTE AS OS -- Join against CTE as if it were a table
    ON E.EmployeeID = OS.SalesPersonID
    LEFT OUTER JOIN Sales_CTE AS OM -- CTE can be referenced more than once
    ON E.ManagerID = OM.SalesPersonID
ORDER BY E.EmployeeID;

You can define multiple CTEs after the WITH keyword by separating each CTE with a comma.

A CTE can reference itself and previously defined CTEs in the same WITH clause. Forward referencing is not allowed.

Lots more here:

Thursday, 6 May 2010

Schema binding in SQL Server

I recently had to make changes to a database table – simple changes, just adding 2 NULL columns. However, I was confronted with an error because the table in question was bound to a view created with SCHEMABIND.

Schema binding allows dependencies to be created between database object so that changes cannot be made accidentally which might otherwise break a dependant object. In the case of a view it would be possible to add, alter or drop table columns the view depends on. Schema binding prevents this.

To modify a database object that participates in schema binding you must drop or alter the bound object to remove the schema binding before making the necessary changes.

Views are not schema bound by default. To ensure views participate in schema binding use the "WITH SCHEMABINDING" clause when creating them.

USE [DatabaseNameHere]

SELECT … snip …
FROM [dbo].[TableNameHere] 

Schema binding is commonly used with objects like views and User Defined Functions (UDF).

Note that for UDFs schema binding can result in performance gains due to the way SQL Server prepares query plans etc.

Tuesday, 4 May 2010

Features new to ASP.Net 4

As usual this is not intended to be  a comprehensive list but an aide-mémoire


Extensible output caching

Output caching now enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism (e.g. disk, cloud storage, and distributed cache engines).

By default all HTTP responses, rendered pages, and controls use the in-memory output cache (the AspNetInternalProvider). You can change the default output-cache provider by specifying a different provider name for defaultProvider attribute (web.config).

In addition, you can select different output-cache providers for individual control and for individual requests and programmatically specify which provider to use.

<%@ OutputCache Duration="60" VaryByParam="None" providerName="DiskCache" %>

Preloading web applications

A new application preload manager (autostart feature) is available when ASP.NET 4 runs on IIS 7.5 on Windows Server 2008 R2.

The autostart feature lets you perform expensive application initialisation prior to processing the first HTTP request (e.g. initialise an application and then signal a load-balancer that the application was initialised and ready to accept HTTP traffic).

This feature requires modification of the IIS 7.5 applicationHost.config. You can implement System.Web.Hosting.IProcessHostPreloadClient within your application which will be invoked by the autostart feature.

“When an IIS 7.5 server is cold-started or when an individual application pool is recycled, IIS 7.5 uses the information in the applicationHost.config file to determine which Web applications have to be automatically started. For each application that is marked for preload, IIS7.5 sends a request to ASP.NET 4 to start the application in a state during which the application temporarily does not accept HTTP requests. When it is in this state, ASP.NET instantiates the type defined by the serviceAutoStartProvider attribute (as shown in the previous example) and calls into its public entry point.”

Permanent page redirection (HTTP 301)

ASP.NET 4 adds a RedirectPermanent helper method that makes it easy to issue HTTP 301 (Moved Permanently) responses:


Session state compression

ASP.NET 4 introduces a new compression option for out-of-process session state providers (including using SQL Server).

“You can set this option using the new compressionEnabled attribute of the sessionState element in the configuration file. When the compressionEnabled configuration option is set to true, ASP.NET compresses (and decompresses) serialized session state by using the .NET Framework GZipStream class.”

ASP.Net web forms

New features include:

  • The ability to set meta tags.
    • Two properties have been added to the Page class: MetaKeywords and MetaDescription.
  • More control over view state.
    • A new property has been added to the Control class: ViewStateMode. You can use this property to disable view state for all controls on a page except those for which you explicitly enable view state.
  • Support for recently introduced browsers and devices.
    • Browser capabilities are represented by the HttpBrowserCapabilities object which is stored in the HttpRequest.Browser property.
    • Browser definition files have been updated to contain information about recently introduced browsers and devices.
  • Easier ways to work with browser capabilities.
    • You can now write a custom provider to determine browser capabilities (e.g. accessing a database or web service).
  • Support for using ASP.NET routing with Web Forms.
    • Pinched from MVC and now in ASP.Net.
  • More control over generated IDs.
    • Huzzah!
    • ClientID now has 4 ClientIDModes:
      • AutoID – the old way.
      • Static – set it yourself but risk having multiple controls with the same ID on a page.
      • Predictable – a bit of a half-way house; use for data binding.
      • Inherit – the mode is inherited from the page or parent control.
  • The ability to persist selected rows in data controls.
  • More control over rendered HTML in the FormView and ListView controls.
  • Filtering support for data source controls.
    • QueryExtender control can be added to EntityDataSource or LinqDataSource controls in order to filter the data returned by these controls.
  • Enhanced support for Web standards and accessibility. There’s a stack of these including:
    • CSS for controls that can be disabled (disabled="disabled" no longer added to display-only controls such as labels; class="aspNetDisabled" used instead).
    • CSS for validation controls - ASP.NET 4 does not automatically show error messages in red.
    • CSS for the hidden fields Div element
    • CSS for the Table, Image, and ImageButton Controls
    • CSS for the UpdatePanel and UpdateProgress Controls
    • Eliminating Unnecessary Outer Table
    • Layout Templates for Wizard Controls
    • New HTML Formatting Options for the CheckBoxList and RadioButtonList Controls
    • Header and Footer Elements for the Table Control
    • CSS and ARIA Support for the Menu Control
    • Valid XHTML for the HtmlForm Control
    • Maintaining Backward Compatibility in Control Rendering
  • ASP.Net MVC – actually this is in the box with Visual Studio 2010, not the .Net framework or ASP.Net.
  • Dynamic Data
    • Enabling Dynamic Data for Individual Data-Bound Controls in Existing Web Applications
    • New Field Templates for URLs and E-mail Addresses
    • Creating Links with the DynamicHyperLink Control
    • Support for Inheritance in the Data Model
    • Support for Many-to-Many Relationships (Entity Framework Only)
    • New Attributes to Control Display and Support Enumerations
    • Enhanced Support for Filters
  • ASP.Net Chart Control
    • Data series, chart areas, axes, legends, labels, titles, and more.
    • Data binding.
    • Data manipulation, such as copying, splitting, merging, alignment, grouping, sorting, searching, and filtering.
    • Statistical formulas and financial formulas.
    • Advanced chart appearance, such as 3-D, anti-aliasing, lighting, and perspective.
    • Events and customizations.
    • Interactivity and Microsoft Ajax.
    • Support for the Ajax Content Delivery Network (CDN), which provides an optimized way for you to add Microsoft Ajax Library and jQuery scripts to your Web applications

Also of interest

Web application deployment with Visual Studio 2010 -

Enhancements to ASP.NET Multi-Targeting

Monday, 3 May 2010

Features new to C# 4

Here’s a smattering of what’s new in C# 4.

Dynamic support

There is a new keyword – dynamic. This keyword allows you to create dynamic objects and let their types (and therefore operations) be determined at run time. This feature facilitates interoperability with other languages including dynamic languages and COM Interop.

The dynamic keyword is easy to use:

dynamic myObject = new SomeObject();
myObject.MyProperty = "SomeValue";

Note that with dynamic objects the compiler won’t catch typos in member names etc. Everything is evaluated at runtime.

“The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).” -

There is also a new ExpandoObject class (part of the DLR):

“The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").” -

You can just add new members on the fly to ExpandoObject instances:

dynamic sampleObject = new ExpandoObject();
sampleObject.test = “Dynamic Property”;

Optional/default parameters

This language feature enables you to specify a parameter value to be used if the parameter is omitted from a call.

Example method declaration:

public static void SomeMethod(int optional = 0) { }

Example method calls:

SomeMethod(); // 0 is used in the method.

This might be useful with MVC action methods where previously nullable parameters were used for optional URL parameters.

Named arguments

This language feature could be useful in conjunction with optional parameters.

“Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list. Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.” - (my italics)

Example method declaration:

public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10)

Example method calls:

anExample.ExampleMethod(3); // one required parameter, 2 optional

anExample.ExampleMethod(3, optionalint: 4); anExample.ExampleMethod(3, optionalstr: “test”); anExample.ExampleMethod(3, optionalint: 4, optionalstr: “test”);

Covariance and contravariance

Covariance enables you to use a more derived type than that specified by the generic parameter, whereas contravariance enables you to use a less derived type.


See also for the in keyword and for the out keyword.

Explained nicely in this web cast:

Saturday, 1 May 2010

Virtual PC shortcuts

I am always forgetting these so…
Shortcut Description
Host key+L Restores Virtual PC Console from a minimized state. Moves Virtual PC Console to the foreground.
Host key+I Installs Virtual Machine Additions.
Host key+ENTER Toggles a virtual machine between full-screen mode and window mode.
Host key+DELETE Sends CTRL+ALT+DELETE to the virtual machine operating system.
Host key+P Pauses or resumes the virtual machine, depending upon its current state.
Host key+R Resets the virtual machine.
Host key+F4 Closes the virtual machine.
Host key+C Copies the selected items.
Host key+V Pastes a copied item.
Host key+A Selects all.
Host key+E Opens the virtual machine settings.
Host key+DOWN ARROW Minimizes the virtual machine.
Host key+LEFT ARROW Switches to the previous virtual machine when running multiple virtual machines, unless you are using full-screen mode.
Host key+RIGHT ARROW Switches to the next virtual machine when running multiple virtual machines, unless you are using full-screen mode.
The “host key” is usually the right-Alt key.
You can press the host key to return control of the mouse to the host computer.