Getting the approver for release to an environment within an Azure DevOps Multi-Stage YAML pipeline

I recently had the need to get the email address of the approver of a deployment to an environment from within a multi-stage YAML pipeline. Turns out it was not as easy as I might have hoped given the available documented APIs.

Background

My YAML pipeline included a manual approval to allow deployment to a given environment. Within the stage protected by the approval, I needed the approver’s details, specifically their email address.

I managed to achieve this but had to use undocumented API calls. These were discovered by looking at Azure DevOps UI operations using development tools within my browser.

The Solution

The process was as follows

  • Make a call to the build’s timeline to get the current stage’s GUID – this is documented API call
  • Make a call to the Contribution/HierarchyQuery API to get the approver details. This is the undocumented API call.

The code to do this is as shown below. It makes use of predefined variables to pass in the details of the current run and stage.

Note that I had to re-create the web client object between each API call. If I did not do this I got a 400 Bad Request on the second API call – it took me ages to figure this out!

Loading drivers for cross-browser testing with Selenium

Another post so I don’t forget how I fixed a problem….

I have been making sure some Selenium UX tests that were originally written against Chrome also work with other browsers. I have had a few problems, the browser under test failing to load or Selenium not being able to find elements.

Turns out the solution is to just use the custom driver start-up options, the default constructors don’t seem to work for browsers other theran Chrome and Firefox.

Hence, I not have helper method that creates a driver from me based the a configuration parameter

  internal static IWebDriver GetWebDriver()
    {
        var driverName = GetWebConfigSetting("webdriver");
        switch (driverName)
        {
            case "Chrome":
                return new ChromeDriver();
            case "Firefox":
                return new FirefoxDriver();
            case "IE":
                InternetExplorerOptions caps = new InternetExplorerOptions();
                caps.IgnoreZoomLevel = true;
                caps.EnableNativeEvents = false;
                caps.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                caps.EnablePersistentHover = true;
                return new InternetExplorerDriver(caps);
            case "Edge-Chromium":
                var service = EdgeDriverService.CreateDefaultService(Directory.GetCurrentDirectory(), "msedgedriver.exe");
                return new EdgeDriver(service);
            default:
                throw new ConfigurationErrorsException($"{driverName} is not a known Selenium WebDriver");
        }
    }

A first look at the beta of GitHub Issue Forms

Update 10 May 2021 Remember that GitHub Issue Forms are in early beta, you need to keep an eye on the regular new releases as they come out. For example, my GitHub Forms stopped showing last week. This was due to me using now deprecate lines in the YAML definition files. Once I edited the files to update to support YAML they all leap back into life


GitHub Issues are core to tracking work in GitHub. Their flexibility is their biggest advantage and disadvantage. As a maintainer of a projects, I always need specific information when an issue is raised. Whether it be a bug, or feature request.

Historically, I have used Issue Templates, but these templates are not enforced. They add a suggestion for the issue text, but this can be ignored by the person raising the issue, and I can assure you they often do.

I have been lucky enough to have a look at GitHub Issue Forms, which is currently in early private beta. This new feature aims to address the problem by making the creation of issues form-based using YML templates.

I have swapped to using them on my most active repos Azure DevOps Pipeline extensions and GitHub Release Notes Action. My initial experience has been very good, the usual YML issue of incorrect indenting, but nothing more serious. They allow the easy creation of rich forms that are specific to the project.

They next step is to see if the quality of the logged issues improves.

Tidying up local branches with a Git Alias and a PowerShell Script

It is easy to get your local branches in Git out of sync with the upstream repository, leaving old dead branches locally that you can’t remember creating. You can use the prune option on your Git Fetch command to remove the remote branch references, but that command does nothing to remove local branches.

A good while ago, I wrote a small PowerShell script to wrapper the running of the Git Fetch and then based on the deletions remove any matching local branches. Then finally returning me to my trunk branch.

Note: This script was based on some sample I found, but I can’t remember where to give credit, sorry.

I used to just run this command from the command line, but I recently thought it would be easier if it became a Git Alias. As Git Aliases run a bash shell, this meant I needed to shell out to PowerShell 7. Hence, my Git Config ended up being as shown below

[user]
        name = Richard Fennell
        email = richard@blackmarble.co.uk
[filter "lfs"]
        required = true
        clean = git-lfs clean -- %f
        smudge = git-lfs smudge -- %f
        process = git-lfs filter-process
[init]
        defaultBranch = main
[alias]
        tidy = !pwsh.exe C:/Users/fez/OneDrive/Tools/Remove-DeletedGitBranches.ps1 -force

I can just run 'git tidy‘ and all my branches get sorted out.

Added Manual Test Plan support to my Azure DevOps Cross-Platform Release notes Task

I have just release 3.46.4 of my Azure DevOps Cross-Platform release Notes task which adds support for generating release notes based on the results of Azure DevOps Test Plans.

There has been support in the task for automated tests, run as part of the build or release process, for a while. However, until this release, there was no way to generate release notes based on manual tests.

Manual Test results are now made available to the templating engine using two new objects:

  • manualtests – the array of manual Test Plan runs associated with any of the builds linked to the release. This includes sub-objects detailing each test.
    Note: Test Runs are also available under the builds array when the task is used in a release, for each build object there is a list of its manual tests as well commits and WI etc.
  • manualTestConfigurations – the array of manual test configurations test have been run against.

The second object, to store the test configurations, is required because the test results only contain the ID of the configuration used, not any useful detail such as a name or description. The extra object allows a lookup to be done if this information is required in the release notes e.g. if you have chosen to list out each test, and each test is run multiple times in a test run against different configurations e.g. UAt and Live

So you can now generate release notes with summaries of manual test runs

Using a template in this form

