Archive for April, 2008

Localizing MVC for ASP.NET views and master pages

Microsoft’s MVC for ASP.NET is still under serious development but at the moment support for localization is a little weak. Here’s one approach that works with the 04/16 source-drop.

LocalizingWebFormViewLocator class

This class helps by trying to identify language-specific versions of views, user controls and master-pages where they exist, falling back to the generic one where necessary.

public class LocalizingWebFormViewLocator : ViewLocator
{
    public LocalizingWebFormViewLocator() : base() {
        ViewLocationFormats = new[] { "~/Views/{1}/{0}.{2}aspx", "~/Views/{1}/{0}.{2}ascx", "~/Views/Shared/{0}.{2}aspx", "~/Views/Shared/{0}.{2}ascx" };
        MasterLocationFormats = new[] { "~/Views/{1}/{0}.{2}master", "~/Views/Shared/{0}.{2}master" };
    }

    protected override string GetPath(RequestContext requestContext, string[] locationFormats, string name) {
        string foundView = FindViewLocation(locationFormats, requestContext, name, CultureInfo.CurrentUICulture.Name + ".");
        if (String.IsNullOrEmpty(foundView))
            foundView = FindViewLocation(locationFormats, requestContext, name, "");
        return foundView;
    }

    protected string FindViewLocation(string[] locationFormats, RequestContext requestContext, string name, string cultureSuffix) {
        string controllerName = requestContext.RouteData.GetRequiredString("controller");
        foreach (string locationFormat in locationFormats) {
            string viewFile = string.Format(CultureInfo.InvariantCulture, locationFormat, name, controllerName, cultureSuffix);
            if (HostingEnvironment.VirtualPathProvider.FileExists(viewFile))
                return viewFile;
            }
        return null;
    }
}

Using the class

To use the class you must set the ViewLocator on the WebFormViewEngine to a new instance of LocalizingWebFormViewLocator (either in the constructor or in your common controller subclass) and ensure that any master pages are specified on the RenderView calls to ensure the localized version is detected.

public class HomeController : Controller
{
    public HomeController() {
        ((WebFormViewEngine)ViewEngine).ViewLocator = new LocalizingWebFormViewLocator();
    }

    public ActionResult Index() {
        return RenderView("Index", "Site");
    }

    public ActionResult About() {
        return RenderView("About", "Site");
    }
}

You must also ensure the thread’s current UI culture is set. The easiest way to do this is to specify the following in your web.config file’s system.web section which will pick it up automatically from the user’s browser settings via the HTTP language-accept header.

<globalization responseEncoding="UTF-8" requestEncoding="UTF-8" culture="auto" uiCulture ="auto" />

MVC for ASP.NET default page in pseudo-Japanese via the Babelfish
Then all you need to do is create views and master pages that have the culture name appended between the name and .aspx, e.g:

/Views/Home/Index.aspx (common fall-back for this view)
/Views/Home/Index.ja.aspx (Japanese view)
/Views/Home/Index.en-GB.aspx (British English view)

/Views/Shared/Site.Master (common fall-back for this masterpage)
/Views/Shared/Site.ja.Master (Japanese masterpage)

Caveats

There are some limitations to this solution:

Only primary language is attempted

Only the user’s primary language specified in their browser is attempted despite browsers having a complete list in order of preference. Ideally we would scan down this entire list before giving up but that would need more code and there is the issue of whether scanning for several languages across several folders could be too much of a performance hit.

Specifying the masterpage on RenderView

It would be nice if you didn’t have to specify the masterpage on renderview but if you do not then the ViewLocator never gets called to resolve the actual masterpage address. This may be for backward compatibility within MVC.

Creating files in Visual Studio

Visual Studio 2008 seems to get a little confused if you create a Index.ja.aspx or Site.ja.aspx – whilst the files are created okay the names are not and you will need to adjust the class names to ensure they don’t conflict and make sure the opening declaration on the .aspx file points to the right code-behind page and inherits from the correct name.

Of course the beauty of this approach is you can mix-and-match using dedicated views where required and localising labels in the fall-back view when it isn’t.

[)amien

Boot Camp 2.1, VMware Fusion 1.1.2 and MacBook Pro firmware

Boot Camp 2.1

Apple have released Boot Camp 2.1 which finally includes official 64-bit support on Vista and support for Windows XP Service Pack 3.

This update may mean that 3D games will play without locking up or installing NVidia’s own drivers and that the trackpad functions correctly again (broken since Boot Camp 1.x)

MacBook Pro Firmware 1.5.1

Apple’s MacBook Pro Firmware Update 1.5.1 applies to all recent MacBook Pro’s including the ones with MBP31.0070.B05 firmware that the 1.5 update failed to upgrade leaving 17″ owners on MBP31.0070.B07.

The new firmware does not fix a problem where trackpad input would become jerky after suspending/sleeping and turning Airport off would make matters worse. 10.5.3 has fixes for Airport after sleeping which might solve the issue…

VMware Fusion 1.1.2

VMware Fusion 1.1.2 is just out and includes a host of fixes and improvements including:

  • Windows XP Service Pack 3
  • Network and USB compatibility
  • Time Machine compatibility

Now that VMware lets Time Machine backup the VM image file and that Time Machine backs up modified files in their entirety you might want to exclude ~/Documents/Virtual Machines it unless you fancy loosing several gigabytes per hour whilst using a VM. Of course if you have your VM running off it’s own partition to allow Boot Camp too then that’s not an issue.

With any luck VMware will figure out a way of Time Machine backing up changed individual files within the Windows filesystem…

