Geeks With Blogs

News




View Tarun Arora's profile on LinkedIn

profile for Tarun Arora at Stack Overflow, Q&A for professional and enthusiast programmers

Tarun Arora - Visual Studio ALM MVP ALM, Agile, Automation, Performance Testing, Software QA, Cloud, ...

 

Download a working solution

Demo Solution Download

I have seen a lot of questions in the community lately on how to use the TFS API to get a list of Team Projects, Iterations & Area Paths in that project, get a list of queries, see the wiql and execute the query programmatically. I will show you the steps on just how to do this. PDTZG6PKJYNE

image

1. Connect to TFS Programmatically

I have a blog post that shows you from where to download the VS 2010 SP1 SDK and how to connect to TFS programmatically.

        public static TfsTeamProjectCollection ConnectToTfsProgrammatically()
        {
            return TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("TfsUrl"));
        }
 

2. Get All Team Projects

I will use the ‘WorkItemStore’ service to retrieve the team projects

        // Get All Team Projects
        public static ProjectCollection GetAllTeamProjects()
        {
            var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("TfsUrl"));
            var wiStore = tfs.GetService<WorkItemStore>();

            return wiStore.Projects;
        }
 

Now that you have the ProjectCollection available, you can loop through and get details of all projects in that collection.

        foreach (Project project in projCollections)
        {
            lstTeamProjects.Items.Add(project.Name);
        }
 

If you were just interested in one project and wanted to get details of only that one project you could use the ‘TryGetTeamProject(string)’ method, this is available with in the ‘VersionControlServer’ service

        // Get project by name 
        public static TeamProject GetProjectDetailsByName(string projectName)
        {
            var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("TfsUrl"));
            var vsStore = tfs.GetService<VersionControlServer>();

            return vsStore.TryGetTeamProject(projectName);
        }

 

3. Get All Iterations in the Team Project

Now that we have the Project object available, it is very easy to get all the iterations in that project. You need to be careful though, the iterations could have child nodes. The code snippet below lets you get the iterations and sub iterations (child nodes). 

 

        // Iterations
        foreach (Node node in project.IterationRootNodes)
        {
             lstIterations.Items.Add(node.Name);
             foreach (Node item in node.ChildNodes)
             {
                 lstIterations.Items.Add(item.Name);
             }
         }

4. Get All Area Paths in the Team Project

It is very simple to get all area paths in the project. You need to be careful though, the area paths could have child nodes. The code snippet below lets you get the area paths and sub area paths (child nodes).

 

       // Area Path
       foreach (Node area in project.AreaRootNodes)
       {
              lstAreaPath.Items.Add(area.Name);

              foreach (Node item in area.ChildNodes)
              {
                  lstAreaPath.Items.Add(item.Name);
              }
        }

5. Get All Queries in the Team Project

It is very simple to get all queries in the project.

 

       // Queries
       foreach (StoredQuery qi in detailsOfTheSelectedProject.StoredQueries)
       {                    
            lstQueries.Items.Add(qi.Name);
       }
 
 

You could also get the Query Text, Query Scope, Query Guid from here.

       // Queries
       foreach (StoredQuery qi in project.StoredQueries)
       {                    
            Debug.Write(String.Format("Query Text: {0}{1}", qi.QueryText, Environment.NewLine));
            Debug.Write(String.Format("Query Scope: {0}{1}", qi.QueryScope, Environment.NewLine));
            Debug.Write(String.Format("Query Guid: {0}{1}", qi.QueryGuid, Environment.NewLine));
       }
 
 

Or if you knew the GUID of the query, you could use the GUID to get the query

       var query = project.Store.GetQueryDefinition(new Guid("ed359a39-9aa2-4185-9121-da0a407f22e5"));
 
 

If you wanted to see the Access Control List associated to the query

       var queryACL = detailsOfTheSelectedProject.Store.GetQueryDefinition(new Guid("ed359a39-9aa2-4185-9121-da0a407f22e5")).AccessControlList;
 
 

