Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added example to set task variable. #580

Merged
merged 2 commits into from
Jan 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions ServerTaskHelper/AzureFunctionSample/MyTaskExecutionHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Newtonsoft.Json;
using AzureFunctionSample;
using System.Linq;

namespace MyAzureFunctionSampleFunctionHandler
{
Expand Down Expand Up @@ -43,6 +44,20 @@ public async Task<TaskResult> ExecuteAsync(TaskMessage taskMessage, TaskLogger t
{
// Creates the container in Azure
await MyApp.CreateContainer(taskLogger, myAppParameters);

using (var taskClient = new TaskClient(taskMessage.GetTaskProperties()))
{
// set variable
var variableName = "ContainerName";
await taskClient.SetTaskVariable(taskId: taskMessage.GetTaskProperties().TaskInstanceId, name: variableName, value: "AzPipelineAgent", isSecret: false, cancellationToken: cancellationToken);

// get variable
var variableValue = taskClient.GetTaskVariable(taskId: taskMessage.GetTaskProperties().TaskInstanceId, name: variableName, cancellationToken: cancellationToken);
message = $"Variable name: {variableName} value: {variableValue}";
await taskLogger.Log(message).ConfigureAwait(false);
}


return await Task.FromResult(TaskResult.Succeeded);
}
catch (Exception ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,30 @@ public async Task AppendTimelineRecordFeedAsync(IEnumerable<string> lines)
await taskClient.AppendTimelineRecordFeedAsync(this.taskProperties.ProjectId, this.taskProperties.HubName, this.taskProperties.PlanId, this.taskProperties.TimelineId, this.taskProperties.JobId, lines).ConfigureAwait(false);
}

public async Task SetTaskVariable(Guid taskId, string name, string value, bool isSecret, CancellationToken cancellationToken)
{
var records = await taskClient.GetRecordsAsync(this.taskProperties.ProjectId, this.taskProperties.HubName, this.taskProperties.PlanId, this.taskProperties.TimelineId, userState: null, cancellationToken: cancellationToken).ConfigureAwait(false);
var taskRecord = records.FirstOrDefault(r => r.Id == taskId);
taskRecord.Variables[name] = new VariableValue { Value = value, IsSecret = isSecret };

await taskClient.UpdateTimelineRecordsAsync(this.taskProperties.ProjectId, this.taskProperties.HubName, this.taskProperties.PlanId, this.taskProperties.TimelineId, new List<TimelineRecord> { taskRecord }, cancellationToken).ConfigureAwait(false);
}

public string GetTaskVariable(Guid taskId, string name, CancellationToken cancellationToken)
{
var records = taskClient.GetRecordsAsync(this.taskProperties.ProjectId, this.taskProperties.HubName, this.taskProperties.PlanId, this.taskProperties.TimelineId, userState: null, cancellationToken: cancellationToken).Result;
var taskRecord = records.FirstOrDefault(r => r.Id == taskId);
foreach(var varaible in taskRecord.Variables)
{
if (string.Equals(varaible.Key, name, StringComparison.OrdinalIgnoreCase))
{
return varaible.Value.Value;
}
}

return null;
}

public void Dispose()
{
vssConnection?.Dispose();
Expand Down
54 changes: 52 additions & 2 deletions ServerTaskHelper/HttpRequestSampleWithoutHandler/MyApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ internal static void ExecuteAsync(string taskMessageBody, string projectId, stri

// Attache task log to the timeline record
UpdateTaskTimelineRecord(httpClient, authToken, planUri, projectId, hubName, planId, timelineId, taskInstanceId, taskLogObjectString);

// Set task varaible
SetTaskVariable(httpClient, authToken, planUri, projectId, hubName, planId, timelineId, taskInstanceId, "MyAppName", "TestApp", false);
}
}
}
Expand Down Expand Up @@ -212,8 +215,46 @@ private static void UpdateTaskTimelineRecord(HttpClient httpClient, string authT

PatchData(httpClient, updateTaskTimelineRecordUrl, requestBody, authToken);
}



private static void SetTaskVariable(HttpClient httpClient, string authToken, string planUri, string projectId, string hubName, string planId, string timelineId, string taskInstanceId, string variableName, string variableValue, bool isSecret)
{
// Get timeline records
const string TimelineRecordsUrl = "{0}/{1}/_apis/distributedtask/hubs/{2}/plans/{3}/timelines/{4}/records?api-version=4.1";

var timelineRecordsUrl = string.Format(TimelineRecordsUrl, planUri, projectId, hubName, planId, timelineId);

var response = GetData(httpClient, timelineRecordsUrl, authToken);
var timelineRecords = "";
if (response.StatusCode == HttpStatusCode.OK)
{
timelineRecords = response.Content.ReadAsStringAsync().Result;
dynamic timelineRecordsData = JsonConvert.DeserializeObject(timelineRecords);
JObject timelineRecord = new JObject();
foreach (var t in timelineRecordsData["value"])
{
string timelineRecordId = (string)t["id"];
if (string.Equals(timelineRecordId, taskInstanceId, StringComparison.OrdinalIgnoreCase))
{
timelineRecord = t;
var taskVaraible = new JObject();
taskVaraible[variableName] = new JObject(new JProperty("value", variableValue), new JProperty("isSecret", isSecret));
timelineRecord.Add(new JProperty("variables", taskVaraible));
}
}

JArray updatedTimelineRecords = new JArray();
updatedTimelineRecords.Add(timelineRecord);
var requestBodyJObject = new JObject();
requestBodyJObject["value"] = updatedTimelineRecords;
requestBodyJObject.Add(new JProperty("count", 1));

var requestBody = JsonConvert.SerializeObject(requestBodyJObject);

PatchData(httpClient, timelineRecordsUrl, requestBody, authToken);
}
}


private static HttpResponseMessage PostData(HttpClient httpClient, string url, string requestBody, string authToken)
{
var buffer = System.Text.Encoding.UTF8.GetBytes(requestBody);
Expand All @@ -239,5 +280,14 @@ private static HttpResponseMessage PatchData(HttpClient httpClient, string url,

return httpClient.PatchAsync(new Uri(url), byteContent).Result;
}

private static HttpResponseMessage GetData(HttpClient httpClient, string url, string authToken)
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", authToken))));

return httpClient.GetAsync(new Uri(url)).Result;
}
}
}