通过 API 在 Team Services 中创建工作项

Create Work Item in Team Services Through API

我正在尝试为客户创建一个 Web 应用程序(托管在 Azure 上),以便能够将工作项提交到我们的团队服务页面。基本上是一个支持票页面,因此他们不必一直打电话解释他们的积压。

下面是我创建工作项的 class 和方法,遵循 Microsoft 的示例代码,出于隐私原因进行了一些明显的更改。此方法由单击按钮触发,到目前为止我无法让它创建任何工作项。

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;

 namespace customapp
 {
  public class CreateWorkItem
  {


    public void CreateWorkItemMethod()
    {

        string personalAccessToken = "xxxxxxxxx";
        string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "xxx", personalAccessToken)));

        Object[] patchDocument = new Object[1];

        patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = "Test" };


        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);


            var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");

            var method = new HttpMethod("PATCH");
            var request = new HttpRequestMessage(method, "https://example.visualstudio.com/exampleproject/_apis/wit/workitems/$Support&20Ticket?api-version=1.0") { Content = patchValue };
            var response = client.SendAsync(request).Result;


            if (response.IsSuccessStatusCode)
            {
               var result = response.Content.ReadAsStringAsync().Result;

            }

 }}}} 

在 PATCH 的 url 中,我使用团队项目的 ID(代替您在下面看到的 /exampleproject)。我们的站点设置了一个整体项目,我们称之为“"Master",里面是每个客户的团队项目,例如"ClientProject"。所以基本上我想创建一个"Support Ticket" Master->ClientProject->Backlog/Board.

中的工作项

改用 Master\areapath(不是 Master\areapath)。

样本主体:

[
  {
    "op": "add",
    "path": "/fields/System.Title",
    "value": "PBIAPI2"
  },
  {
    "op": "add",
    "path": "/fields/System.AreaPath",
    "value": "Scrum2015\SharedArea"
  }
]

另一方面,最好使用 VSTS/TFS API 和 Microsoft Team Foundation Server Extended Client package 来创建工作项。

简单示例代码:

var u = new Uri("https://[account].visualstudio.com");
            VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.VssBasicCredential(string.Empty, "[personal access token]"));
           var connection = new VssConnection(u, c);

var workitemClient = connection.GetClient<WorkItemTrackingHttpClient>();
var workitemtype = "Product Backlog Item";
            string teamProjectName = "Scrum2015";
            var document = new Microsoft.VisualStudio.Services.WebApi.Patch.Json.JsonPatchDocument();
            document.Add(
    new Microsoft.VisualStudio.Services.WebApi.Patch.Json.JsonPatchOperation()
    {
        Path = "/fields/Microsoft.VSTS.Common.Discipline",
        Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Add,
        Value = "development"
    });
            document.Add(
                new Microsoft.VisualStudio.Services.WebApi.Patch.Json.JsonPatchOperation()
                {
                    Path = "/fields/System.Title",
                    Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Add,
                    Value = string.Format("{0} {1}", "RESTAPI", 6)
                });
            document.Add(new Microsoft.VisualStudio.Services.WebApi.Patch.Json.JsonPatchOperation()
            {
                Path = "/fields/System.AreaPath",
                Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Add,
                Value =string.Format("{0}\{1}",teamProjectName, "SharedArea")
            });
            document.Add(
                new Microsoft.VisualStudio.Services.WebApi.Patch.Json.JsonPatchOperation()
                {
                    Path = "/fields/System.AssignedTo",
                    Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Add,
                    Value = "[user account]"
                });
            document.Add(
                new Microsoft.VisualStudio.Services.WebApi.Patch.Json.JsonPatchOperation()
                {
                    Path = "/fields/System.Description",
                    Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Add,
                    Value = "destest"
                });
var workitem= workitemClient.CreateWorkItemAsync(document, teamProjectName, workitemtype).Result;

方法必须是 POST 并且 URI 正确使用 Api tfs 是:

https://dev.azure.com/{organization}/{proyect}/_apis/wit/workitems/${type}?api-version=5.0

签到:

https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/create?view=azure-devops-rest-5.0

下一个代码对我有用。

 static void Main(string[] args)
    {
        CreateWorkItem();
    }


    public static void CreateWorkItem()
    {
        string _tokenAccess = "************"; //Click in security and get Token and give full access https://azure.microsoft.com/en-us/services/devops/
        string type = "Bug";
        string organization = "type your organization";
        string proyect = "type your proyect";
        string _UrlServiceCreate = $"https://dev.azure.com/{organization}/{proyect}/_apis/wit/workitems/${type}?api-version=5.0";
        dynamic WorkItem = new List<dynamic>() {
                new
                {
                    op = "add",
                    path = "/fields/System.Title",
                    value = "Sample Bug test"
                }
            };

        var WorkItemValue = new StringContent(JsonConvert.SerializeObject(WorkItem), Encoding.UTF8, "application/json-patch+json");
        var JsonResultWorkItemCreated = HttpPost(_UrlServiceCreate, _tokenAccess, WorkItemValue);
    }


    public static string HttpPost(string urlService, string token, StringContent postValue)
    {
        try
        {
            string request = string.Empty;
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", token))));
                using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage(new HttpMethod("POST"), urlService) { Content = postValue })
                {
                    var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;
                    if (httpResponseMessage.IsSuccessStatusCode)
                        request = httpResponseMessage.Content.ReadAsStringAsync().Result;
                }
            }
            return request;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }