Tuesday, April 30, 2013

Find out name of last checked in user programatically using TFS 2010 SDK

Below is a code snippet used in a POC related to automated code review mechanism using FxCop and TFS 2010. The details of how that code review is going to work cannot be revealed now. May be after incorporation of the same into our projects and with permission.

Basics about TFS programming using TFS 2010 SDK

If you are new to TFS and programming TFS system, please read my earlier post about the same. Only change from the earlier post is the location of TFS SDK dlls. In VS 2010 the location is changed to

[Install drive]:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0

The main thing you need to know in programming TFS is, how to create the service object, which is interacting with the different features of TFS, such as work items, source code handling, user management etc...And of course the TFS object model exposed via the sdk dlls.

Getting the details of last checked in user of TFS file / folder

Once you obtained the instance to the corresponding service its the matter of querying for the result or performing the action using suitable method. In this case the TFS Service we need to get is VersionControlServer object and the change sets can be obtained using the  QueryHistory method.

//tfsFilePath should be in the TFS format ie starting with $\<TFS project>\<folder>
        
private string GetLastCheckedInUser(string tfsFilePath)
        {
            IGroupSecurityService grpservice = GetGroupSecurityService();
            VersionControlServer vcs = GetVersionControlServer();
 
            System.Collections.IEnumerable enumerableResult = vcs.QueryHistory(
                path: tfsFilePath,
                version: VersionSpec.Latest,
                deletionId: 0,
                recursion: RecursionType.Full,
                user: "",
                versionFrom: null,
                versionTo: VersionSpec.Latest,
                maxCount: 1,
                includeChanges: true,
                slotMode: true,
                includeDownloadInfo: false,
                sortAscending: false);
            //sortAscending give the last checked in user. enumerableResult is supposed to contain only one item as the maxCount is 1
            foreach (Changeset cs in enumerableResult)
            {
                string comitter = cs.Committer;
                //eventhough cs.CommitterDisplayName property is available, sometime it may return the result as domain\\username.So convert it to displayName using group account service.
                return grpservice.ReadIdentityFromSource(SearchFactor.AccountName, cs.Committer).DisplayName;
            }
            return null;
        }

If you alter the QueryHistory method you can achieve so many things.

No comments: