Search code examples
c#tfstfs-2015

Finding user in TFS Project programmatically


We have more than one collection under one TFS server and each collection have more than one project. I want to be able to check if entered username is part of any project level group on TFS server. So far I am able to connect to TFS, and get all project names under the collection. I need help in finding the group name and then querying those groups to check if user is part of that group or not.

Here is the code I tried -

static void Main(string[] args)
    {
        NetworkCredential netCred = new NetworkCredential(@"username", @"pwd");
        TfsConfigurationServer configServ = new TfsConfigurationServer(new Uri("https://my-tfs.schwab.com/tfs"), netCred);

        var tfsAllCols = new List<KeyValuePair<Guid, string>>();
        try
        {
            configServ.Authenticate();
            Console.WriteLine("Autheticated in server with ad creds...");

            ReadOnlyCollection<CatalogNode> colNodes = configServ.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection },
                false,
                CatalogQueryOptions.None);
            foreach (CatalogNode node in colNodes)
            {
                var colId = new Guid(node.Resource.Properties["InstanceId"]);
                TfsTeamProjectCollection teamProjectCollection =
                    configServ.GetTeamProjectCollection(colId);

                tfsAllCols.Add(new KeyValuePair<Guid, string>(colId, teamProjectCollection.Name));

            }

    //hardcoding the colname for testing
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("https://ruby-tfs.schwab.com/tfs/colname/"), netCred);

            tpc.EnsureAuthenticated();

            // Get the catalog of team project collections
            ReadOnlyCollection<CatalogNode> projNodes = tpc.CatalogNode.QueryChildren(
            new[] { CatalogResourceTypes.TeamProject },
            false, CatalogQueryOptions.None);

        }
        catch (Exception ex)
        {

            throw ex;
        }

        Console.ReadLine();
    }

Solution

  • Instead of hard coding, you could use TFSSecurity command-line tool to retrieve the groups and members in team project:

    1. Use /g to list the groups in a team project, in a team project collection, or across Team Foundation Server:

    tfssecurity /g [scope] [/collection:CollectionURL] [/server:ServerURL]

    1. Use /imx to display information about the identities that compose the expanded membership of a specified group:
    > tfssecurity /imx Identity [/collection:CollectionURL][/server:ServerURL]
    

    If you insist hard coding, you could follow the blog below to query TFS for groups and memberships:

    https://blogs.msdn.microsoft.com/vasu_sankaran/2010/10/11/querying-tfs-for-groups-and-memberships/

    Update:

    enter image description here