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

时间:2017-06-23 01:41:58

标签: c# visual-studio azure azure-devops azure-devops-rest-api

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

以下是我根据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的网址中,我正在使用团队项目的ID(代替/ exampleproject,见下文)。我们的网站设置为有一个整体项目,我们称之为“”Master“,内部是每个客户的团队项目,例如”ClientProject“。所以基本上我想在Master中创建一个”支持票“工作项 - > ClientProject->积压/板

2 个答案:

答案 0 :(得分:2)

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

样本正文:

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

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

简单示例代码:

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;

答案 1 :(得分:1)

该方法必须为 POST ,并且能够正确使用Api tfs的Uri是:

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);
        }
    }