Tips

Caliburn.Micro and Ninject

I'm developing an application where a great deal of the functionality will be provided through plug in assemblies dropped into the main installation folder. This application is using Ninject as the dependency injection framework, and Caliburn.Micro for its support of the MVVM architecture.

Fortunately, making these two frameworks cooperate is pretty easy - all you have to do is to create a custom Caliburn.Micro bootstrapper to tie them together. Here's mine, with some explanation about how it works interspersed.

It's a (PowerShell) Trap

Here’s a PowerShell trap that needs better publicity - if you have both x64 and x86 versions of PowerShell installed (say, as you would on Windows Server 2008 R2), their security policies are independent.

CallerInfo in C# 5

Checking out Jouni Heikniemi's excellent map of What's new in .NET 4.5 I spotted this comment:

Methods can access call site info as parameter (CallerInfo)

NUnit to the Rescue

I've been spending much of my time working on a multi-tier system that makes use of special purpose data transfer objects for communication between the service tier and various clients.

These dedicated data transfer objects need to be properly marked up with [DataContract] and [DataMember] attributes, else the object is incomplete when transferred over the wire.

Unfortunately, any errors in the markup weren't apparent at compile time. Instead, they were being discovered either at runtime, when a service call failed outright, or while writing client code, when an expected property was missing from a proxy generated by svcutil.

Enter NUnit to save the day with a cunning unit test.

When Live Mesh fails

TL;DR: If Live Mesh stops working, check the system clock on each machine is correct.

I've been using Windows Live Mesh for quite some time, replicating a library of digital photos across three different machines(*). This gives my wife and I considerable flexibility, in that it doesn't matter where photos are downloaded, we both have ready access.

Custom Chrome

If you're working on an application that uses custom window chrome - whether you're using Windows.Forms or WPF - then make sure you check out the Marlett font, already installed on your system.

Configuration of Log4Net through code

While writing a windows service, I created a console version for debugging use. I wanted this console to display all the logging, in real time, so I could see things were working. A bit of a search revealed that ColoredConsoleAppender was the desired class, so I added code to set things up.

Warning MSB3247: Found conflicts between different versions of the same dependent assembly

Here's a Visual Studio tip that falls into the category of "obvious once you know it" ...

When you get this error:

Found conflicts between different versions of the same dependent assembly.

To find out further information about which assembly has been found, and which projects are affected, look in the Output window under "Build". You'll find a dense paragraph of information that tells you everything you need to know.

Fixing a Xaml parse exception

Working on a side project, I started getting a very odd persistent error. Placing a user control onto a window using the Visual Studio designer gave an error dialog "Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception." Hand coding the Xaml for the user control gave the same error:

Bindable Run for FlowDocuments

Looking for a way to databind to a paragraph of text in WPF, I first learnt about FlowDocuments, then about Run and how it doesn't support databinding. Further consultation with Professor Google led me to Scott Hanselman's The Weekly Source Code #40 where I found links telling me how to make binding work.

Equal Button Sizes in WPF

On StackOverflow, I read an interesting WPF question:

Suppose you have a window with multiple buttons such as Ok/Cancel or Yes/No/Cancel.
All the buttons need to be the same width.

Several good answers had been given, but none mentioned the simplest technique - leveraging SharedSizeGroup to constrain Grid columns to the same width.

In my answer to the question, I wrote:

Invalid Build Configuration: Debug|BNB

While upgrading the NAntGraph solution to .Net 4, my build script started failing with an inexplicable error:

C:\Projects\NAntGraph\NAntGraph2.sln.metaproj : error MSB4126:
The specified solution configuration "Debug|BNB" is invalid.
Please specify a valid solution configuration using the Configuration and Platform properties
(e.g. MSBuild.exe Solution.sln /p:Configuration=Debug /p:Platform="Any CPU")
or leave those properties blank to use the default solution configuration.

Performance Monitoring for Visual Studio

The smart guys over at Developer Division have been working on making Visual Studio perform better. A key need they have in achieving this is for real data - actual metrics on where Visual Studio is running slow for real users.

Dependency Load Failures

Ever encountered this error?

System.IO.FileLoadException: Could not load file or assembly {0} or one of its dependencies.

I find this particularly frustrating because it doesn't tell you which dependency couldn't be loaded. Aarrgghh!!

Richard Dingwall to the rescue - go download libcheck, a small but very useful tool he's just released on github.

Tab ordering in Visual Studio

So it all started when I saw an interesting tweet:

"Broken by design". Visual Studio - yet another product I won't waste my time reporting any more bugs for: http://bit.ly/ewsHSO @CADbloke (RT by RoyOsherove)

I clicked through and read the details on the Microsoft Connect website - and it related to a Visual Studio function that I've used literally hundreds of times: editing the tab order of controls in WinForms.

So I tweeted back, somewhat provocatively:

It's not a bug when the user doesn't bother to learn how the tool works. Could it be better? Sure. Is it broken. No.

But, explaining why it's not broken is too much of a challenge for 140 characters - so I figured I'd blog it.

IIS Web Application installation trap

Here's a trap if you're setting up an existing web application on a new IIS 7.5 installation ...

If your web application fails on startup with this error:

The requested page cannot be accessed because the related configuration data for the page is invalid.
There is a duplicate 'system.web.extensions/scripting/scriptResourceHandler' section defined

The likely cause is that you are trying to run a web application written to run on the .NET 2.0 runtime on the .NET 4.0 runtime.

There are three solutions.

On the length of names ...

Fresh from the Twitters, courtesy of Uncle Bob:

The length of a variable name should be proportional to its scope.

The length of a function or class name is the inverse.

Wise advice.

Importing Excel data with SSIS

If you're crazy enough(*) to be using SSIS to import information from an Excel workbook into a database, you may get an error like this:

Error: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.
The AcquireConnection method call to the connection manager "Time Series XLSX" failed with error code 0xC00F9304.

DataBinding Lag in WPF

WPF Binding is extremely powerful and useful - but it does have a few traps for the unwary. Propagation lag is one of them.

While most WPF controls default their bindings with UpdateSourceTrigger set to PropertyChanged, updating the bound property every time the control is changed, TextControl defaults to LostFocus. Updates to the bound property are therefore performed only when the control loses focus.

WCF, Callbacks and IIS

Creating an IIS hosted web service that uses callbacks and publishes metadata.

Lets Play

If you're still working on getting your head around TDD, you could do a lot worse than following James Shore's series Let's Play, a growing series of web casts that show TDD in a real life project.

What I like most about the series is the "warts and all" approach that James takes, much more satisfying and informative than the usual sanitised "perfect run" you see in most demos.

Knowing when Builds finish

Did you know that Visual Studio can play a sound to tell you when the build completed - in fact, different noises to tell you about success and failure? I didn't - but here's how to do it.

Doing less with LINQ

While reading a recent article in MSDN magazine, I came across some code that gives me a great opportunity to show how to get more done with less effort by using LINQ.

Avoiding Stack Overflow with Params

Here's a pattern that I've seen occur a number of times - a pair of method overloads, one accepting IEnumerable<T> and the other accepting params T[].

WCF and IList<T>

Here's an interesting problem I encountered recently with a WCF based web service and the humble IList<T> interface.

I'm working on a classic 3-teir system: Client/Application/Database. The Client and Application are using Windows Communication Foundation (WCF) to interact. For convenience, we have an assembly of Data Transfer Objects (or DTOs) which is shared across both the client and the server.

While working on a recent system enhancement, I encountered an odd error - a NotSupportedException with the message "Collection was of a fixed size".

Using TypeConverters with WPF

I'm working on a little project at the moment which is dynamically building a WPF user interface based on a configuration file loaded when the application starts. This involves code to manually create all of the bits and pieces that are normally specified directly in a Xaml file.

One useful shortcut I've found is to leverage .NETs built in TypeConverter framework - the same technique used by the Xaml loader itself.

Using Windows SignOn with PowerBuilder and SQL Server

Following The Good Samaritan Principle, here's a tip for people using PowerBuilder against a SQL Server back end with single-sign-on.

Windows 7 Window Management

I'm one of the many who've been trying out the Windows 7 Release candidate - yes, I know that it's available retail now, it's on the Christmas list.

One thing that's bugged me is the apparent lack of follow through with Multi-monitor support. You see, if you drag windows around with the mouse, Windows 7 offers some useful auto-dock functionality, but only at the outer edges of the screens.

A Winforms Layout Puzzle

Here’s a strange piece of behaviour – a puzzle (with solution) for you.

Imagine that you’re working with Win.Forms, constructing a resizable layout using a TableLayoutForm as the host.

