Paul Hacker's Blog

Musings from a "Hacker"
posts - 21, comments - 65, trackbacks - 22

My Links

News



Archives

Friday, August 04, 2006

Access Stored Queries in Team Foundation Server

Have you ever had a need to take advantage of the StoredQueriesCollection in TFS? I was recentlly working on a project where I wanted to access a WorkItem query that I had created in my TFS project rather than create a SQL query string. To accomplish this I needed to access the StoredQueriesCollection for the TFS project that I was working with. Here is a snippet of code that will get the job done.

//connect to TFS

TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(ConfigurationManager.AppSettings["TFS_SERVER"],new UICredentialsProvider());
            tfs.EnsureAuthenticated();

//get the current user that is logged in
            tfsuser = tfs.AuthenticatedUserName;

            WorkItemStore store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));

//Get my project
                Project tfsProject = store.Projects [ConfigurationManager.AppSettings["TFS_PROJECT"]];

//Get the Stored Queries

                StoredQueryCollection sqc = tfsProject.StoredQueries;

                string querystring;

                foreach (StoredQuery query in sqc)
                {
                    if (query.Name == "All My Open Tasks")
                    {

//Get the query text that I will need to run
             

 querystring = query.QueryText;

//replace the @project variable inthe query with the name of my project

                        querystring = querystring.Replace("@project", "'" + tfsProject.Name + "'");

                        WorkItemCollection wic = store.Query(querystring);

//loop through the WorkItems that the query returns

                        foreach (WorkItem wi in wic)
                        {

//Loop through the fields and getthe data that I need

                            foreach (Field field in wi.Fields)
                            {
                                string Title = field.Value.ToString();

                                string startDate = (DateTime)field.Value;
                                string finishDate = (DateTime)field.Value;

                            }

                        }
                    }
                }

I could have very easily wrote a SQL query string, but I wanted to show how you take advantage of the StoredQueriesCollection. Hope you find this useful.

 

-pjhacker

posted @ Friday, August 04, 2006 8:31 AM | Feedback (3) |

Powered by: