Reputation: 640
I want to programmatically retrieve information of all pull requests associated to a work item in Azure DevOps using Azure DevOps WebAPI. I have figured out how to retrieve an instance of
Microsoft.TeamFoundation.WorkItemTracking.WebApi.Model.WorkItem
For my work item.
To find the pull requests related to it, I can iterate through the Relations field and find a relation where Url contains PullRequestId
. At the end of that string, I can locate the Pull Request id to be used with the GetPullRequestAsync
.
The URL might look like this:
vstfs:///Git/PullRequestId/2139bb34-57e3-4d7d-a6e1-1c0542a45e29%2F8a2b707f-ca7a-418d-8462-2bf076a54aad%2F39723
So my code would look like this:
foreach ( WorkItemRelation wir in wi.Relations)
{
if ( wir.Url.Contains("PullRequestId"))
{
var pr = build.GetPullRequestAsync("<MyProject>", "Providername", "39723", "repository id").Result;
// Do somethin with pr object
}
}
My issues with this are the following
GetPullRequestAsync
requires a provider name and repository id.
But should that information not be retrievable from the instance of
Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItemRelation
.Upvotes: 4
Views: 2868
Reputation: 40603
Instead of relying on PullRequestId
I would recommend you use attributes. In URL you will find all what you need:
var credential = new VssBasicCredential(string.Empty, "PAT");
var connection = new VssConnection(new Uri("https://dev.azure.com/thecodemanual/"), credential);
var witClient = connection.GetClient<WorkItemTrackingHttpClient>();
var build = connection.GetClient<BuildHttpClient>();
var repoClient = connection.GetClient<GitHttpClient>();
var workItem = witClient.GetWorkItemAsync(1, expand: Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItemExpand.Relations).Result;
foreach (var relation in workItem.Relations)
{
if((string)relation.Attributes["name"] == "Pull Request")
{
Console.WriteLine(relation.Url);
var segment = relation.Url.Split("/").Last();
var ids = segment.Split("%2F");
var repo = repoClient.GetRepositoryAsync(ids[1]).Result;
Console.WriteLine(repo.Name);
var pr = build.GetPullRequestAsync(ids[0], "TfsGit", ids[2], ids[1]).Result;
Console.WriteLine(pr.Title);
// Do somethin with pr object
}
}
Upvotes: 5
Reputation: 19391
As far as I know, there is no other better way to achieve this. The currently known method is to retrieve the pull request id from the url.
From the response you can retrieve the relations with the "name": "Pull Request"
. Then you can split the url string with %2F
, the pull request id is the last part.
Regarding the second issue, you can use this Get Pull Request By Id rest api to get the pull request detailed information. Just need to provide pull request id in the request.
GET https://dev.azure.com/{organization}/{project}/_apis/git/pullrequests/{pullRequestId}?api-version=5.1
Upvotes: 0