0

If the right condition I will make a call to my Azure DevOps server, to set a build to not be deleted.

I followed: https://learn.microsoft.com/en-us/rest/api/azure/devops/build/leases/add?view=azure-devops-rest-6.0

I have some C# code where I try to set retain for a specific build. But I get bad request in the HttpResponse. I do several other calls to the API also due the bad request I feel confidence it isn't permissions.

I have added my code though anonymized.

using (var httpClient = new HttpClient(new HttpClientHandler()))
{
  httpClient.DefaultRequestHeaders.Accept.Add(new 
    MediaTypeWithQualityHeaderValue("application/json"));
    
  httpClient.DefaultRequestHeaders.Authorization = new 
    AuthenticationHeaderValue("Basic", personalAccessToken);
    
  JObject postBody = new JObject
  {
    { "daysValid", 100 },
    { "ownerId", "user@domain.com" },
    { "definitionId", 2222 },
    { "protectPipeline", true },
    { "runId", 4444 }
  };
    
  HttpContent content = new StringContent(postBody.ToString(), 
    Encoding.UTF8, "application/json");
    
  using HttpResponseMessage response = await 
httpClient.PostAsync($"https://dev.azure.com/{organization}/{project}/_apis/build/retention/leases?api-version=6.0-preview.1",
                            content).ConfigureAwait(false);
  if (!response.IsSuccessStatusCode)
  {
  }
}
JerryA
  • 153
  • 1
  • 8
  • Although I will not directly answer on your question regarding the C# code you provided, here is a guide to accomplish the requested directly from your Azure devops pipeline using powershell. https://blog.johnfolberth.com/dynamically-retain-azure-devops-pipelines. – GeralexGR May 04 '22 at 14:45
  • Thanks - I have found examples how to if I would do it in a pipeline. But I would prefere to do it in C# where I have the logic to determine if a build should be retained or not. – JerryA May 05 '22 at 06:32

1 Answers1

2

The solution was actually quite simple. At least when you know it. The content data I provided should be in an array, so after I changed to:

JArray array = new JArray { postBody };

HttpContent content = new StringContent(JsonConvert.SerializeObject(array), Encoding.UTF8, "application/json");

It worked perfectly and I can now see my new lease is added to the build.

JerryA
  • 153
  • 1
  • 8