Azure DevOps Server创建工作项

Azure DevOps Server创建工作项

  1. 身份认证
    创建工作项首先我们要了解微软提供的一些身份认证方式
    https://docs.microsoft.com/zh-cn/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops-2019&tabs=preview-page
    我们采用PAT的方式进行下面的操作
    创建个人访问令牌以验证访问权限
    1.在Azure DevOps中登录到您的组织

    2.在您的主页上,打开您的配置文件,然后选择“ Azure DevOps配置文件”。
    在这里插入图片描述
    3. 在安全性下,选择个人访问令牌,然后选择+新建令牌。
    4. 为令牌命名,选择要使用令牌的组织,然后为令牌选择有效期。在这里插入图片描述
    5. 选择 此令牌的范围以授权执行您的特定任务。
    6. 完成后,请确保复制令牌。您将使用此令牌作为密码。(记得一定要复制不然你只能重新创建了

  2. 编写创建工作项代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.TeamFoundation.WorkItemTracking.WebApi;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi.Patch.Json;
using Microsoft.VisualStudio.Services.WebApi.Patch;
using Microsoft.VisualStudio.Services.WebApi;
using System.Net.Http.Headers;
using System.Net.Http;
using Newtonsoft.Json;
using ConsoleApp3;
using Newtonsoft.Json.Linq;

public class CreateBug
{
    readonly string _uri;
    readonly string _personalAccessToken;
    readonly string _project;

    /// <summary>
    /// Constructor. Manually set values to match your organization. 
    /// </summary>
    public CreateBug()
    {
        JObject json=ConfigFile.GetJson();
        
        _uri = json["_uri"].ToString();
        _personalAccessToken = json["_personalAccessToken"].ToString();
        _project = json["_project"].ToString();
    }

    /// <summary>
    /// Create a bug using the .NET client library
    /// </summary>
    /// <returns>Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItem</returns>    
    public WorkItem CreateBugUsingClientLib(string file,string content)
    {
        Uri uri = new Uri(_uri);
        string personalAccessToken = _personalAccessToken;
        string project = _project;

        var credentials = new ConsoleApp3.PatCredentials("", _personalAccessToken);
        JsonPatchDocument patchDocument = new JsonPatchDocument();

        // 文件名
        patchDocument.Add(
            new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path = "/fields/System.Title",
                Value = file,
            }
        );

        // 描述信息-bug中可以不用添加该字段
        patchDocument.Add(
             new JsonPatchOperation()
             {
                 Operation = Operation.Add,
                 Path = "/fields/System.Description",
                 Value = "asdasdsadassdadad"
             }
        );

        // 重现步骤
        patchDocument.Add(
            new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path = "/fields/Microsoft.VSTS.TCM.ReproSteps",
                Value = content,
            }
        );

        // 系统信息
        patchDocument.Add(
            new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path = "/fields/Microsoft.VSTS.TCM.SystemInfo",
                Value = "Our authorization logic needs to allow for users with Microsoft accounts (formerly Live Ids) - http:// msdn.microsoft.com/library/live/hh826547.aspx"
            }
        );

        // 优先级
        patchDocument.Add(
            new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path = "/fields/Microsoft.VSTS.Common.Priority",
                Value = "1"
            }
        );

        // 指派人
        patchDocument.Add(
            new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path = "/fields/System.AssignedTo",
                Value = "xxx"
            }
        );

        //严重级别
        patchDocument.Add(
            new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path = "/fields/Microsoft.VSTS.Common.Severity",
                Value = "2 - 高"
            }
        );

        VssConnection connection = new VssConnection(uri, credentials);
        WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient<WorkItemTrackingHttpClient>();

        try
        {
            WorkItem result = workItemTrackingHttpClient.CreateWorkItemAsync(patchDocument, project, "Bug").Result;

            Console.WriteLine("Bug Successfully Created: Bug #{0}", result.Id);

            return result;
        }
        catch (AggregateException ex)
        {
            Console.WriteLine("Error creating bug: {0}", ex.InnerException.Message);
            return null;
        }
    }
}

上面的几个参数是我从配置文件中读出来的 大家可以自行发挥。其中CreateWorkItemAsync中参数Bug为工作项中的缺陷,其他的大家可以自己去查询一下
如果是部署到云服务端的这样的可以创建好工作项了
本地服务器Http请求失败解决方案
如果部署到本地服务器并且地址为http(部署到本地的大部分都没有加证书)我们会发现在创建的时候会提示安全认证的错误,因为CreateWorkItemAsync方法需要支持https的安全认证,这里给大家提一下思路正常我们遇到发送http请求的时候如果出现安全认证的错误一般都会去想如何绕过安全认证,同样的这里也可以。

using Microsoft.VisualStudio.Services.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp3
{
    internal sealed class PatCredentials : FederatedCredential
    {
        public PatCredentials()
             : this((VssBasicToken)null)
        {
        }

        public PatCredentials(string userName, string password)
            : this(new VssBasicToken(new NetworkCredential(userName, password)))
        {
        }

        public PatCredentials(ICredentials initialToken)
           : this(new VssBasicToken(initialToken))
        {
        }

        public PatCredentials(VssBasicToken initialToken)
            : base(initialToken)
        {
        }

        public override VssCredentialsType CredentialType => VssCredentialsType.Basic;

        public override bool IsAuthenticationChallenge(IHttpResponse webResponse)
        {
            if (webResponse == null ||
                webResponse.StatusCode != HttpStatusCode.Found &&
                webResponse.StatusCode != HttpStatusCode.Found &&
                webResponse.StatusCode != HttpStatusCode.Unauthorized)
            {
                return false;
            }

            return webResponse.Headers.GetValues("WWW-Authenticate").Any(x => x.StartsWith("Basic", StringComparison.OrdinalIgnoreCase));
        }

        protected override IssuedTokenProvider OnCreateTokenProvider(Uri serverUrl, IHttpResponse response)
        {
            return new BasicAuthTokenProvider(this, serverUrl);
        }

        private sealed class BasicAuthTokenProvider : IssuedTokenProvider
        {
            public BasicAuthTokenProvider(IssuedTokenCredential credential, Uri serverUrl)
                : base(credential, serverUrl, serverUrl)
            {
            }
            protected override string AuthenticationScheme => "Basic";
            public override bool GetTokenIsInteractive => this.CurrentToken == null;

        }
    }
}

这样不管是本地部署还是云端部署都可以成功的创建工作项了 。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值