Integrate Azure DevOps API for Continuous Integration in .NET
- Ensure your .NET application has access levels to interact with Azure DevOps API by setting up appropriate PAT (Personal Access Token). This token is used for authentication and should be securely stored, preferable as environment variables.
- Use the Azure DevOps RESTful APIs to automate your CI/CD processes. The APIs allow you to create, manage, and monitor pipelines, run builds, and more.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class AzureDevOpsService
{
private string _organizationName = "your-organization-name";
private string _projectName = "your-project-name";
private string _patToken = "your_personal_access_token"; // Securely retrieve this from environment variables
private string _url = $"https://dev.azure.com/{_organizationName}/{_projectName}/_apis";
public async Task TriggerBuildAsync()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes($":{_patToken}")));
var buildUri = $"{_url}/build/builds?api-version=6.0";
var requestBody = new { definition = new { id = 1 } }; // Provide your build definition id
var jsonContent = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
var response = await client.PostAsync(buildUri, jsonContent);
response.EnsureSuccessStatusCode();
Console.WriteLine("Build triggered successfully");
}
}
}
- Configure your .NET applications to use webhook endpoints for receiving real-time Azure DevOps events like build completion. This can be efficiently achieved using ASP.NET Core WebHooks.
- Create a WebAPI controller to handle incoming webhook events. You need to respond to these events according to your CI workflow logic.
using Microsoft.AspNetCore.Mvc;
[Route("api/[controller]")]
pubic class DevOpsWebhookController : ControllerBase
{
[HttpPost]
public IActionResult OnBuildCompleted([FromBody] dynamic payload)
{
// Process the payload received from Azure DevOps
Console.WriteLine($"Build completed with status: {payload.resource.result}");
return Ok();
}
}
- Ensure secure pipeline updates using API clients such as `Octokit` in your .NET applications, which offer enhanced security and more manageable API interactions.
- Besides triggering builds, use the Azure DevOps API to fetch build logs, monitor build status, and access artifacts, allowing you to optimize your CI practices for .NET projects.
// Example to fetch build status
public async Task GetBuildStatusAsync(int buildId)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes($":{_patToken}")));
var buildStatusUri = $"{_url}/build/builds/{buildId}?api-version=6.0";
var response = await client.GetAsync(buildStatusUri);
response.EnsureSuccessStatusCode();
var responseData = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Build Status: {responseData}");
}
}
- Maintain a robust error-handling mechanism within your HTTP request methods to adequately handle failed requests and improve resilience.
- Always stay updated with the Azure DevOps REST API documentation to understand new features and best practices, allowing you to efficiently manage your CI/CD pipelines.