VSTS Create New WorkItem

I am using the VSTS REST API and I am trying to create a new WorkItem. But I can get the existing WorkItem from VSTS and update the WorkItem.

        var listDoNotUpdate = new List<string>();
        listDoNotUpdate.Add("System.BoardColumn");
        listDoNotUpdate.Add("System.BoardColumnDone");
        var wi = await this.Client.GetWorkItemAsync(4000);
        wi.Fields["System.Title"] = "Test";
        wi.Fields["System.Description"] = "Test";
        wi.Fields["Microsoft.VSTS.Common.AcceptanceCriteria"] = "Test";
        var doc = new JsonPatchDocument();
        foreach (var field in wi.Fields)
        {
            if (!listDoNotUpdate.Contains(field.Key))
            {
                doc.Add(new JsonPatchOperation
                {
                    Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Replace,
                    Path = string.Concat("/fields/", field.Key),
                    Value = field.Value
                });
            }
        }

        await this.Client.UpdateWorkItemAsync(doc, 4000);

But how can I create a new WorkItem and load it?

+4
source share
3 answers

They seem to have forgotten the CreateWorkItemAsync method. All other update methods have a corresponding Create method. To create a work item, you can use the following snippet

var client = new RestClient(string.Format(
    CultureInfo.InvariantCulture,
    "https://{0}.visualstudio.com/defaultcollection/{1}/_apis/",
    "<vstsAccount>",
    "<project>"));
client.Authenticator = new HttpBasicAuthenticator("accessToken", "<accessToken>");
var json = @"[{'op': 'add','path': '/fields/System.Title','value': 'Title of your work item'}]";
var request = new RestRequest("wit/workitems/$Product Backlog Item?api-version=1.0", Method.PATCH);
request.AddParameter("application/json-patch+json", json, ParameterType.RequestBody);
request.AddHeader("Accept", "application/json");
var response = client.Execute(request);

The response will contain json of the new work item. Use it to retrieve the id of the new item.

+2
source

You're close Instead of calling UpdateWorkItemAsync, you need to call UpdateWorkItemTemplateAsync.

var collectionUri = "https://{account}.visualstudio.com";
var teamProjectName = "{project}";
var workItemType = "{workItemType}";
var client = new WorkItemTrackingHttpClient(new Uri(collectionUri), new VssClientCredentials());

var document = new JsonPatchDocument();
document.Add(
    new JsonPatchOperation()
    {
        Path = "/fields/System.Title",
        Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Add,
        Value = "Title"
    });

var wi = client.UpdateWorkItemTemplateAsync(
    document,
    teamProjectName,
    workItemType).Result;
+4
source

Source: https://habr.com/ru/post/1624421/


All Articles