TFS AutoShelve: a utility to automatically shelve check outs to the TFS server

Have you ever worked on a team where a developer went on vacation without checking in an important change?  Ever known someone that kept a file checked out over multiple days (or weeks) and lost their work because of hard drive (or other) failure?  Having seen the effect of such mishaps, I decided to implement a simple utility that will automatically shelve each developer's check outs to the Team Foundation Server.

If you are not familiar with shelving, it's a feature in TFS that will store pending changes on the server without checking them in.  Shelving is very useful in many scenerios, but it is especially useful to me for prevention and insurance.

The utility is a dead simple console application that is configured to run as a log off script on each developer's computer.  You could also configure it as a scheduled task.  It connects to the TFS server, determines what the user has checked out on that computer and shelves the changes on the server.  The full utility is available on CodePlex here, but I thought some of you might find it useful to see the essential shelving code.

        string tfsServer = "";        string shelfSetName = "AutoShelve";        // Connect to the Team Foundation Server        TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(tfsServer);        // Get the Version Control Server        VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));        // Get the list of workspaces for the current user        Workspace[] workspaces = vcs.QueryWorkspaces(            null,            tfs.AuthenticatedUserName,            null);        // Enumerate each workspace and         // determine if there are any pending changes        foreach (Workspace ws in workspaces)        {            // You can only shelve what is on this computer!            if (System.Environment.MachineName.ToUpper(CultureInfo.InvariantCulture) != ws.Computer.ToUpper(CultureInfo.InvariantCulture))            {                // Continue to next workspace                continue;            }            // Get the changes in this workspace            PendingChange[] changes = ws.GetPendingChanges();            // If there are any pending changes,            // shelve them            if (changes.Length > 0)            {                // Create a shelveset                Shelveset set = new Shelveset(                    vcs,                    shelfSetName,                    tfs.AuthenticatedUserName);                // Shelve the changes                ws.Shelve(                    set,                    changes,                    ShelvingOptions.Replace);            }        }

TFS AutoShelve is a very simple utlity that is quite powerful in practice--especially the first time it saves your backside.