TFS API – How to retrieve a User’s SID based on their Account Name

This post goes along with my prior post on working with Fact tables in a TFS Warehouse Adapter.  I specified that you can pass the User’s SID as the value of the Person Dimension on a FactEntry.  You normally don’t have this data readily available but the user’s account name (DomainUserName) usually is.

To retrieve the SID based on the account name, follow the steps outlined in this blog post from Peter Blomqvist.  He goes into detail about how this works and other uses for this code and I recommend reading his article thoroughly. 

I’ve stolen his code and modified it specifically for returning the SID so that I can grab it in the future from here.

 1: using System;
 2: using System.Net;
 3: using Microsoft.TeamFoundation.Client;
 4: using Microsoft.TeamFoundation.Server;
 6: public Identity GetUserInfo(string accountname)
 7: {
 8:  string tfsUri = "YOURTFSSERVER";
 9:  string tfsUser = "YOURTFSACCOUNT";
 10:  string tfsPassword = "YOURTFSPASSWORD";
 11:  string sid = String.Empty;
 13:  NetworkCredential nc = new NetworkCredential(tfsUser, tfsPassword);
 15:  TeamFoundationServer tfs = new TeamFoundationServer(tfsUri, nc);
 17:  IGroupSecurityService gss = (IGroupSecurityService)tfs.GetService(typeof(IGroupSecurityService));
 19:  Identity identity = gss.ReadIdentity(SearchFactor.AccountName, accountname, QueryMembership.None);
 21:  if (identity != null)
 22:  {
 23:  return identity.sid;
 24:  }
 26:  return null;
 27: }