How can I access the `Build.BuildNumber` Azure variable from the inside of an ASP.NET application?

2.3k Views Asked by At

How can I access the Build.BuildNumber Azure variable from the inside of an ASP.NET application?

Is it the same as assembly number and can be retrieved using the (source)?

Assembly web = Assembly.Load("App_Code");
AssemblyName webName = web.GetName();

string myVersion = webName.Version.ToString();

I mean this Build.BuildNumber:

The name of the completed build, also known as the run number. You can specify what is included in this value.

A typical use of this variable is to make it part of the label format, which you specify on the repository tab.

Note: This value can contain whitespace or other invalid label characters. In these cases, the label format will fail.

This variable is agent-scoped, and can be used as an environment variable in a script and as a parameter in a build task, but not as part of the build number or as a version control tag.

2

There are 2 best solutions below

0
On BEST ANSWER

There is no direct relation between the build number that is generated in the pipeline and the version number in code. How would there be, because in order for that to happen the code need to be changed in order for the code to contain the build number.

However, there are build tasks that are able to do just that: take the devops pipeline build number and inject it in the code.

I use the VersionAssemblies and VersionDotNetCoreAssemblies tasks for that from this project.

You have to specify how the build number is configured, see the docs. Then you have to run the task just before the actual build is done.

The yaml pipeline then looks similair to this:

name: '1.$(date:yyyy).$(DayOfYear)$(rev:.r)'

<snip>

          - task: VersionDotNetCoreAssemblies@2
            inputs:
              Path: '$(Build.SourcesDirectory)'
              VersionNumber: '$(Build.BuildNumber)'
              Injectversion: False
              VersionRegex: '\d+\.\d+\.\d+\.\d+'
              FilenamePattern: '.csproj'
              AddDefault: true
              OutputVersion: 'OutputedVersion'

Then, in code we can do this:

var version = assembly.GetName().Version.ToString();

Output will be something like:

1.2021.109.1

Full documentation of the build task is found here. There is also a task for .Net Framework (not .Net Core) assemblies.

0
On

If you want to version the DLLs with the build number so the best way is like @Peter Bons answered here.

But, if you want to access the build number inside your code you can do it in this way:

var buildNumber = Environment.GetEnvironmentVariable("Build_BuildNumber", EnvironmentVariableTarget.Process);