At Design time, your form looks like this (click to enlarge):

Designtime
Designtime

But, at run time it looks like this (click to enlarge):

Runtime
Runtime

The "Good Samaritan" Principle

Sometimes a quick consultation with Professor Google or Doctor Bing just doesn't bring you any satisfaction - and you end up having to work.

Richard Dingwall suggests that when this happens, you should consider blogging about the issue, sharing your experience so that others can benefit. (In many ways, this is a capsule description of all human progress!)

Testing and Static Methods

I'm working with a large codebase at the moment, trying to write unit tests to ensure that the changes I'm making aren't compromising the existing code.

For some of the code, this is easy. For other pieces, not so much.

One area that I'm finding difficult is in the area of static methods. Historically, I've been a fan of static methods for some scenarios. But, now I'm finding them a bit of a pain.

MappingLists with NHibernate

Here's a subtlety of NHibernate mapping that I ran into this morning.

When you map a one-to-many relationship as a list, you can have null values in that list when loaded.

How to Find Stuff

At this weeks Wellington .NET user group, James asked me how I find stuff - when I need to find out how to get something done, how do I find the information I need. Here's what I told him.

Exception Inspection

Watch $exception
Watch $exception

Here's a useful tip that I didn't know - you can use the pseudo-variable $exception in the Watch window to see the exception that's just been caught.

PhpMyAdmin and the White Screen of Death

After a recent hardware failure (*) I've been setting up a new LAMP sandbox, this time using Ubuntu 9.04 running in a virtualised environment.

Everything was going fine, but after importing a database backup into MySQL, PhpMyAdmin started misbehaving, giving a White Screen of Death after login. View source revealed an empty file.

WinForms DataBinding Goodness

There's a lot of "goodness" buried in WinForms databinding that doesn't get to see the light of day. Here's one example I discovered just today ...

How not to set up Tests

Some unit tests on a project were newly failing - I'd done the checkin immediately before the first failure, so it fell to me to sort out the problem.

Class Diagrams as Documentation

customer.png
customer.png

The Class Diagram tooling built into Visual Studio is worth its weight in gold as documentation.

What I didn't know, and discovered today, is that using Copy Image populates the clipboard with not only a raster version of the image, but a vector version as well. Fantastic for embedding into Word documents when writing documentation.

Strange Win.Forms behaviour

Here’s a strange piece of behaviour – a puzzle (with a solution) for you.

Imagine that you’re working with Win.Forms, constructing a resizable layout using a TableLayoutForm as the host.

Using Lambdas as Event Handlers

Of all the new features in C# 3.0, Lambda expressions have to be one of my favourites.

One non-obvious way that they can be used is as event handlers, in just the way that anonymous delegates could be.

Margin Guides in Visual Studio

To set a margin guide in Visual Studio requires a minor Registry Hack (*)

First, use RegEdit to go to the key HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor.

RegEdit Screenshot
RegEdit Screenshot

Next, create a new string value "Guides" with value "RGB(128,128,128) 99" (sans quotes). This creates a gray guideline just after the 99th column.

Change RBGB(r,g,b) to change the colour of the guide; you can create multiple guides by separating them with commas at the end.

(*) Usual warnings apply - stuff up your Registry and your machine is hosed. Take precautions.

Finding Configuration Files

Here’s a useful technique for finding the location of configuration files.

Each AppDomain has a base directory from which it loads assemblies – when you double click a WinForms or WPF application, the new process that starts up has an AppDomain whose base directory is the directory in which your exe is located.

Small Fonts

A recent question on StackOverflow.com asked Why use Monospace fonts in your IDE.

One of the answers referenced the use of Comic Sans as a font for coding. I couldn't quite believe it, so I tried it out - and found that Comic Sans is actually very readable at small font sizes, easy on the eye and very compact. Check this out:

fonts.png
fonts.png

(Click to enlarge)

WiX Techniques Updated

My whitepaper on WiX techniques has been updated to correct an error.

The previous version of the whitepaper omitted the definition of the "PreventDowngrading" custom action, necessary for proper upgrade behaviour.

The related blog posts (on versioning and upgrading) have also been updated.

Upgradable MSI installations with WiX

I had some interesting challenges when integrating WiX based MSI installer generation into my build scripts. My previous post (NAnt and WiX Versioning) details how I ended up injecting version numbers into the MSI build. In this post, I detail how to ensure that each newly generated installation file will cleanly replace the previous.

