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;
 5:  
 6: public Identity GetUserInfo(string accountname)
 7: {
 8:  string tfsUri = "YOURTFSSERVER";
 9:  string tfsUser = "YOURTFSACCOUNT";
 10:  string tfsPassword = "YOURTFSPASSWORD";
 11:  string sid = String.Empty;
 12:  
 13:  NetworkCredential nc = new NetworkCredential(tfsUser, tfsPassword);
 14:  
 15:  TeamFoundationServer tfs = new TeamFoundationServer(tfsUri, nc);
 16:  
 17:  IGroupSecurityService gss = (IGroupSecurityService)tfs.GetService(typeof(IGroupSecurityService));
 18:  
 19:  Identity identity = gss.ReadIdentity(SearchFactor.AccountName, accountname, QueryMembership.None);
 20:  
 21:  if (identity != null)
 22:  {
 23:  return identity.sid;
 24:  }
 25:  
 26:  return null;
 27: }
 28: