avivasolutionsnl / Beacon

A TeamCity or Azure DevOps monitoring tool that uses a Delcom USB LED or Shelly bulb to notify your teams
https://chocolatey.org/packages/beacon
Apache License 2.0
5 stars 4 forks source link

Add support for azure devops #32

Closed Barsonax closed 4 years ago

Barsonax commented 4 years ago

Azure Devops has a REST API which Beacon could use to also support Azure Devops.

There is a nuget package available which makes it easy to use this REST service in .NET projects. Here's a simple console example that polls the status of the lastest build on the master branch:

using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace AzureDevopsApiTest
{
    public class AzureDevopsOptions
    {
        /// <summary>
        /// The base url of the organisation or tfs instance.
        /// </summary>
        public Uri BaseUrl { get; set; }

        public string ProjectName { get; set; }

        /// <summary>
        /// The definition id of the build.
        /// </summary>
        public int DefinitionId { get; set; }

        /// <summary>
        /// For branches use refs/heads/branchname.
        /// For tags use refs/tags/tagname.
        /// </summary>
        public string BranchName { get; set; }

        /// <summary>
        /// Optional, not needed for public projects.
        /// </summary>
        public string PersonalAccessToken { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var options = new AzureDevopsOptions
            {
                BaseUrl = new Uri("https://dev.azure.com/yourorganisation"),
                ProjectName = "projectname",
                DefinitionId = 11,
                BranchName = "refs/heads/master",
                //PersonalAccessToken = "yourtokenhere"
            };

            var credentials = options.PersonalAccessToken == null ? new VssCredentials() : new VssBasicCredential(string.Empty, options.PersonalAccessToken);
            VssConnection connection = new VssConnection(options.BaseUrl, credentials);

            BuildHttpClient buildClient = connection.GetClient<BuildHttpClient>();

            var definitions = new[] { (await buildClient.GetDefinitionAsync(options.ProjectName, options.DefinitionId)).Id };

            while (true)
            {
                var latestBuild = (await buildClient.GetBuildsAsync(options.ProjectName, definitions, top: 1, branchName: options.BranchName)).FirstOrDefault();

                Console.WriteLine(latestBuild?.Status ?? BuildStatus.None);

                await Task.Delay(500);
            }
        }
    }
}