Databinding with Lists

A question came up recently on the NZ dot Net mailing list:

Any one use listbox.DataSource = myList for data binding to a List box?

I cannot refresh the data source "myList". If I use the following code to update the data source:

listbox.DataSource = null;
listbox.DataSource = newList;

The items in the listbox are object types rather than data values.

Can any one tell me how to refresh the data in the list box when binding to the control?

My reply was:

NAnt and WiX Versioning

In this post, I show how I've managed to integrate WiX into my NAnt build scripts while retaining consistency of versioning.

Outcome Based Thinking

Over on 43 Folders (great site, well worth a spelunk or two) there's a great post on getting focused.

I feel these techniques before, and find them quite useful - at least, when I remember to apply them. :-)

One key that has been really useful for me is to pay attention on how I phrase things I add to my TODO list - the template <em>I need to $FOO because I want to $BAR</em> is helpful here.

Conscious Development

I'm working on a couple of minor personal projects at the moment, and I'm using them as an opportunity to try and hone my skills at TDD/BDD style development. Even though I first heard about TDD some years ago, I haven't yet made the breakthrough where it becomes automatic. I guess I'm still at the conscious competence stage of skill acquisition.

Single Instance Applications

The .NET framework has lots and lots of built in goodies that aren't well enough known - like built in support for [ensuring only a single copy of the application runs at a time](http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinForm...).

Too often, we developers spend ages coding up support for operations that are already there!

Intersect and Except

As a part of the infrastructure introduced in .NET 3.5 to support the various flavours of LINQ, there are a whole heap of generic extension methods that are available whenever you have IEnumerable<T>.

Two that I've found useful recently areIntersect() and Except() - both of these work to filter values out of the sequence.

A couple of examples are the best way to understand them:

// Returns all multiples of three
IEnumerable<int> multiplesOfThree = ...;
// 3, 6, 9, 12, 15, 18, 21, ...
 
// Returns all multiples of four
IEnumerable<int> multiplesOfFour = ...;

Extension Methods and Null Pointers

I'm sure that most of you know that you can't call methods on a null reference, so you'll expect that this code will fire a nasty exception:

IPath p = null;
int l = p.Length();

Except, it doesn't.

Why?

Dual Monitor Visual Studio

I'm a big believer in the benefits of having dual monitors - in fact, I'm fortunate enough to have dual monitors on both the computers I use most often.

One of the challenges is to make good use of Visual Studio across both monitors. While the Visual Studio IDE is very good at maximizing the usefulness of a single monitor (by having various panes strategicly docked), it doesn't lend itself so well to a dual screen configuration.

A Settings Problem Solved

Following up on my previous post, I've found the cause of the problem.

Configuration Manager in Visual Studio Express

Update, September 2010:
See the comments below for how to make this work with Visual Studio Express 2010.

This one has been bugging me for a while, so I'm very glad to find a fix.

The defaults for Visual Studio Express have the Configuration Manager hidden, I guess on the justifiable basis that most users of VS Express would just be confused by it.

Copy Error Dialogs

Here's a quick tip I was shown by a friendly Help Desk guy this week (thanks, Ben!).

Next time you get an error dialog from some random piece of software, don't reach for a pen to write down the relevant details.

User Settings Gotcha in Visual Studio

Found an interesting trap when configuring settings for a screensaver I'm working on.

Conditional Compilation

Now here's a trick that I didn't know - you can use the [Conditional] attribute to suppress a method unless a given symbol is defined at compile time.

From the MSDN documentation:

Applying ConditionalAttribute to a method indicates ... the method should not be compiled into Microsoft intermediate language (MSIL) unless the conditional compilation symbol that is associated with ConditionalAttribute is defined.

Mostly of use when you're writing logging and other diagnostic code - indeed, major use in the framework seems to be in the Debug and Trace classes.

Renaming WPF Windows

So, I wanted to rename a window in a WPF application - a prototype I'm working on.

First, I rename the code in the .cs code-behind file. Then, I change the Class attribute on the root element of the xaml file.

 

Cool, thinks I. A quick compile, no errors, everything looks good.

But, when the application is run ... I got an error dialog saying “There is no source code available for the current location”:

wpf001.png

Eh? I thought the technology was called WPF, not WTF!