## Manual Test Plans
| Run ID | Name | State | Total Tests | Passed Tests |
| --- | --- | --- | --- | --- |
{{#forEach manualTests}}
| [{{this.id}}]({{this.webAccessUrl}}) | {{this.name}} | {{this.state}} | {{this.totalTests}} | {{this.passedTests}} |
{{/forEach}}

Or detailing out all the individual test

with a template like this

## Manual Test Plans with test details
{{#forEach manualTests}}
### [{{this.id}}]({{this.webAccessUrl}}) {{this.name}} - {{this.state}}
| Test | Outcome | Configuration |
| - | - | - |
{{#forEach this.TestResults}}
| {{this.testCaseTitle}} | {{this.outcome}} | {{#with (lookup_a_test_configuration ../../manualTestConfigurations this.configuration.id)}} {{this.name}} {{/with}} |
{{/forEach}}
{{/forEach}}

Fixing my SQLite Error 5: ‘database is locked’ error in Entity Framework

I have spent too long today trying to track down an intermittent “SQLite Error 5: ‘database is locked’” error in .Net Core Entity Framework.

I have read plenty of documentation and even tried swapping to use SQL Server, as opposed to SQLite, but this just resulted in the error ‘There is already an open DataReader associated with this Connection which must be closed first.’.

So everything pointed to it being a mistake I had made.

And it was, it turns out the issue was I had the dbContext.SaveChanges() call inside a foreach loop

It was

using (var dbContext = scope.ServiceProvider.GetRequiredService()) {
    var itemsToQueue = dbContext.CopyOperations.Where(o => o.RequestedStartTime < DateTime.UtcNow && o.Status == OperationStatus.Queued);
    foreach (var item in itemsToQueue) {
        item.Status = OperationStatus.StartRequested;
        item.StartTime = DateTime.UtcNow;
        dbContext.SaveChanges();
    }
}

And it should have been

 using (var dbContext = scope.ServiceProvider.GetRequiredService()) {
    var itemsToQueue = dbContext.CopyOperations.Where(o => o.RequestedStartTime < DateTime.UtcNow && o.Status == OperationStatus.Queued);
    foreach (var item in itemsToQueue) {
        item.Status = OperationStatus.StartRequested;
        item.StartTime = DateTime.UtcNow;
    }
    dbContext.SaveChanges();
}

Once this change was made my error disappeared.

What to do when moving your Azure DevOps organisation from one region to another is delayed.

There are good reasons why you might wish to move an existing Azure DevOps organisation from one region to another. The most common ones are probably:

  • A new Azure DevOps region has become available since you created your organisation that is a ‘better home’ for your projects.
  • New or changing national regulations require your source stored in a specific location.
  • You want your repositories as close to your workers as possible, to reduce network latency.

One of these reasons meant I recently had to move an Azure DevOps organisation, so followed the documented process. This requires you to

  1. Whilst logged in as the Azure DevOps organisation owner, open the Azure DevOps Virtual Support Agent
  2. Select the quick action ‘Change Organization Region’
  3. Follow the wizard to pick the new region and the date for the move.

You are warned that there could be a short loss of service during the move. Much of the move is done as a background process. It is only the final switch over that can interrupt service, hence this interruption being short.

I followed this process, but after the planned move date I found my organisation has not moved. In the Virtual Support Agent, I found the message.

Please note that region move requests are currently delayed due to ongoing deployments. We may not be able to perform the change at your requested time and may ask you to reschedule. We apologize for the potential delay and appreciate your patience!

I received no other emails, I suspect overly aggressive spam filters were the cause of that, but it meant I was unclear what to do next. Should I:

  1. Just wait i.e. do not reschedule anything, even though the target date is now in the past
  2. Reschedule the existing move request to a date in the future using the virtual assistant wizard
  3. Cancel the old request and start the process again from scratch

After asking the question in the Visual Studio Developer Community Forums I was told the correct action is to cancel the old request and request a new move date. It seems that once your requested date is passed the move will not take place no matter how long you wait.

Hence, I created a new request, which all went through exactly as planned.

Porting my Release Notes Azure DevOps Pipelines Extension to GitHub Actions

One of my most popular Azure DevOps Extensions is my Release Notes Pipeline task. This allows the creation of release notes using information obtained from the Azure DevOps API and formatted using a Handlebars Template.

Given the popularity of GitHub Actions, I got to wondering whether porting this extension was viable?

Well the release of my new Generate Release Notes with a Handlebars Template action shows that it was.

The basic concept of this new action is the same as for the older task, get information on the pipeline/workflow run using the API and then format it using a Handlebars template. However, the information that can be returned is different. But this stands to reason as GitHub is not Azure DevOps. This is especially true when you consider the differences between the simplicity of GitHub Issues and the complexity, and variability of format, of Azure DevOps Work Items

The new action is focused on the workflow run it is called from. It make an API call to get the details of the run. This contains a lot of information about the run and URL links to associated items. Using these link, the associated information is retrieved using the API and the results added to the objects available in the Handlebars template. In this initial version of the Action the objects tree available in a template includes:

  • runDetails – the details of the current workflow run
    • pull_requests – the array of pull requests associated with the run
      • commits – the array of commits associated with the PR
      • comments – the array of comment associated with the PR
      • linkedIssues – the array of linked issues with the PR

As with my Azure DevOps Extension I have made use of the extensibility of Handlebars. My new action includes all the Handlebar Helpers, plus some action specific helpers I have written and you have the ability to add your own custom handlebar helpers if needed.

So I hope people find this new Action useful, I guess only time will tell

Running UWP Unit Tests as part of an Azure DevOps Pipeline

I was reminded recently of the hoops you have to jump through to run UWP unit tests within an Azure DevOps automated build.

The key steps you need to remember are as follows

Desktop Interaction

The build agent should not be running as a service it must be able to interact with the desktop.

If you did not set this mode during configuration this post from Donovan Brown shows how to swap the agent over without a complete reconfiguration.

Test Assemblies

The UWP unit test projects are not built as a DLL, but as an EXE.

I stupidly just made my VSTest task look for the generated EXE and run the tests they contained. This does not work generating the somewhat confusing error

Test run will use DLL(s) built for framework .NETFramework,Version=v4.0 and platform X86. Following DLL(s) do not match framework/platform settings.
BlackMarble.Spectrum.FridgeManagement.Client.OneWire.UnitTests.exe is built for Framework .NETCore,Version=v5.0 and Platform X86.

What you should search for as the entry point for the tests is the .appxrecipe file. Once tI used this my tests ran.

So my pipeline YML to run all the tests in a built solutions was

- task: VisualStudioTestPlatformInstaller@1
   inputs:
      packageFeedSelector: 'nugetOrg'
      versionSelector: 'latestPreRelease'              

- task: VSTest@2
    displayName: 'VSTest - testAssemblies'
    inputs:
       platform: 'x86'
       configuration: '$(BuildConfiguration)'
       testSelector: 'testAssemblies' 
testAssemblyVer2: | # Required when testSelector == TestAssemblies
         **\*unittests.dll
        **\*unittests.build.appxrecipe
         !**\*TestAdapter.dll
         !**\obj\** 
       searchFolder: '$(Build.SourcesDirectory)/src'
       resultsFolder: '$(System.DefaultWorkingDirectory)\TestResults'
       runInParallel: false
       codeCoverageEnabled: true
       rerunFailedTests: false
       runTestsInIsolation: true
       runOnlyImpactedTests: false
        
- task: PublishTestResults@2

   displayName: 'Publish Test Results **/TEST-*.xml'
  condition: always()