Blog Archives

A Day in the Life of a Metro-veloper

This is a follow-up post to my Windows Phone 7 presentation last week at the SDDN.

I have uploaded my powerpoint deck to SlideShare.

Some of the sample apps I used are available on MSDN.

And there was a recent video on youtube of an awesome golfing app that really shows the power of the WP7 UX.

Advertisements

push notifications in windows phone 7

Basics

There’s lots of information hiding within about 10 links on MSDN about how push notifications for WP7. The short of it is the phone opens a HttpNotificationChannel which gives it a unique URI for your applications to send notifications to it.

There are three types of notifications – tile, toast and raw. Tile notifications are used for changing the background, count and title of the application when it is pinned to the Start screen. Toast notifications provide unobtrusive notifications to users when they are outside the application, allowing them to step in easily to perform an action. Raw notifications are messages of any format that can be sent to the phone application and received while it is active.

The problem with the information out there is that it is slightly conflicting because of the recent changes to the APIs with different versions of the toolkit. As a result, I spent many hours trying to get this relatively simple piece of functionality working. At one point I decided that whenever I got something working I’d try shrink wrap it and publish it, so here we go…

DISCLAIMER: WOMM…

WARNING: There’s a lot of code here… Please read the Client Side and Server Side sections before believing you are qualified to download the sample. The sample has a thin WPF client implementation over the server side code to make it a little easier to get started. Remember to check the Debug output window for the phone application when you need a Uri to send a notification.

Client Side

My aim was to get the code required for subscribing to notifications to be as simple as possible. I got it down to the following few lines of code:

// in App.ctor
NotificationService notificationService = new NotificationService("some funky channel name");
notificationService.RawNotificationReceived += RawNotificationReceived;
notificationService.ToastNotificationReceived += ToastNotificationReceived;
notificationService.ChannelUriUpdated += ChannelUriUpdated;

// in Application_Launching & Application_Activated
notificationService.Subscribe();

// event handlers
void ToastNotificationReceived(object sender, ToastNotificationReceivedEventArgs e)
{    // example of handling a toast notification within the application
    MessageBox.Show(e.Message, e.Title, MessageBoxButton.OK);
}

void RawNotificationReceived(object sender, RawNotificationRecievedEventArgs e)
{
    MessageBox.Show(e.Message);
}

void ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
    // call a webservice to report e.ChannelUri
}

There are a couple of things to note. Firstly, the Subscribe() method is called in the Application_Launching and Application_Activated events. This is due to the tombstoning nature of WP7.

Next, there are separate event handlers for Toast and Raw notifications. They are handled differently because toast notifications have a definite payload format that specifies the ability to send to pieces of text (a title and a message). A raw notification can be anything, which is why I have decided to simply surface the string representation of the payload. A toast must also be handled if the application is executing – i.e. it will not be displayed by the OS.

Also, there is no tile notification handler. This is because the OS handles this directly.

Lastly, the ChannelUriUpdated event handler. This is necessary for your phone application to let the server application know that there is a phone waiting for notifications. When this occurs, the phone application should call a web service to register the URI. The NotificationService class will write this information to the Debug console whenever the application is started, so it is not required for debugging purposes.

Server Side

While I was busy working on the client side, I realised that obviously I’d eventually need to have some server side code to send the notifications. Again, I wanted to simplify it as much as possible:

NotificationService service = new NotificationService();

// send a raw notification
service.SendRaw(clientUri, messageText);

// send a toast notification
service.SendToast(clientUri, titleText, messageText);

// send a tile notification
service.SendTile(clientUri, backgroundImageUri, countValue, titleText);

See… simple. Smile

The Real Code

As I mentioned earlier, you can download all this here. Otherwise, feel free to read through this (or just copy/paste it) to get a better understanding of how the HttpNotificationChannel works.

Client side NotificationService implementation:

public class NotificationService
{
    string channelName;
    HttpNotificationChannel channel;

    public NotificationService(string channelName)
    {
        this.channelName = channelName;
    }

    /// <summary>
    /// Subscribes to the notification events on the channel.
    /// If the channel doesn't already exist, it will be created
    /// and bound to shell tile and toasts.
    /// </summary>
    public void Subscribe()
    {
        if (channel == null) BindChannel();
    }

    /// <summary>
    /// Unubscribes from the notification events on the channel.
    /// </summary>
    public void Unsubscribe()
    {
        if (channel != null) UnsubscribeFromChannelEvents();
    }

    /// <summary>
    /// Finds or creates the notification channel and binds the shell tile
    /// and toast notifications as well as events.
    /// </summary>
    private void BindChannel()
    {
        channel = HttpNotificationChannel.Find(channelName);

        if (channel == null || channel.ChannelUri == null)
        {
            if (channel != null) DisposeChannel();

            channel = new HttpNotificationChannel(channelName);
            channel.ChannelUriUpdated += channel_ChannelUriUpdated;
            channel.Open();
        }
        else System.Diagnostics.Debug.WriteLine(channel.ChannelUri.AbsoluteUri);

        SubscribeToChannelEvents();

        if (!channel.IsShellTileBound) channel.BindToShellTile();
        if (!channel.IsShellToastBound) channel.BindToShellToast();
    }

    /// <summary>
    /// Subscribes to the channel's events.
    /// </summary>
    private void SubscribeToChannelEvents()
    {
        channel.ShellToastNotificationReceived += channel_ShellToastNotificationReceived;
        channel.HttpNotificationReceived += channel_HttpNotificationReceived;
        channel.ErrorOccurred += channel_ErrorOccurred;
    }

    /// <summary>
    /// Unsubscribes from the channel's events
    /// </summary>
    private void UnsubscribeFromChannelEvents()
    {
        channel.ShellToastNotificationReceived -= channel_ShellToastNotificationReceived;
        channel.HttpNotificationReceived -= channel_HttpNotificationReceived;
        channel.ErrorOccurred -= channel_ErrorOccurred;
    }

    /// <summary>
    /// Closes the channel and disposes it.
    /// </summary>
    private void DisposeChannel()
    {
        channel.Close();
        channel.Dispose();
        channel = null;
    }

    /// <summary>
    /// Event handler for the ChannelUriUpdate event.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
    {
        channel.ChannelUriUpdated -= channel_ChannelUriUpdated;
        System.Diagnostics.Debug.WriteLine(e.ChannelUri.AbsoluteUri);
        OnChannelUriUpdated(e);
    }

    /// <summary>
    /// Raised when the notification channel is given a URI.
    /// </summary>
    /// <remarks>
    /// This is when you would call a web service to tell it that a client is
    /// registered and what the notification URI is.
    /// </remarks>
    public event EventHandler<NotificationChannelUriEventArgs> ChannelUriUpdated;

    /// <summary>
    /// Raises the ChannelUriUpdated event.
    /// </summary>
    /// <param name="e"></param>
    protected virtual void OnChannelUriUpdated(NotificationChannelUriEventArgs e)
    {
        if (ChannelUriUpdated != null) ChannelUriUpdated(this, e);
    }

    /// <summary>
    /// Event handler for the HtppNotificationReceived event.
    /// This is called when a raw notification is received.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void channel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
    {
        byte[] bytes;
        using (var stream = e.Notification.Body)
        {
            bytes = new byte[stream.Length];
            stream.Read(bytes, 0, (int)stream.Length);
        }
        var message = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

        OnRawNotificationReceived(message);
    }

    /// <summary>
    /// Occurs when a raw notification is received.
    /// </summary>
    public event EventHandler<RawNotificationRecievedEventArgs> RawNotificationReceived;

    /// <summary>
    /// Raises the RawNotificationReceived event on the UI thread.
    /// </summary>
    /// <param name="message"></param>
    protected virtual void OnRawNotificationReceived(string message)
    {
        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            if (RawNotificationReceived != null) 
                RawNotificationReceived(
                    this, 
                    new RawNotificationRecievedEventArgs(message)
                    );
        });
    }

    /// <summary>
    /// Event handler for the ShellToastNotificationReceived event.
    /// This occurs when a toast notification is received on the channel.
    /// </summary>
    /// <remarks>
    /// This must be handled by the application if it is running when a toast is received.
    /// </remarks>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void channel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
    {
        var title = e.Collection.Values.First();
        var message = e.Collection.Values.Skip(1).FirstOrDefault() ?? string.Empty;
        OnToastNotificationReceived(title, message);
    }

    /// <summary>
    /// Occurs when a toast notification is received.
    /// </summary>
    /// <remarks>
    /// This must be handled by the application if it is running when a toast is received.
    /// </remarks>
    public event EventHandler<ToastNotificationReceivedEventArgs> ToastNotificationReceived;

    /// <summary>
    /// Raises the ToastNotificationReceived event on the UI thread.
    /// </summary>
    /// <param name="title"></param>
    /// <param name="message"></param>
    protected virtual void OnToastNotificationReceived(string title, string message)
    {
        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            if (ToastNotificationReceived != null) 
                ToastNotificationReceived(
                    this, 
                    new ToastNotificationReceivedEventArgs(title, message)
                    );
        });
    }

    /// <summary>
    /// Event handler for the ErrorOccurred event.
    /// Handles different events according to ErrorType.
    /// </summary>
    /// <remarks>
    /// Needs more work... ;-(
    /// </remarks>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void channel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
    {
        switch (e.ErrorType)
        {
            // something went severely wrong. lets wait a while before trying again.
            case ChannelErrorType.ChannelOpenFailed:
                DisposeChannel();
                System.Threading.Thread.Sleep(60000);
                BindChannel();
                break;
            // an image uri has been referenced in a notification that was
            // not bound to the shell tile.
            case ChannelErrorType.MessageBadContent:
                break;
            // too many notifications have been received in too short a time span.
            case ChannelErrorType.NotificationRateTooHigh:
                break;
            // a bad payload was received. re-establish the connection to overcome this.
            case ChannelErrorType.PayloadFormatError:
                DisposeChannel();
                BindChannel();
                break;
            // the type notifications we're receiving is going to change.
            case ChannelErrorType.PowerLevelChanged:
                break;
            default:
                break;
        }
    }
}

public class RawNotificationRecievedEventArgs : EventArgs
{
    public string Message { get; private set; }
    public RawNotificationRecievedEventArgs(string message)
    {
        Message = message;
    }
}

public class ToastNotificationReceivedEventArgs : EventArgs
{
    public string Title { get; private set; }
    public string Message { get; private set; }
    public ToastNotificationReceivedEventArgs(string title, string message)
    {
        Title = title;
        Message = message;
    }
}

Server side code:

public interface INotificationService
{
    NotificationResponse SendTile(string uri, string backgroundImageUri, int count, 
                                  string title, [Optional] Guid messageId);
    NotificationResponse SendToast(string uri, string text1, [Optional] string text2, 
                                   [Optional] Guid messageId);
    NotificationResponse SendRaw(string uri, string message, [Optional] Guid messageId);
}

public class NotificationService : INotificationService
{
    const int maxPayloadLength = 1024;

    const string targetHeader = "X-WindowsPhone-Target";
    const string notificationClassHeader = "X-NotificationClass";
    const string messageIdHeader = "X-MessageID";
    const string notificationStatusHeader = "X-NotificationStatus";
    const string subscriptionStatusHeader = "X-SubscriptionStatus";
    const string deviceConnectionStatusHeader = "X-DeviceConnectionStatus";

    const string tileMessageFormat =
        "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
        "<wp:Notification xmlns:wp=\"WPNotification\">" +
            "<wp:Tile>" +
                "<wp:BackgroundImage>{0}</wp:BackgroundImage>" +
                "<wp:Count>{1}</wp:Count>" +
                "<wp:Title>{2}</wp:Title>" +
            "</wp:Tile>" +
        "</wp:Notification>";
    /// <summary>
    /// X-WindowsPhone-Target: token
    /// </summary>
    const string tileTarget = "token";
    /// <summary>
    /// X-NotificationClass: 1
    /// </summary>
    const string tileNotificationClass = "1";

    const string toastMessageFormat =
        "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
        "<wp:Notification xmlns:wp=\"WPNotification\">" +
            "<wp:Toast>" +
                "<wp:Text1>{0}</wp:Text1>" +
                "<wp:Text2>{1}</wp:Text2>" +
            "</wp:Toast>" +
        "</wp:Notification>";
    /// <summary>
    /// X-WindowsPhone-Target: toast
    /// </summary>
    const string toastTarget = "toast";
    /// <summary>
    /// X-NotificationClass: 2
    /// </summary>
    const string toastNotificationClass = "2";

    /// <summary>
    /// X-NotificationClass: 3
    /// </summary>
    const string rawNotificationClass = "3";

    public NotificationResponse SendTile(string uri, string backgroundImageUri, int count, 
                                         string title, [Optional] Guid messageId)
    {
        var str = string.Format(tileMessageFormat, backgroundImageUri, count, title);
        return SendNotification(uri, str, tileNotificationClass, tileTarget, messageId);
    }

    public NotificationResponse SendToast(string uri, string text1, [Optional] string text2, 
                                          [Optional] Guid messageId)
    {
        var str = string.Format(toastMessageFormat, text1, text2);
        return SendNotification(uri, str, toastNotificationClass, toastTarget, messageId);
    }

    public NotificationResponse SendRaw(string uri, string message, 
                                        [Optional] Guid messageId)
    {
        return SendNotification(uri, message, rawNotificationClass, messageId: messageId);
    }

    private NotificationResponse SendNotification(string uri, string message, 
                                                  string notificationClass, 
                                                  [Optional] string target, 
                                                  [Optional] Guid messageId)
    {
        var payload = Encoding.UTF8.GetBytes(message);
        if (payload.Length > maxPayloadLength) 
            throw new ArgumentException(
                "The message provided is longer than the maximum payload length (1024B).",
                message
                );

        var sendNotificationRequest = WebRequest.Create(uri) as HttpWebRequest;
            
        sendNotificationRequest.Method = WebRequestMethods.Http.Post;
        sendNotificationRequest.ContentLength = payload.Length;
        sendNotificationRequest.ContentType = "text/xml";

        // X-NotificationClass: 1, 2, 3
        sendNotificationRequest.Headers.Add(notificationClassHeader, notificationClass);
        // X-WindowsPhone-Target: token, toast
        if (!string.IsNullOrWhiteSpace(target)) 
            sendNotificationRequest.Headers.Add(targetHeader, target);
        // X-MessageId: 00000000-0000-0000-0000-000000000000
        if (messageId != null && messageId != Guid.Empty) 
            sendNotificationRequest.Headers.Add(messageIdHeader, messageId.ToString());

        using (var requestStream = sendNotificationRequest.GetRequestStream())
            requestStream.Write(payload, 0, payload.Length);

        HttpWebResponse response;
        string errorMessage = null;
        try
        {
            response = sendNotificationRequest.GetResponse() as HttpWebResponse;
        }
        catch (WebException ex)
        {
            response = ex.Response as HttpWebResponse;
            errorMessage = ex.Message;
        }
        return new NotificationResponse
        {
            MessageId = response.Headers[messageIdHeader],
            ErrorMessage = errorMessage,
            NotificationStatus = response.Headers[notificationStatusHeader],
            SubscriptionStatus = response.Headers[subscriptionStatusHeader],
            DeviceConnectionStatus = response.Headers[deviceConnectionStatusHeader],
            StatusCode = response.StatusCode
        };
    }
}

public class NotificationResponse
{
    public string ErrorMessage { get; set; }
    public DateTimeOffset Timestamp { get; set; }
    public string MessageId { get; set; }
    public HttpStatusCode StatusCode { get; set; }
    public string NotificationStatus { get; set; }
    public string DeviceConnectionStatus { get; set; }
    public string SubscriptionStatus { get; set; }
}

DOWNLOAD IT NOW!

Remember, to get the Uri just watch the Debug output window when your WP7 application starts up.

Good luck Smile

[Update 2010-08-27] Added extra check to Client.NotificationService.BindChannel() so that a channel that already exists but does not have a URI is disposed and a new one is created.

Commerce Server 2009 R2 and Visual Studio 2010

So you’re a Commerce Server developer that’s sitting on the bleeding edge…? Well now you’ve got the same chance of starting your site as easily as you did with CS2007 and VS2008 – i.e. not much. Why, you ask…? Because the team have not updated the template that they use for the Project Creation Wizard addin, so it’s just as useful as it always has been… =p

Let’s see how it works…

Using the Project Creation Wizard

Just like in the old days of CS2007 and pre-R2, hit File > New Website and you’ll get the “New Web Site” wizard. Select your language of choice (C# is the better one) and “Commerce C# ASP.NET Web Application”.

image

Although for some odd reason, they’ve decided you can’t use the file system or any non-localhost url (like above), so at least when you first create the site you need to do so under localhost.

If you’re a real developer, you’ll say yes to this too… 🙂

image

You’ll then have the Commerce Server Site Packager application pop up to unpack a default web site. This will ask for the site url, but not ask any of the good old questions like what you want to name the application directories, meaning you’re stuck with a crappy prefix on every directory it unpacks.

Anyway, once that’s done you should have an unpacked beginning of a web site. If you go to this point without a couple of COM errors, then congratulations. But now you’ll also notice that the project created was a “Web Site” project instead of a “Web Application” project.

So what’s next… oh yeah! Find another way to do it that actually makes sense.

Manual Site Creation

If you’ve been through the process of using the Commerce Server Site Package application to extract a site in previous versions of commerce server, then you’re not going to learn much here… nothing has changed! If you haven’t, please read on.

Well if you’ve been through the Project Creation Wizard then you have two things up your sleeve, you have a good web.config to start from and a csapp.ini file that points to the original PUP file used to unpack the empty website. If you haven’t, then don’t worry – I’ve uploaded the Commerce Server 2009 Starter Files to my SkyDrive and I can tell you that the original PUP file lives at “C:\Program Files (x86)\Microsoft Commerce Server 9.0\Extensibility Kits\Samples\Pup Packages\empty.pup”.

Now you can open the Commerce Server Site Package application manually at “C:\Program Files (x86)\Microsoft Commerce Server 9.0\PuP.exe”. It will ask you if you want to package or unpackage, but if you don’t have a site on your machine package will be disabled and unpackage will be selected. After hitting next, select the PUP file mentioned above and select Custom Unpack then hit next again. Then select create a new site and hit next.

Now you need to type a name into Site Name text box that does not conflict with any existing sites and click next – e.g. CommerceSample. This name is used by your web application to identify which site resources are used by the application because Commerce Server allows you to have multiple “Sites” on a machine. Then you’ll want to unpack all the resources available and click next. Click next again to create the authentication and profiling resources.

Now you will be setup all the database connections for each resource in the site.

image

Selecting a resource and clicking Modify allows you to set all the basic connection details. If you are using a remote database server, this is where you need to change the settings.

image

After modifying the connection strings as necessary and clicking next, you will be able to select the applications you want to unpack.

image

Each Site is “usually” made up of 5 applications – a Marketing, Orders, Profile and Catalog web service and a Web app. After selecting them all hit next.

You can now rename any or all of the applications and change the web site in IIS that they will be hosted on and virtual directory they will be under.

image

After a few seconds, you will be asked to provide some scripts. Click next twice to skip this.

After about a minute, you will be notified of whether the database connections were successfully set up. Click next to continue. You will then be notified of whether all the resources were extracted successfully. Click done.

Now, to get the web config into the right place, find the location of the web application that was extracted and drop in the web.config. This folder will have 3 files in it before you drop in the config file– csapp.ini, OrderObjectMappings.xml and OrderPipelineMappings.xml.

And that’s it! Well, not really… you now have extracted a Commerce Server web site, but it will not run. Now you’re in another world of pain called “Configuring a Commerce Server Site”.

Want Open Search Integration in Your Website…?

Over the past few weeks, Tatham Oddie, Damian Edwards and myself have been working on publishing a framework/toolkit for integration OpenSearch into any ASP.NET search enabled website. I’m pleased to announce we have finally hit a release!

The project is available at opensearchtoolkit.codeplex.com. Tatham has a great post on how to integrate it into your site on his blog

OpenSearch is a technology that already has widespread support across the web and is now getting even more relevant with Internet Explorer 8’s Visual Search feature and the Federated Search feature in the upcoming Windows 7 release.

Now it’s time to make it even easier. Ducas Francis, one of the other members of my team, took on the job of building out our JSON feed for Firefox as well as our RSS feed for Windows 7 Federated Search. More formats, more fiddly serialization code. Following this, he started the OpenSearch Toolkit; an open source, drop-in toolkit for ASP.NET developers to use when they want to offer OpenSearch.

Today marks our first release.

So get on over to codeplex, hit up Tatham’s blog for instructions and drop the toolkit into your web site so you can take advantage of all the coolness that is OpenSearch.

Discovering Search Terms

More trawling through old code I had written brought this one to the surface. One of the requirements of the system I’m working on was to intercept a 404 (Page Not Found) response and determine if the referrer was a search engine (e.g. google) to redirect to a search page with the search term. Intercepting the 404 was quite easily done with a Http Module…

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace DemoApplication
{
    public class SearchEngineRedirectModule : IHttpModule
    {
        HttpApplication _context;

        public void Dispose()
        {
            if (_context != null)
                _context.EndRequest -= new EventHandler(_context_EndRequest);
        }

        public void Init(HttpApplication context)
        {
            _context = context;
            _context.EndRequest += new EventHandler(_context_EndRequest);
        }

        void _context_EndRequest(object sender, EventArgs e)
        {
            string searchTerm = null;
            if (HttpContext.Current.Response.StatusCode == 404
                && (searchTerm = DiscoverSearchTerm(HttpContext.Current.Request.UrlReferrer)) == null)
            {
                HttpContext.Current.Response.Redirect("~/Search.aspx?q=" + searchTerm);
            }
        }

        public string DiscoverSearchTerm(Uri url)
        {
            …
        }
    }
}

Implementing DiscoverSearchTerm isn’t that difficult either. We just have to analyse search engine statistics to see which ones are most popular and analyse the URL produced when performing a search. Luckily for us, most are quite similar in that they use a very simple format that has the search term as a parameter in the query string. The search engines I analysed included live, msn, yahoo, aol, google and ask. The search term parameter of these engines was either named “p”, “q” or “query”.

Now, all we have to do is filter for all the requests that came from a search engine, find the search term parameter and return its value…

public string DiscoverSearchTerm(Uri url)
{
    string searchTerm = null;
    var engine = new Regex(@"(search.(live|msn|yahoo|aol).com)|(google.(com|ca|de|(co.(nz|uk))))|(ask.com)");
    if (url != null && engine.IsMatch(url.Host))
    {
        var queryString = url.Query;
        // Remove the question mark from the front and add an ampersand to the end for pattern matching.
        if (queryString.StartsWith("?")) queryString = queryString.Substring(1);
        if (!queryString.EndsWith("&")) queryString += "&";
        var queryValues = new Dictionary<string, string>();
        var r = new Regex(
        @"(?<name>[^=&]+)=(?<value>[^&]+)&",
        RegexOptions.IgnoreCase | RegexOptions.Compiled
        );
        string[] queryParams = { "q", "p", "query" };
        foreach (var match in r.Matches(queryString))
        {
            var param = ((Match)match).Result("${name}");
            if (queryParams.Contains(param))
                queryValues.Add(
                ((Match)match).Result("${name}"),
                ((Match)match).Result("${value}")
                );
        }
        if (queryValues.Count > 0)
            searchTerm = queryValues.Values.First();
    }
    return searchTerm;
}

The above code uses two regular expressions, one to filter for a search engine and the other to separate the query string. Once it’s decided that the URL is a search engine’s, it creates a collection of query string parameters that could be search parameters and returns the first one.

Unfortunately, there wasn’t enough time in the iteration for me to properly match the search engine with the correct query parameter, but as is most commonly the parameter comes into the query string quite early so it’s fairly safe to assume that the first match is correct.

Randomly Sorting a List using Extension Methods

I was trawling through some old code I had written while doing some “refactoring” and came across this little nugget. I wanted to sort a list of objects that I was retrieving from a database using LINQ to SQL into a random order. Seeing as extension methods are all the rage, I decided to use them…

public static class ListExtensions { 
  public static IEnumerable<T> Randomise<T>(this IEnumerable<T> list) { 
    Random rand = new Random();
    var result = list.OrderBy(l => rand.Next());
    return result; 
  } 
}

How does it work…? It adds the Randomise() extension method to the end of any IEnumerable<T> (e.g. List<T>) and uses the OrderBy function to change the sort order based on a randomly generated number.

var randomCategories = context.Categories.Randomise();

The above code will execute the Randomise function to reorder the list of Category objects retrieved from the context randomly and assign the result to randomCategories.