Thursday, April 15, 2010

TFS2010: Who am I? (getting logged in user info)

When you login to TFS using object model, sometimes it may be useful to get information about logged in user (such as domain, account, email etc.).

In TFS 2008 object model, one would get the logged in user display name, domain name, account name and email as following:

    1 TeamFoundationServer server = new TeamFoundationServer("tfsserver",

    2        new System.Net.NetworkCredential("domain_name\\user_name", "pwd"));

    3 server.EnsureAuthenticated();

    4 

    5 Console.Write(server.AuthenticatedUserDisplayName);

    6 // returns user's display name

    7 

    8 Console.Write(server.AuthenticatedUserName);

    9 // returns domain_name\user_name

   10 

   11 // AuthenticatedUserIdentity is Microsoft.TeamFoundation.Server.Identity

   12 Console.Write(server.AuthenticatedUserIdentity.Domain + "\\" +

   13         server.AuthenticatedUserIdentity.AccountName);

   14 // returns domain_name\user_name  

   15        

   16 Console.Write(server.AuthenticatedUserIdentity.MailAddress); 

   17 // returns user’s email  

In TFS 2010 OM, AuthenticatedUserDisplayName, AuthenticatedUserName and AuthenticatedUserIdentity properties are all deprecated, and instead AuthorizedIdentity property is introduced on Team Project Collection class. The code below makes use of the new property to retrieve logged in user information:

    1 TfsTeamProjectCollection collection = new TfsTeamProjectCollection(

    2        new Uri(http://tfsserver:8080/tfs/defaultcollection,

    3        new System.Net.NetworkCredential("domain_name\\user_name", "pwd"));

    4 collection.EnsureAuthenticated();

    5 

    6 // AuthorizedIdentity is Microsoft.TeamFoundation.Framework.Client.TeamFoundationIdentity

    7 Console.Write(collection.AuthorizedIdentity.DisplayName);

    8 // returns user's display name

    9 

   10 Console.Write(collection.AuthorizedIdentity.GetAttribute("Domain", "default"));

   11 // returns domain_name

   12 

   13 Console.Write(collection.AuthorizedIdentity.GetAttribute("Account", "default"));

   14 // returns user_name

   15 

   16 Console.Write(collection.AuthorizedIdentity.GetAttribute("Mail", "default")); 

   17 // returns user’s email

Mirror from my MSDN blog

No comments: