Smart Code

Extension methods for XElement

I've found myself writing code like this quite a bit lately:

var orderElement 
    = document.Element(OrderXml.OrderElementName);
if (orderElement == null)
{
    var message
        = string.Format(
            "Didn't find expected child element <{0}>",
            OrderXml.OrderElementName);
    throw new InvalidOperationException(message);
}

The intent is to find a specified child element, throwing an error if the element is not found.

Asserting Convention

I'm using PostSharp on a project, with a custom aspect that provides standard handling for authentication and authorisation.

To ensure that all our service methods are properly annotated with our custom aspect (there are only a couple of service calls that shouldn't have the attribute present) I wrote a unit test:

On Naming and Convention ...

Richard Dingwall has a good blog post talking about one specific case where a naming convention goes bad and starts hindering, instead of helping, development.

Spoken Numbers

Here's a little utility function that adds an appropriate suffix after numbers to show them as they might be said:

/// <summary>
/// Format a number as it would be said.
/// </summary>
/// <param name="aValue">Number to format.</param>
/// <returns>Formatted number with suffix.</returns>

"Evil" ToString()

Courtesy of a tweet from Scott Hanselman, here's a nifty ToString() extension method that allows you to name properties and fields directly.

It works like this:

var p
    = new Person
    {
        Name = "William Williams",
        BirthDate = new DateTime(1936, 1, 1)
    };
 
Console.WriteLine(p.ToString("{Name}, born {BirthDate:d}, Age {Age}"));

See the original on pastie.org.

Improving on POCO Associations

Building on our past discussion (see Improving on POCO Properties and Improving on POCO Collections), let us look at how we can improve the implementation of associations between our domain objects.

In a standard POCO domain model, associations are handled as simple object references, or as lists of object references:

class Customer
{
    Person PerformedBy;
    IList<Orders> PlacesOrders;
}

Dude, you're working too hard

Sometimes I look at a piece of code and find it hard not to sigh, especially when the developer has done something the hard way.

Take this piece of code, for example:

var key = EntityKeyFactory.CreateKey<ITsClassKey>(
    new object[]
    {
        aItemRequest.ItemName,
        aItemRequest.SystemName
    });

For reference, here's the declaration of the CreateKey function:

public static T CreateKey<T>(params object[] aKeyValues)

Do you see the problem?

Range Properties

A common need in domain modelling is to specify a range - of dates, of prices, or some other numeric measure. Typically, we model this with a pair of properties, as in this example:

class MarketingCampaign
{
    DateTime? EffectiveFrom;
    DateTime? EffectiveUntil;
}

Improving on POCO Collections

In my previous blog entry, Improving on POCO Properties, we looked at the benefits we can reap for our domain objects if we represent properties with dedicated helper objects instead of restricting ourselves to the usual C# syntax.

As you may have guessed by now, there are improvements that can be made in other areas as well. In this post, the focus will be on composite objects.

Improving on POCO Properties

Plain Old CLR Objects (POCOs), along with their close cousins POJOs (Plain Old JVM Objects) are often held up as the ideal for use when modelling our problem domains.

The arguments in favour of using POCOs are compelling - including independence from any particular object relational mapper (ORM), avoidance of the need to implement a specific interface or to have a certain ancestor object. In fact, the arguments are so compelling that large sectors of the development community take it as a matter of faith that there is no better way.

Still working too hard

Here's another example of someone working too hard ...

    try
    {
        // Load the XML string into an XmlTextReader
        XDocument xmlFile = XDocument.Parse(inputXmlString);
 
        string prettyXml = xmlFile.ToString(SaveOptions.None);
        editXml.Text = prettyXml;
        success = true;
    }
    catch (Exception exception)
    {
        if (exception.GetType() == typeof(XmlException))
        {
           ShowMessage("The File is not a valid format. Format should be XML", 

Linq vs Loop performance

The StackOverflow question Convince me to move to .net 3.5 (from 2.0) piqued my curiosity when against one answer the commenter wrote:

This does come at a cost tho: ox.no/posts/linq-vs-loop-a-performance-test/…

I followed the link to find out, and found a benchmark that is, in my opinion, flawed.

Why?

Scoped Values

Here's an interesting utility class, a scoped value. This allows you to have a member variable that gets changed for a time, and then automatically restored back to the original value.

Looked at another way, a Scoped is a member variable where changes are not permanent. Instead, changes are kept during a particular scope of execution, then reverted.

When is this useful?

One sample use is for the mouse cursor - with a suitably configured Scoped you can simply change the cursor to an hour glass during a process and then have it automatically restored again afterwards.

Getting the small things right

message.png

It really bugs me when an application shows me a message like the one shown here.

I'm willing to agree that, overall, it's a minor issue - but the poor use of language really bugs me, and it makes me suspicious that maybe the rest of the application has had an equal lack of attention to detail.

An Event Snippet

Original posted April 2008, updated May 2009 with a revised version of the snippet.

Following on from my recent post about code snippets for property declarations, I thought I'd share the snippet I use for event declarations.

Sometimes we work too hard

Sometimes we developers do things the hard way for no better reason that not knowing that a better way is there.

Unscary Code

I found a better approach, one that isn't as scary ...

builder.Define(
    mEntryColumn,
    aEditor,
    (column, editor) => column.AddNumericField(editor.Format)
                            .BoundTo(editor, e => e.Value)
                            .FocusBoundTo(editor, e => e.Focused));

Scary Code

wtf.png

I just wrote this code:

builder.Define(
    mEntryColumn,
    aEditor,
    (column, editor) => column.AddNumericField(editor.Format)
                            .BoundTo(editor, e => e.Value)
                            .FocusWhen<ResponseEditor, EventArgs>(
                                editor, 
                                (e, handler) => e.Focussed += handler));

FocusWhen() is designed to hook up a UI Control (just created by the call to AddNumericField()) with a domain object (aEditor) so that aEditor can make the control focused.

Easier Enums

Here's a slightly easier way to work with flag enumerations.

Linq Goodness

At tonight's meeting of the Wellington .NET User group we had two presentations – one on Linq Syntax from Owen Evans, and one on avoiding Cross Site Scripting attacks from Kirk Jackson. Both presentations were informative and interesting, and I learnt a few new things from each.

Owen’s Linq presentation reminded me of a couple of Linq goodies that I wrote recently – so I thought I’d share.

A Better Property Snippet

One of the less well known features in Visual Studio are the snippets - fragments of code ready for insertion into your code at a moments notice. In Visual Studio 2005, the prop snippet was a very useful way to declare new class properties, but in Visual Studio 2008 they crippled it. Since you can create your own snippets, I created a better version of prop that works the way I want.

Safe coding and IDisposable

I'm really fussy about writing safe code, and I'm a sucker for neat tricks as well - so this deceptively simple idea from Ayende.com is doubly attractive.

The idea in this blog entry is to make it easy to expose an API that's both semantic and safe for the caller.

So often an API requires that pairs of methods are called together - StartProcess and EndProcess or some similar situation.