Search code examples
c#azure-devopsazure-devops-rest-apitfs-sdk

Want to fetch feature details based on Feature title for workitem type feature in Azure DevOps using C#


I am trying to develop a console application to fetch the workitem details for workitem type Feature in Azure DevOps.

I want to fetch details like Feature id,state. the title of Feature will contain Demand number along with demand name, I will be knowing the Demand number which is in Feature Title and want fetch the feature id if exists.

I am using these Nuget package for my code:

Microsoft.TeamFoundation.WorkItemTracking.WebApi;
Microsoft.VisualStudio.Services.WebApi;

Solution

  • First, you have to connect to the service wit PAT and get the work item client:

    VssConnection connection = new VssConnection(new Uri(ServiceURL), new VssBasicCredential(string.Empty, PAT));
    WitClient = connection.GetClient<WorkItemTrackingHttpClient>();
    

    If you know a work item id, you can get a work item and find all its fields in the Fields dictionary:

    var wi = WitClient.GetWorkItemAsync(Id).Result;
    foreach (var fieldName in wi.Fields.Keys)
    Console.WriteLine(“{0,-40}: {1}”, fieldName, wi.Fields[fieldName].ToString());
    

    If you try to find a work item through the title contents, you can use the wiql query:

    string queryWiqlList = @"SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = 'TEAM_PROJECT_NAME' and [System.Title] Contains '<YOUR SEARCH_TEXT>' and [System.State] <> 'Removed' and [System.State] <> 'Closed'";
    
    Wiql wiql = new Wiql();
    wiql.Query = wiqlStr;
    WorkItemQueryResult result = WitClient.QueryByWiqlAsync(wiql).Result;
    
    if (result != null)
    {
        if (result.WorkItems != null) // this is Flat List 
            foreach (var wiRef in result.WorkItems)
            {
                var wi = WitClient.GetWorkItemAsync(wiRef.Id).Result;
                Console.WriteLine(String.Format("{0} - {1}", wi.Id, wi.Fields["System.Title"].ToString()));
            }
    }