[)amien

WordPress 2.5 notes from the field

It’s been a few weeks since I upgraded to WordPress 2.5 and whilst the upgrade went well it hasn’t been all plain sailing.

New and changed

Manage files removed

The Manage > Files administration function has been silently removed despite still appearing in the on-line documentation.

If you don’t have FTP access this was the only way to modify your .htaccess and other important files without installing additional software. I can understand such a powerful function could be abused but an option to turn it back on or even a warning about its removal in the upgrade notes/read-me would have been useful.

Hopefully somebody will repackage the old functionality into a plug-in.

New look administration

I’m not sold on the new administration theme look but Dean J Robinson has crafted a plug-in called Fluency that refines the styling.

Generally usability in the administration user interface is better, the write post screen makes a lot more sense and the category & tag management is more logical.

Auto update plug-ins

I love this new feature, it shows you when a new version of a plug-in is available and then lets you automatically update. It isn’t without issue however, specifically it:
Screen-shot of WordPress 2.5's automatic plug-in upgrade feature

  1. overwrites modified local versions without warning
  2. may go wrong (it “upgraded” my wp-PostViews to wp-DBManager)
  3. does not provide a roll-back or revert facility

Still it’s a v1 feature and I’m sure it’ll get some refinement in 2.6.

Compatibility

Live search broken (Redoable theme)

The Ajax-enabled live search is broken in Redoable although the normal search works. There have been no signs of an update in quite despite an un-patched HTML injection vulnerability.

Gregarious

This social bookmarking plug-in is broken in 2.5 and the author is too busy to fix it right now and the search for an alternative led me to Joost and his Sociable plug-in.

I’m not 100% happy with the output from Sociable right now but that can wait until my new theme is finished.

Other tweaks

These weren’t caused by the 2.5 upgrade but once you start messing with one thing there’s always that urge to fix other things you know aren’t right.

Google Analytics

Whilst testing my site I found XHTML compliance was broken. It turns out that Joost’s Google Analytics for WordPress incorrectly rewrites the hyperlinks when they parent another element such as an image. Putting on my PHP hacking hat I managed to fix it by editing the plug-in and changing the last line of ga_parse_link to:

return '<a '.$matches[1].'href="'.$matches[2].'//' .$matches[3].'"'.' '.$coolBit.$matches[4].'>'.$matches[5].'</a>';

Subscriber counts

My feed subscriber counts have been bugging me for a while as they jump up and down seemingly at random. In fact, it can be traced down to two things:

  1. If you base it on less than 5 days of activity you’ll get the weekend dip
    Solution: Count 7 days worth of individual subscribers
  2. Google Reader etc. sometimes stop passing the subscriber count from time to time
    Solution: Use single most recent multi-subscriber header for each service/feed in the last 30 days

If you want to do the same you need to edit the Feed Statistics plug-in and change the how_many_subscribers function to:

$q = "SELECT subscribers, CASE WHEN subscribers = 1 THEN identifier ELSE CONCAT(identifier, feed) END AS ident FROM ".$table_prefix."feed_subscribers  WHERE ((subscribers = 1 AND
	date > '".date("Y-m-d H:i:s", time() - (60 * 60 * 24 * get_option("feed_statistics_expiration_days")))."' ) OR 
	(subscribers = 1 AND LOCATE('###',identifier) != 0 AND 
	date > '".date("Y-m-d H:i:s", time() - (60 * 60 * 24 * get_option("feed_statistics_expiration_days") * 3))."' ) OR
	(subscribers > 1 AND date > '".date("Y-m-d H:i:s", time() - (60 * 60 * 24 * 30 * 3))."' ) )
	ORDER BY ident ASC, date DESC";

This should help but it’s not ideal with individual readers counted more than once if they change IP and groups counted as one if they are sharing an IP/NAT.

[)amien

Four Windows apps for home-sick Mac users

Libra (like Delicious Library)

Delicious Library is a DVD, game and book organisation tool I’ve been using since my PowerBook G4 and a 2.0 version has been dangling from Wil Shipley’s mouth longer than I care to remember.

Windows users however will find Libra a very interesting clone and it features some of the same great features such as bar-code scanning via a web cam, tracking loans, a rendered virtual shelf and fast queries.

Unlike Delicious Library 1.x it also features sharing your library on-line, tweaking the types and rendering and a more advanced query engine and is available free for non-commercial use.

E Text Editor (like TextMate)

TextMate is a programming editor for the Mac that can be extended through the use of Bundles to provide additional syntax highlighting, menu options and command processing. It is fast, feels lightweight and therefore incredibly customisable all of which contribute to it’s success.

E Text Editor is a Windows clone of TextMate that doesn’t just mimic the user interface but also provides compatibility with TextMate bundles allowing you to take advantage of some of the many great enhancements available and at $34 is almost half the price although it doesn’t feel as snappy as it’s Mac counterpart.

Digsby (like Adium)

Adium is my instant messaging client of choice allowing me a single app to manage MSN, ICQ and Google Talk (I wish they would get basic Skype support in there too).

Digsby provides similar functionality whilst also throwing social networking (Facebook, Twitter) and email notification (Hotmail, GMail, Yahoo Mail etc.) into the mix.

Dash (like Quicksilver)

QuickSilver provides a quick keyboard-based entry system for performing a wide variety of tasks and selections within Mac OS X and what it doesn’t do can often be added with plug-ins.

Dash achieves a similar effect on Windows but I have to admit I’m not really sold on either yet. I think the movement from keyboard to mouse and back every now and then must be a good break for your hands if not for your productivity…

[)amien