image

Just before moving a head, if you wanted to see if the query ‘Is Personal’ or team query. The property ‘IsPersonal’ would reveal this,

     var queryIsPersonal = detailsOfTheSelectedProject.Store.GetQueryDefinition(new Guid("ed359a39-9aa2-4185-9121-da0a407f22e5")).IsPersonal;

 

 

6. Get the WIQL of the query

The queries use the ‘Work Item Query Language’ you can read more about the WIQL on msdn library. If you wanted to see the query text then there are two ways of doing this,

1. Using the TFS API

      // Query Text
      foreach (StoredQuery qi in project.StoredQueries)
      {
           lstQueries.Items.Add(qi.QueryText);
      }

2. Without the TFS API

  • Create a new query in TFS and click on save

image

  • Save it on the location filesystem rather than on the server

image

  • Change the extension from *.wiq to *.txt

image

 

7. Execute the TFS Query Programmatically

Now that we have the query text we will convert it in to TFS query object,

      // Convert any parameters before converting the string to Query object, other wise will raise exception
     
tbQueryDetails.Text = project.Store.
                               GetQueryDefinition(qi.QueryGuid).QueryText.Replace("@project", String.Format("'{0}'", detailsOfTheSelectedProject.Name));

      var query = new Query(wiStore, tbQueryDetails.Text);


 

Note that the query can either be a flat query or a linked query. if you try and execute a linked query using a flat query execution method you will get the following exception,

TF248021: You have specified a query string that is not valid when you use the query method for a flat list of work items. You cannot specify a parameterized query or a query string for linked work items with the query method you specified.

So, best to check the property ‘IsLinkedQuery’ and verify what type of query it is. The linked query will need to be executed using the ‘query.RunLinkedQuery’ method.

 if (query.IsLinkQuery)
 {
       var queryResults = query.RunLinkQuery();

       foreach (WorkItemLinkInfo item in queryResults)
       {
            lstWorkItems.Items.Add(detailsOfTheSelectedProject.Store.GetWorkItem(item.TargetId).Id);
       }
  }
  else
  {
       var queryResults = query.RunQuery();

       foreach (WorkItem item in queryResults)
       {
            lstWorkItems.Items.Add(item.Id);
       }
   }
 
 

Questions, Suggestions, Feedback, feel free to reply to the post.

Share this post :
Digg This
Posted on Sunday, July 10, 2011 7:23 PM TFS2010 , TFS API | Back to top


Comments on this post: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Great post! Tons of great information, and will definitely make my life much easier by being able to automate some of the things we currently do manually in TFS. Thanks!
Left by deadlydog on Aug 17, 2011 7:37 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Interessant Post !

how can i add area with code? which Tfs Service will be used?

thanks
Left by Micgi on Aug 20, 2011 7:33 AM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Hi Micgi, Thanks for your comment.
To perform operations on the area path you need to use the ICommonStructureService service. You can have a look at this msdn link that shows you the methods and properties available to you with this service http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.server.icommonstructureservice(v=VS.100).aspx. To add the node you will use the CreateNode method, read more about it here => http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.server.icommonstructureservice.createnode.aspx. HTH Cheers, Tarun
Left by Tarun Arora on Aug 20, 2011 9:03 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Check out this link on how to add area path and iteration programmatically, a demo also available for download http://blogs.microsoft.co.il/blogs/shair/archive/2009/01/30/tfs-api-part-10-add-area-iteration-programmatically.aspx.
Cheers, Tarun
Left by Tarun Arora on Aug 20, 2011 9:07 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
foreach (WorkItemLinkInfo item in queryResults)
{
lstWorkItems.Items.Add(detailsOfTheSelectedProject.Store.GetWorkItem(item.TargetId).Id);
}

On the code above (which I took from your post), what is the type of lstWorkItems...
Left by Muse on Sep 03, 2011 9:50 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Hi Muse,

