Reviews and links for July 2010

Imperial Bedrooms by Bret Easton Ellis

Imperial Bedrooms by Bret Easton Ellis

4/5

Returns to the characters of Less Than Zero twenty five years later. I don't think it's a plot spoiler to say that they're not happy and well adjusted people. I found Glamorama to be pretty tedious and Lunar Park only marginally better. It was a huge relief that Imperial Bedrooms just flows. It's a welcome return to his earlier narrative style. Dread and paranoia are visceral presences from the start and then layers of fear and horror build until it can't get any worse and then somehow does. Brilliant.

 

More...

Converting Blogger ATOM export to BlogML

I'm slowly converting a number of blogs from Blogger to BlogEngine.NET. The least fun part is dealing with the Blogger export file. For this blog I used a Powershell script but had problems with comments not exporting correctly and it was quite painful to fix everything up. Blogger allows you to export a copy of your blog using ATOM, however BlogEngine.NET (and other tools) speak BlogML.

I've just released a command line tool that takes the ATOM format Blogger export and converts it to BlogML. You can download Blogger2BlogML from Codeplex. The tool uses .NET 4.0 (client profile) so you'll need to install this if you don't already have it. If you give Blogger2BlogML a try let me know how you get on. 

ESRI Shapefile Library Update

I've just released a small update for my ESRI Shapefile Reader project on Codeplex. The only change is a patch from SolutionMania that fixes a problem when the shapefile name is also a reserved name in the metadata database. The patch escapes the name preventing an exception from being thrown.

Catfood.Shapefile.dll is a .NET 2.0 forward only parser for reading an ESRI Shapefile. Download 1.20 from Codeplex.

Scanning from the ADF using WIA in C#

I've been going nuts trying to scan from the document feeder on my Canon imageClass MF4150. Everything worked as expected from the flatbed, no dice trying to persuade the ADF to kick in. I found some sample code but it was oriented towards devices that can detect when a document is available in the feeder. Evidently my Canon doesn't expose this and so needs to be told the source to use.

The way to do this is to set the WIA_DPS_DOCUMENT_HANDLING_SELECT property to FEEDER. You then read WIA_DPS_DOCUMENT_HANDLING_STATUS to check that it's in the right mode and initiate the scan. This did not work for toffee.

After much experimentation I discovered a solution. I had been setting device properties and then setting item properties before requesting the scan. Switching the order - item then device - made everything work.

Here's the function to scan one page:

More...

Use WPF Dispatcher to invoke event handler only when needed

After floundering a bit with the WPF Dispatcher I've come up with a simple way to make sure an event handler executes on the UI thread without paying the overhead of always invoking a delegate.

void someEvent_Handler(object sender, SomeEventEventArgs e)
{
    if (this.Dispatcher.CheckAccess())
    {
        // do work on UI thread
    }
    else
    {
        // or BeginInvoke()
        this.Dispatcher.Invoke(new Action<object, SomeEventEventArgs>(someEvent_Handler), 
            sender, e);
    }
}

This has the benefit (for me at least) of being very easy to remember. Hook up the event handler and then if there's a chance it could be called from a different thread wrap it using the pattern above. It's easier to read than an anonymous delegate and much faster than defining a specific delegate for the event in question.

I haven't tested the various methods to see which is the fastest yet… will get round to this at some point.

XamlParseException and 256x256 icons

When testing out a WPF app on XP I got an unhelpful XamlParseException error report. 

I was a little puzzled because I was hooking up error reporting in App.xaml.cs:

App.Current.DispatcherUnhandledException += 
    new DispatcherUnhandledExceptionEventHandler(Current_DispatcherUnhandledException);
AppDomain.CurrentDomain.UnhandledException += 
    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

My error handler was attempting to create a XAML window to report the error, and evidently this was bombing out as well triggering the good doctor Watson. I added a MessageBox call instead and discovered that the XamlParseException was wrapping a FileFormatException and the stack trace indicated that the problem was with setting the icon for the window. After removing the icon the app started up fine. Weird.

It turns out that WPF chokes on a compressed 256x256 icon on XP and Vista (Windows 7 seems to cope fine). Saving the icon without compression fixes the problem. I use IcoFX and you can set this at Options -> Preferences -> Options -> Compress 256x256 images for Windows Vista. Of course the consequence is that the icon is a couple of hundred kilobytes larger.

Space and multibyte character encoding for posting to Twitter using OAuth

I've spent the last day learning how to use OAuth and XAuth to post to Twitter. There are rumblings that Twitter will start to phase out basic authentication later this year, and more importantly you can only get the nice “via...” attribution if you use OAuth (for new apps, old ones are grandfathered in).

I coded up my own OAuth implementation, referring to Twitter Development: The OAuth Specification on Wrox and the OAuthBase.cs class from the oauth project on Google Code. Both are great references, but both fail with multibyte characters. The problem is that each byte needs to be separately escaped. OAuthBase.cs encodes characters as ints rather than breaking out the bytes and the Wrox article incorrectly suggests using Uri.EscapeDataString(). 

Here's a method to correctly encode parameters for OAuth:

public static string OAuthUrlEncode(string s)
{
    if (string.IsNullOrEmpty(s))
    {
        return string.Empty;
    }
    else
    {
        StringBuilder sb = new StringBuilder(s.Length);

        for (int i = 0; i < s.Length; i++)
        {
            if (NoEncodeChars.IndexOf(s[i]) == -1)
            {
                // character needs encoding
                byte[] characterBytes = Encoding.UTF8.GetBytes(s[i].ToString());
                for (int b = 0; b < characterBytes.Length; b++)
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture,
                    "%{0:X2}",
                    characterBytes[b]);
                }
            }
            else
            {
                // character is allowed
                sb.Append(s[i]);
            }
        }

        return sb.ToString();
    }
}

NoEncode chars is a list of the permitted characters:

private const string NoEncodeChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";

An impact of this encoding is that spaces must be encoded as %20 rather than plus. I was worried that each space would end up counting as three characters towards the 140 character limit. I tested this and it isn't true, so use HttpUtility.UrlEncode() to calculate the number of characters in the post OAuthUrlEncode() or similar to actually encode post parameter.

Reviews and links for March 2010

Juliet, Naked by Nick Hornby

Juliet, Naked by Nick Hornby

3/5

Classic Hornby. It's fairly close to High Fidelity with it's themes of love and music obsession-ism and so feels slightly too comfortable but certainly worth a read if you're a fan. 3/24/2010 2:00:00 AM

 

