无法使用参数变量触发vNext构建

时间:2017-11-09 19:56:18

标签: tfsbuild

如果我只指定构建定义ID,那么下面的代码可以正常工作。如果我指定参数,得到这个错误。请指教。 触发器vNext构建定义614失败! - System.Net.WebException:远程服务器返回错误:(400)错误请求。    在System.Net.HttpWebRequest.GetResponse()    在TestConsoleApp.Program.TriggerVNextBuild(String WorkItemId,String BuildDefinitionId)中的C:\ TestConsoleApp \ Program.cs:第53行

     static private void TriggerVNextBuild(string WorkItemId, string BuildDefinitionId)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://testtfs2017:8080/tfs/mycollection/myteamproject/_apis/build/builds?api-version=2.0");
            request.Credentials = CredentialCache.DefaultNetworkCredentials;
            request.Method = "Post";
            request.ContentType = "application/json";
            Stream stream = request.GetRequestStream();
            //string json = "{\"definition\":{\"id\":" + BuildDefinitionId + "}}"; WORKING

            //NOT WORKING
            string json = "{\"definition\":{\" id\": " + BuildDefinitionId + "}" + "," +
                              "\"parameters\": {\" ReleaseWorkItemID\": " + WorkItemId + "}}";

            byte[] buffer = Encoding.UTF8.GetBytes(json);
            stream.Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Console.Write(response.StatusCode);
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }
        }
        catch (Exception e)
        {
            System.IO.File.WriteAllText(@"C:\TFSLogs\vNextAutomation.txt", "Trigger vNext Build Definition " + BuildDefinitionId + " is failed! --  " + e.ToString());
        }
    }

最诚挚的问候,

1 个答案:

答案 0 :(得分:0)

我们无法指定定义中不可用或未定义的参数。

我测试过并且可以重现这个问题,这是C#中的json语法问题。

试试这个:

string json = "{\"definition\":{\"id\":" + BuildDefinitionId + "},\"parameters\":\"{\\\"system.debug\\\":\\\"true\\\"}\"}";

此外,您还可以使用PowerShell使用指定的参数触发vNext构建版本。

以下示例供您参考:

Param(
   [string]$collectionurl = "http://server:8080/tfs/DefaultCollection/",
   [string]$projectName = "ProjectName",
   [string]$keepForever = "true",
   [string]$BuildDefinitionId = "34",
   [string]$user = "username",
   [string]$token = "token"
)

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

function CreateJsonBody
{

    $value = @"
  {
  "definition": {
    "id": $BuildDefinitionId
  },

  "parameters": "{\"system.debug\":\"true\",\"BuildConfiguration\":\"debug\",\"BuildPlatform\":\"x64\"}"
}
"@

 return $value
}

$json = CreateJsonBody

$uri = "$($collectionurl)/$($projectName)/_apis/build/builds?api-version=2.0"
$result = Invoke-RestMethod -Uri $uri -Method Post -Body $json -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}