Thanks for your question. lstWorkItems is a Windows Forms ListView Control. More details about the control on the msdn link => http://msdn.microsoft.com/en-us/library/system.windows.forms.listview(v=VS.100).aspx. It belongs to the namespece System.Windows.Forms and the type is ListView Class.

HTH
Cheers, Tarun
Left by Tarun Arora on Sep 04, 2011 10:24 AM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Hi Muse,

On a second note, if you just wanted to see the output while you play with the code, you can replace the "lstWorkItems.Items.Add()" with "Debug.Write()" and add a reference to => System.Diagnostics. This will print the results to the Output windows when you run the program in debug mode. When you become confident with the results you can replace the results written to output with a control.

HTH
Cheers, Tarun
Left by Tarun Arora on Sep 04, 2011 10:27 AM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Hi Tarun,

Great post - this will get me started pulling what I need from the API.
Cheers, Atif
Left by Atif Rehman on Oct 24, 2011 4:59 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Hi Atif,

Thanks for your kind note, i am glad that experts like your self are visiting my blog. Thanks a lot.

Cheers, Tarun
Left by Tarun Arora on Oct 24, 2011 5:59 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Can you point in the right direction for VB.net code examples, especially on how to get the latest files from server to local.

Regards
Left by Andrew on Nov 07, 2011 3:18 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Hi Andrew,

The TFS API is available in VB.NET as well. Please refer to the following URL on MSDN that shows you VB.NET code sample for connecting to TFS, similarly most of the other headers and samples under the section extending TFS 2010 will have 2 tabs, code sample in C#, VB.NET. http://msdn.microsoft.com/en-us/library/bb286958.aspx#Y1200.
In case you have any follow up questions please feel free to add to the thread.

Cheers, Tarun
Left by Andrew on Nov 07, 2011 3:22 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Hi Tarun,
I wanted to know if there is any way by which one could download latest code from a project in TFS to any local folder (not necessarily the mapped one).

Thanks,
Gaurav.
Left by Gaurav on Feb 10, 2012 3:33 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Hi Tarun,
I am getting argumentexception
tbQueryDetails.Text = detailsOfTheSelectedProject.Store.
GetQueryDefinition(qi.QueryGuid).QueryText.Replace("@project", String.Format("'{0}'", detailsOfTheSelectedProject.Name));

Please help me out.
Left by ritesh on Aug 01, 2012 1:16 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
Hi,

We are trying to pull information related to the below fields in WorkIteam object:
Priority
Severity
Could not find this info directly under WorkIteam object. Our Query has these fields.
How do we pull this information?


Left by Hari on Aug 03, 2012 9:31 AM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
@Hari -

wi["Priority"] and wi["Severity"] is what you should be doing to get this information.

Any other fields that you do not see by wi. can be looked up in the tfs WI fields table in the database and then use the convention wi["fieldName"] to get its value.

HTH
Cheers, Tarun
Left by Tarun Arora on Aug 20, 2012 12:26 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
@Raj - Regarding your comment
Argument null exception when running "tbQueryDetails.Text = detailsOfTheSelectedProject.Store.
GetQueryDefinition(qi.QueryGuid).QueryText.Replace("@project", String.Format("'{0}'", detailsOfTheSelectedProject.Name));"

Can you please tell me the value of qi.QueryGuid. Can you make sure you have a {0} in your qi.QueryGuid.
Left by Tarun Arora on Aug 20, 2012 12:29 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
This is very useful Tarun. Thanks for posting.
Left by Antony on Nov 11, 2012 10:06 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
How would I use credentials with this app? The sample on your previous post uses TfsConfigurationServerFactory, but this app does not?
Left by Carl on Nov 12, 2012 2:31 PM

# re: TFS 2010 SDK: Get Projects, Iterations, Area Path, Queries and Work Items Programmatically
Requesting Gravatar...
What is "detailsOfTheSelectedProject"
Left by Aviral on Nov 16, 2012 5:05 AM

comments powered by Disqus

Copyright © Tarun Arora [Microsoft MVP] | Powered by: GeeksWithBlogs.net | Join free