Friday, December 7, 2012

Tfs Automation - Create Builds Automatically for New Solutions

I recently wrote a tfs server plugin that creates new builds automatically whenever you add or branch a solution file.  It's fairly simple, but worth sharing.
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Client;
public class BuildCreator : ISubscriber
{
public string Name
{
get { return "Automated Build Creator"; }
}
public SubscriberPriority Priority
{
get { return SubscriberPriority.Normal; }
}
public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType, object notificationEventArgs, out int statusCode, out string statusMessage, out Microsoft.TeamFoundation.Common.ExceptionPropertyCollection properties)
{
statusCode = 0;
statusMessage = string.Empty;
properties = null;
if (notificationType == NotificationType.Notification && notificationEventArgs is Microsoft.TeamFoundation.VersionControl.Server.CheckinNotification)
{
var checkinNotification = notificationEventArgs as Microsoft.TeamFoundation.VersionControl.Server.CheckinNotification;
TeamFoundationLocationService service = requestContext.GetService<TeamFoundationLocationService>();
Uri selfReferenceUri = service.GetSelfReferenceUri(requestContext, service.GetDefaultAccessMapping(requestContext));
TfsTeamProjectCollection tfsTeamProjectCollection = new TfsTeamProjectCollection(selfReferenceUri);
var versionControl = (VersionControlServer)tfsTeamProjectCollection.GetService(typeof(VersionControlServer));
var changeSet = versionControl.GetChangeset(checkinNotification.Changeset);
foreach (var change in changeSet.Changes)
{
if ((change.ChangeType & (ChangeType.Add | ChangeType.Branch)) == 0)
continue;
if (!Path.GetExtension(change.Item.ServerItem).Equals(".sln"))
continue;
var buildDefinitionHelper = new BuildDefinitionHelper(tfsTeamProjectCollection);
buildDefinitionHelper.CreateBuildDefinition(change.Item.ServerItem);
}
}
return EventNotificationStatus.ActionPermitted;
}
public Type[] SubscribedTypes()
{
return new Type[] { typeof(Microsoft.TeamFoundation.VersionControl.Server.CheckinNotification) };
}
}
view raw BuildCreator.cs hosted with ❤ by GitHub


It takes advantage of another piece of code I had previously written (or perhaps found online, I honestly can't remember now) to create builds using the TFS api.

Installing it is very simple, just build the class into an assembly and copy it to c:\Program Files\Microsoft Team Foundation Server 11.0\Application Tier\Web Services\bin\Plugins you may also need to copy a couple of the referenced dlls to the same folder.