Greaka
Greaka

Reputation: 755

attach workitem to build via REST API

I want to attach a work item on tfs to a build. i am reading SVN logs which contain the work item number and try to update the actual build to attach them.

workitems.Add(workItemStore.GetWorkItem(workitemid));
buildDetail.Information.AddAssociatedWorkItems(workitems.ToArray());

When I try to hit buildDetail.Information.Save(); or buildDetail.Save();, I get an AccessDeniedException.

See another post.

So I wanted to try with REST... After loads of pages on MSDN, I concluded there is no .NET Client Library that takes care of builds. It looks like my only option is to patch a json into the TFS:

PATCH https://{instance}/DefaultCollection/{project}/_apis/build/builds/{buildId}?api-version={version}

How do I add the workitems the right way?

EDIT: I've found an old post which mentioned a dll in the TFS namespace which has the same capabilities like the call from above. Unluckily, it's not refered in MSDN. Same problem here: no way to add workitems.

To spread the issue and adress it to MS: Patrick has created a post on uservoice

UPDATE:

I managed to link a build in the work item. Here is an approach in :

var json = new JsonPatchDocument
            {
                new JsonPatchOperation()
                {
                    Operation = Operation.Add,
                    Path = "/relations/-",
                    Value = new WorkItemRelation()
                            {
                                Rel = "ArtifactLink",
                                Url = build.Uri.ToString()
                            }
                }
            };

var client = new WebClient { UseDefaultCredentials = true };
client.Headers.Add(HttpRequestHeader.ContentType, "application/json-patch+json");
client.UploadData(
    options.CollectionUri + "/_apis/wit/workitems/" + workitemid + "?api-version=1.0",
    "PATCH",
    Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(json)));

But there is still no direct binding in the build: build

And the work items says unknown executable linktype work item

According to the message given in the workitem, I assume that I am using the false linktype. Does anybody have a reference for me, what types I am able to and should use?

URI UPDATE: I am already using the mentioned uri: json

MINOR SOLUTION:

I had to add the name "Build" to the Attributes of the patch. I still does not recognize it in the build itself but for now, I can work with the link as build type.

var json = new JsonPatchDocument
            {
                new JsonPatchOperation()
                {
                    Operation = Operation.Add,
                    Path = "/relations/-",
                    Value = new WorkItemRelation()
                            {
                                Rel = "ArtifactLink",
                                Url = build.Uri.ToString()
                                Attributes = new Dictionary<string, object>()
                                {
                                    { "name", "Build" },
                                    { "comment", build.Result.ToString() }
                                }
                            }
                }
            };

Upvotes: 2

Views: 1757

Answers (2)

Eddie Chen - MSFT
Eddie Chen - MSFT

Reputation: 29966

You could add a workitem to a build by updating the workitem to add a relation link to the build via Rest API. Refer to this link for details: Add a Link.

After you add a link to the build in the workitem, the workitem would be show in the build summary.

Following is the content sample of the body,

[
    {
        "op": "test",
        "path": "/rev",
        "value": "2"
    },
    {
        "op": "add",
        "path": "/relations/-",
        "value":
        {
            "rel": "ArtifactLink",
            "url": "vstfs:///Build/Build/12351"
        }
    }
]

Add code sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;

namespace AssociateWorkItemToBuild
{
    class Program
    {
        static void Main(string[] args)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
                     ASCIIEncoding.ASCII.GetBytes(
                        string.Format("{0}:{1}", "username", "password"))));

                string Url = "https://xxxxxx.visualstudio.com/_apis/wit/workitems/149?api-version=1.0";
                StringBuilder body = new StringBuilder();
                body.Append("[");
                body.Append("{");
                body.Append("\"op\":\"add\",");
                body.Append(" \"path\":\"/relations/-\",");
                body.Append("\"value\":");
                body.Append("{");
                body.Append("\"rel\": \"ArtifactLink\",");
                body.Append("\"url\": \"vstfs:///Build/Build/12596\"");
                body.Append("}");
                body.Append("}");
                body.Append("]");

                var method = new HttpMethod("PATCH");
                var request = new HttpRequestMessage(method, Url)
                {
                    Content = new StringContent(body.ToString(), Encoding.UTF8,
                                    "application/json-patch+json")
                };

                using (HttpResponseMessage response = client.SendAsync(request).Result)
                {
                    response.EnsureSuccessStatusCode();
                    string responseBody = response.Content.ReadAsStringAsync().Result;
                }
            }
        }
    }
}

Upvotes: 1

PatrickLu-MSFT
PatrickLu-MSFT

Reputation: 51093

Update

Just as Eddie replied, you could add a workitem to a build by updating the workitem to add a relation link to the build via Rest API.

About LinkType there has been a clear demo in Eddie's answer. You need to use build uri.

The format needs to be vstfs:///Build/Build/8320

The BuildUri for the TFS Build tasks is a property that needs to be set so that those tasks can communicate with the server about the build they are performing actions for.


You can also use $env:BUILD_BUILDURI in a powershell script, more detail info and ways you can also refer this blog from MSDN: Build association with work Items in vNext Finally will get :

enter image description here

Upvotes: 1

Related Questions