qin
qin

Reputation: 1713

display build version on web page

I am developing a web site using asp.net core.
And I publish it with Visual Studio or/and VSTS.

I want to display some information about which build it is on the web page.
(something like rev 2016.9.20.4002)

How can I do that?

Upvotes: 4

Views: 10236

Answers (6)

yozniak
yozniak

Reputation: 695

It may be not exactly what requested but was quite efficient in my situation. If docker is used to build and deploy web apps, consider adding this step to your CI build script before docker build command (bash):

echo ENV BUILD_NUMBER=$(Build.BuildNumber) >> Dockerfile

In the app code just use BUILD_NUMBER environment variable.

The advantage of this method is that build number value becomes metadata of the docker image just like labels but you can also access it from the inside your app.

Upvotes: 0

Dhaval
Dhaval

Reputation: 113

After a day of research, finally found/created a better option than using any random app (Replace Token) from Marketplace.

The option I am talking is already available in VSTS, Azure CLI task.

Here are the stpes:

  1. Add setting BUILD_NUMBER with initial value of 1.0 in appsettings.json
  2. Read appsettings.json in your app and display it. I am sure you all are smart enough to figure out how to use appsettings to display Build Number on your WebApplication.
  3. In Azure Portal, similarly create an App Setting named BUILD_NUMBER with initial value of 1.0 in Azure Application settings section under App Services for your App.
  4. In VSTS, In your Release definition, add a task Azure CLI.
  5. Populate required fields such as Azure Subscription, Script Location with Inline script and last but most important Inline Script with following CLI command

az webapp config appsettings set -n iCoreTestApi -g ArchitectsSandbox -s Dev --settings BUILD_NUMBER=$(Build.BuildNumber)

Command explanation:

  • iCoreTestApi should be replaced by your real WebApp or Api name in Azure
  • ArchitectsSandbox should be replaced by your resource group in Azure
  • Dev is the slot name, you may or may not have it.
  • Rest of the command remains same.

Once you will queue new build, after successful completion of the deployment, you can see app settings section on Azure is updated with new BUILD_NUMBER.

Let me know if you still have any question.

Upvotes: 3

starian chen-MSFT
starian chen-MSFT

Reputation: 33708

You can track it with build number.

  1. Go to your VSTS site and create build definition
  2. Select General tab, specify build number format, for example: $(date:yyyyMMdd)$(rev:.r)
  3. (Optional) Select Triggers tab, check Continuous integration (CI) and configure filters if you want queue build for each check-in.
  4. Configure other settings (e.g. steps/task in Build tab) After build complete, go to the summary of that build definition (click build definition title hyperlink to go to summary page), the result will be like this:

enter image description here

Steps to display build number to your website:

  1. Install Replace Tokens extension to you VSTS
  2. Edit your build definition to add Replace token task
  3. Specify target files and root directory (for asp.net core app, you can specify **\appsettings.json) enter image description here
  4. Select Variable tab and add a new variable. Save your build definition enter image description here
  5. Edit appsettings.json file of your asp.net project. Sample code:
 {
      "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-ab933d83-8f4b-4024-9f3c-1aef5339a8f3;Trusted_Connection=True;MultipleActiveResultSets=true"
      },
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Debug",
          "System": "Information",
          "Microsoft": "Information"
        }
      },
      "CodeVersion": {
        "Num": "#{MyBuildNumber}#"
      }
    }
  1. Add logical to your asp.net project to read appsettings.json to get specific value and display in the page.
  2. Check in your code and queue build.

Upvotes: 6

Will Ray
Will Ray

Reputation: 10889

Just as an alternative option, you could read the time that the assembly was created and display it in a version format. Every time the assembly is rebuilt, this value would change to the time it was created.

(adapted from this answer for .Net Core)

public static class AppInfo
{
    private static Lazy<string> buildVersion =
        new Lazy<string>(() => GetBuildVersion(Assembly.GetEntryAssembly()));

    public static string BuildVersion { get; } = buildVersion.Value;

    private static string GetBuildVersion(Assembly assembly)
    {
        var filePath = assembly.Location;
        const int c_PeHeaderOffset = 60;
        const int c_LinkerTimestampOffset = 8;

        var buffer = new byte[2048];

        using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            stream.Read(buffer, 0, 2048);

        var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset);
        var secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset);
        var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        var linkTimeUtc = epoch.AddSeconds(secondsSince1970);

        var localTime = TimeZoneInfo.ConvertTime(linkTimeUtc, TimeZoneInfo.Local);
        var minutesFromMidnight = localTime.Minute + localTime.Hour * 60;

        return localTime.ToString("yyyy.M.dd.") + minutesFromMidnight;
    }
}

Then just reference it in Razor as:

@AppInfo.BuildVersion

Upvotes: 1

VickiM
VickiM

Reputation: 71

Do you mean something like this:

In project.json:

{
  "title": "Your Application name",
  "version": "2016.9.20.4002",
  "copyright": "Your Company 2016",
  "description": "Awesome ASP.Net Core Application",
  "dependencies": {
//rest of project.json

You can then create a property in your view model or model such as:

    public static string Version
    {
        get
        {
            var assembly = Assembly.GetExecutingAssembly();
            var fileVersion = GetCustomAttribute<AssemblyFileVersionAttribute>(assembly);

            return fileVersion?.Version;
        }
    }

In your view:

@model Namespace.CustomViewModel
<!--Other HTML Code-->

    <span id="applicationVersion">@CustomViewModel.Version</span>

Upvotes: 2

Set
Set

Reputation: 49789

Looks like ApplicationEnvironment class is what you need:

var appEnv = new Microsoft.Extensions.PlatformAbstractions.ApplicationEnvironment();
string version = appEnv.ApplicationVersion;

Also How can I auto-increment an MVC 6 version number? may be also interesting to you, but keep in mind, that IApplicationEnvironment has been removed.

Upvotes: 1

Related Questions