The Girl with the Dragon Tattoo (Millennium, #1) by Stieg Larsson

The Girl with the Dragon Tattoo (Millennium, #1) by Stieg Larsson

3/5

Slow, but highly atmospheric mystery. The first half of the book is dedicated to setting the scene and then the pieces start to fit into place like a glacier melting. The pace makes the occasional punctuation of extreme sexual violence all the more shocking. Fun enough, so I'll probably read the rest of the trilogy and try to catch the film (which has to be a profoundly truncated version).3/22/2010 2:00:00 AM

 

Practical WPF Charts and Graphics by Jack Xu

Practical WPF Charts and Graphics by Jack Xu

4/5

Be aware that this book is 90% code, 5% mathematics and 5% explanation. This isn't a criticism, Dr. Xu builds up a complete charting library that includes 2D, WPF 3D and manual 3D methods. The mathematics covers the theory and practice of 2D and 3D transforms as well as techniques for smoothing, interpolating and trending data. It's a fast read to get a sense of the content and then a great reference work to dip back into as needed. 3/14/2010 3:00:00 AM

 

C# Design and Development: Expert One on One by John Paul Mueller

C# Design and Development: Expert One on One by John Paul Mueller

1/5

This book is just atrocious. Each section sells itself as providing all the information you need about a certain topic, then provides trivial and often incorrect or at least highly subjective details. A couple of examples:

The chapter on error handling makes the point that you should catch the most specific Exception possible, but then goes on to demonstrate catching a FormatException, a DivideByZero exception and then just System.Exception. The whole point is to avoid catching Exceptions that you can't handle. There's a legitimate debate here between trying to plaster up the cracks with general catches and letting the application die with a useful stack, however this book doesn't discuss it. There's also very brief coverage of creating your own derived Exception but it doesn't touch on serialization.

Serializing an XML file is somehow included in the section on "Special Coding Methodologies", and labors over calling both .Flush() and .Close() on a StreamWriter. Despite the fact that you only need to call Close(), and that StreamWriter is IDisposable and so a using statement is really the way forward for this example.

I could go on, but won't. Avoid. 3/8/2010 2:00:00 AM

 

Links

- Dorothy Erskine Park Exists from Spots Unknown (Must go find this park.).

- Casttoo from jwz (I want to break my arm again...).

- Woman murdered over Facebook photo from BBC News | News Front Page | World Edition (Somehow I don't think the photo being on Facebook was the important part of the story...).

- Petition against Pope's UK visit from BBC News | News Front Page | World Edition (A better petition would be to get the Pope and Dawkins together on Question Time.).

- 'Heart risk' at football stadiums from BBC News | News Front Page | World Edition (Surprisingly few are equipped to remove gall stones as well.).

- Postal Service's emerging model: Never on Saturday from SFGate: Top News Stories (How about once a week. While you're at it recycle the junk at the post office and don't bother hauling it out for delivery.).

Reviews and links for February 2010

Programming WPF by Chris Sells

Programming WPF by Chris Sells

4/5

A highly detailed and well written reference to WPF. Note that this second edition is still based on Visual Studio 2005 / .NET 3.0 so a little out of date now. I still found the book to be very useful and would recommend it both for picking up WPF basics and to refer back to for more advanced topics when needed.2/26/2010 2:00:00 AM

 

Professional C# 2008 by Christian Nagel

Professional C# 2008 by Christian Nagel

4/5

I'm in the process of upgrading to VS2008 and loved the 2005 version of this book so picked up the 2008 update. It's a broad language and framework reference, perfect for understanding what's available in .NET 3.5 and how to get started. My only complaint is that it could have used a "what's new" section or guide to separate out completely new technologies from those familiar from .NET 2.0. Not a big problem though, it's easy to skim through the old stuff and then pay attention when you reach something new. I'll probably pick up the 2010 version in 2015 or so ;)2/15/2010 2:00:00 AM

 

Links

- UK NHS urged to buy Fairtrade tools from BBC News | News Front Page | World Edition (Fair enough, but what about having developing countries pay to train doctors and nurses and then poaching them to work for the NHS?).

- Brown 'upset' by bullying claims from BBC News | News Front Page | World Edition (And when he finds those responsible he's going to turn purple, squint and twat them.).

- CBS runs free ad for "magic" energy box from Boing Boing (A slightly more skeptical take. Magic box plus natural gas...).

- French halal burger sparks appeal from BBC News | News Front Page | World Edition (So eat somewhere else. You're in France and not about to starve.).

- One inch equals $30,000 in online dating world from Boing Boing (I'm worth $2.2 million :)).

- Video: Mantis vs. Cursor from Boing Boing (OK, I need a Preying Mantis to entertain me like this while I work...).

- Toyota recalls 8,000 US vehicles from BBC News | News Front Page | World Edition (And they're not even real propellers. They're just the joke ones you can attach to your tow hitch.).

- Britain reveals how U.S. treated detainee from SFGate: Top News Stories (Miliband against the "principle of their disclosure by an English court against U.S. wishes"!).

- Mariposaaah!!! from Spots Unknown (Feels steeper walking up it.).

BlogEngine.NET most popular pages widget using Google Analytics

I finished off my BlogEngine.NET migration yesterday missing a couple of useful sections from the previous incarnation of this blog. The first is a list of the most popular posts based on Google Analytics data. I've just finished porting this from a UserControl to a widget for BlogEngine.NET. To use this just download and extract this zip file to your widgets directory:

MostPopularFromGA.zip (5.22 kb)

You can see the widget in action under the Most Popular heading to the left if you're reading this post on the blog.

More...

I Thought He Came With You
Robert Ellison's blog.

Thank you for choosing HSA Bank!

Blog Archives