Auto increment build number in a JavaScript app

Auto increment build number in a JavaScript app

Whilst looking a simple way to auto increment an application build version number for a small React JavaScript application I found a neat solution so I’m sharing it here for others to use (and for me to refer back to on my next project).

Photo by Ariel on Unsplash

Problem:

For a small React application using NPM I needed to automatically increment a build number on every production build without having to remember to do it, and then I needed to refer to that version number within the application in order to display in on the site’s footer.

Solution:

After a short Google I found this really neat solution posted by Jan Lübeck on the Creact-React-App Github site here which I then very slightly tweaked for my requirements.

The solution is to essentially call a NodeJs script from npm build script definition whcih updates a metadata JSON file within the prpoject to increment the build version number by 1. This file can then be read within the React code as required to display the currnt vuild verson.

First we need to store the build version numbers in a JSON file:

{
"buildMajor":1,
"buildMinor":0,
"buildRevision":3,
"buildTag":"BETA"
}

Only the buildRevision will be updated automatically as we will want manual control over the major/minor numbers as we implement semantic versioning.

The NodeJS Script (generate-buildno.js) is below. This opens the metadata.json file, reads the buildRevision value and then updates it by 1 before saving the file:

var fs = require('fs');
console.log('Incrementing build number...');
fs.readFile('src/metadata.json',function(err,content) {
    if (err) throw err;
    var metadata = JSON.parse(content);
    metadata.buildRevision = metadata.buildRevision + 1;
    fs.writeFile('src/metadata.json',JSON.stringify(metadata),function(err){
        if (err) throw err;
        console.log(`Current build number: ${metadata.buildMajor}.${metadata.buildMinor}.${metadata.buildRevision} ${metadata.buildTag}`);
    })
});

To call this script at build time we update the package.json file and change the build command to call our script first, before the normal build command:

 "scripts": {
    "start": "react-scripts start",
    "build": "node generate-buildno.js && react-scripts build",
    "test": "react-scripts test",
  },

Now when we call npm run build the JSON file we be updated and the build revision number incremented. The React code that needs to display the app version number just has to read the metadata.json file like the example React Components below:

import React from 'react';
import metadata from './metadata.json';

function FooterComponent() {
  return (
    <div className="sf-footer">
      &copy; 2020 RichHewlett.com
      <div className="sf-footer-version">
        {`Version ${metadata.buildMajor}.${metadata.buildMinor}.${metadata.buildRevision} ${metadata.buildTag}`}
      </div>
    </div>
  );
}
export default FooterComponent;

Remember after building the application to commit your changed metadata.json file into source control!

Java keystore certificate missing after Jenkins upgrade

Java keystore certificate missing after Jenkins upgrade

Following a tricky upgrade to a Jenkins server it was found that the server was no longer able to communicate with the Git server, although SSH access with private keys was stil working correctly. On invrestigating the Jenkins logs (found at Logs at: http://YOUR-JENKINS-SERVER-URL/log/all) this error was found to be the problem:

Failed to login with creds MYCREDENTIALNAMEHERE
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
Caused: sun.security.validator.ValidatorException: PKIX path building failed
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
Caused: javax.net.ssl.SSLHandshakeException

The problem here is that the Java runtime is not able to validate the connection as it doesnt have the relevant SSL certificate. To resolve I needed to download the certificate from the site and add it to the Java Keystore.

Photo by Chunlea Ju on Unsplash

On the server download the relevant web certificate for connecting to the relevant site (a GitHub server in my instance) that you are trying to access. Next find which Java JRE your Jenkins was using. This can be found in your Jenkins.xml file under the executable element. For example %BASE%\jre\bin\java means c:\Jenkins\JRE\bin\java if you have installed Jenkins to C:\Jenkins on Windows. Now find the cacerts file inside that Java runtime that it was using (for example C:\Jenkins\jre\lib\security\cacerts) where you will need to install the Certificate. To add the cert to the Java Keystore for that Java install run the below in a terminal:

keytool -import -alias INSERT_ALIAS_NAME_HERE -keystore PATH_TO_JRE_HERE\security\cacerts -file CERTIFICATE_FILE_NAME

for example…

keytool -import -alias ExampleName -keystore C:\Jenkins\jre\lib\security\cacerts -file exampleCertFile.cer

If you are asked for a password then it will be ‘changeit‘ by default.

Now the JRE Java runtime on the box that Jenkins is now using has the Certificate installed it will be able to make a SSL connection.

Current Podcast Recommendations

Current Podcast Recommendations

 As someone with a long commute I find Podcasts a great way of keeping up to date with technology (as well as other things) and it helps me feel that my commute time is not wasted. Over the years I think I have benefited from this approach as its increased my level of general knowledge and helped me keep up to date with the latest developments in the industry.

Over the last ten years I have occasionally posted my top podcast picks and here are the links to my previous posts in 2010, 2012 and 2016.

Below is a list of my current podcast recommendations for technical and non-technical subjects.

Podcasts on Software Development:
Podcasts on Technology:
Other Recommended Podcasts :
Photo by Malte Wingen on Unsplash

Jenkins: Script not permitted to use method signature

Jenkins: Script not permitted to use method signature

I’ve recently ran into an error in a Jenkins CI/CD pipeline when using java.util.Date objects in my Groovy script pipeline and so I’d thought I’d share the problem and workaround.

Problem

In order to create a date time and build number stamp into an output build package as part of a Jenkins build I made use of the java Date object in Groovy, something like this:

def date1 = new Date(1456533546)
def today = new Date()
def diff = (today-date1)

On running the build I get this error in the console log:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:
Scripts not permitted to use staticMethod 
org.codehaus.groovy.runtime.DateGroovyMethods minus java.util.Date

It turns out that as the Groovy script jenkinsfile is running in the Groovy Sandbox in Jenkins it has a white-list of approved method signatures out of the box, but java.util.Date is not one of them.

Solution

If you add the Script Security Plugin to your Jenkins install, if its not there already, then you’ll be able to whitelist new methods and apis that can be used by the Jenkins pipeline scripts.

Log onto Jenkins as an Administrator and go to Manage Jenkins > In-process Script Approval and scroll to the bottom where the Script Security Plugin will have put new entries. Here you’ll find recent script permission failures and details.

options in Script Approval UI

Choosing to “Approve” the signature will then approve scripts to use this java signature (in this example the java.util.Date object) and the error should go away.

For more information see the official Jenkins docs here.

Free SSL encryption on Azure with Cloudflare

Free SSL encryption on Azure with Cloudflare

I have a small Web Application site (running ASP.net Core) hosted on Microsoft Azure under a shared plan. Azure shared plans are budget friendly whilst providing features like custom domain names. Until recently the site was HTTP only which was initially fine for my use case but as HTTPS is becoming increasingly a minimum standard on most sites and even browsers are now warning users when navigating to unsecure sites, it was time to move to HTTPS.

Photo by James Sutton on Unsplash

The Problem

Whilst setting up HTTPs certificates has got easier and cheaper there is still usually a trade off between effort and cost. I could have added SSL to my Azure subscription but I couldn’t justify that cost for the site in question. So I needed an easy and cheap solution – and I definitely found it with Cloudflare!

The Solution

I am amazed how easy it was to set up SSL fronting of my existing site using Cloudflare’s SSL.

  1. Create an account at Cloudflare.com
  2. Enter your domain name where the site is hosted.
  3. Confirm the pricing plan (choose FREE)
  4. Cloudflare scans the domain’s DNS entries and asks you to confirm which entries you want proxying. Once done you’ll be given the new NameServers which you’ll need to update on your domain registar’s site.
  5. Once the NameServers have synced (could take minutes to 48 hours) you are done!

There are a few configuration modes for their SSL offering, e.g. full SSL (i.e. SSL from end users to Cloudflare to origin server) or Flexible (i.e. where the SSL stops at Cloudflare and traffic is not encrypted from your origin server to Cloudflare). The options you choose will depend on your setup and your requirements. As my site is hosted on Azure I got Full SSL encryption by default (using Azure’s SSL keys to encrypt traffic from my web server to Cloudflare).

You don’t need an Azure hosted site for this SSL goodness to work as they will front your service wherever its hosted.

This process was so easy I should have done it months ago. For more info checkout these resources:

Build warnings & .Net Standard dependencies

Build warnings & .Net Standard dependencies

Having recently migrated a Windows Azure hosted .Net Framework ASP.net MVC 5 web application over to ASP.net Core (v2.2) I hit a few issues so I’m documenting them here for my future self and anyone else who might find it useful. The application was a multi functional ASP.net MVC site with an Azure Blob Storage Service back-end that I re-wrote in new ASP.Net Core with a mixture of both MVC and Razor Pages. The new site was .Net core 2.2 which referenced supporting projects built to .Net Standard 2.0.

The Problem

The application ran fine locally and as I was re-purposing the same Windows Azure Web Service instance I re-configured it to support .Net Core via the Azure Portal. Its not clear if this step is actually required but it makes sense to set it correctly (see screnshot below).

Next I deployed my Web App via Web Deploy, and then hit the homepage but immediately received a long list of errors such as the one below:

The type 'Attribute' is defined in an assembly that is not referenced. 
You must add a reference to assembly
'System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'. 
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Index), @"mvc.1.0.view", @"/Views/Home/Index.cshtml")] ……etc……

It looked like .Net itself was not being found on the target machine, and so after checking the server settings and server logs in the Azure Portal I double checked my project references to confirm I was targeting .Net Core and .Net Standard 2.0 and that’s when I found a build Warning that I had previously missed:

[NU1701] Package 'Microsoft.Azure.KeyVault.Core 1.0.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. 
This package may not be fully compatible with your project

One of my dependent projects in the solution was referencing the Azure SDK assembly Microsoft.Azure.Storage.Blob (via NuGet package) which in turn was referencing a version of Microsoft.Azure.KeyVault.Core that was not compatible with .NetStandard 2.0. This solution ran fine locally (as the dependent framework is installed on my machine) but when the application was deployed to a server without the .Net Framework Version=v4.6.1 binaries the application failed to load. More on this problem can be found in this GitHub issue.

The Solution

The solution was to reference a later version of the Microsoft.Azure.KeyVault.Core assembly that does support .NetStandard. As my project had no direct reference to Microsoft.Azure.KeyVault.Core (as it was a dependency of Microsoft.Azure.Storage.Blob) I had no dependency reference to update and so instead added a direct dependency to Microsoft.Azure.KeyVault.Core version 3.0.3 in my project file. This didn’t directly resolve my issue though despite reportedly working for other people, but at this point I decided to update all my Azure SDK references which took Microsoft.Azure.Storage.Blob to v11.1.3 which references a .NetStandard 2.0 compliant version of the KeyVault.Core dependency:

  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Storage.Blob" Version="11.1.3" />
  </ItemGroup>

After upgrading (tweaking a few updated namespaces that has changed in the newer package versions) I deployed the project successfully without error. Issue resolved!

The lesson here I think is to firstly don’t ignore build warnings (we all sometimes – right?) and secondly be careful with dependencies and their children not being .NetStandard compliant. This may be less of a problem in the future as .Net Core and .Net Standard gets more widespread adoption but for now its one to watch for.

IIS Express Launch Script

IIS Express Launch Script

Usually during web development you want to run your web code locally via a local development web server and there are many options for this. In fact most development workflows provide this functionality. For example Visual Studio provides a local web server to run your code, and React/Webpack toolchains usually use NodeJS based solutions. Sometimes though you want to want to fire up something simple to run your code outside your development workflow.

Photo by Aryan Dhiman on Unsplash

The Problem

When developing ReactJS projects I often prefer to run my transpiled bundled code (produced via ‘NPM run build’) in a different way to my development code on a different local web server and, as I usually have IIS Express installed already, I prefer to use that than install new global Node based web server tools. Whilst the command line parameters for IIS Express are simple I have added them to this post to prevent me having to remember them in the future 🙂

The Solution

To run IIS Express from the commandline use:

iisexpress /path:<path_to_files>

You can also specify a port number and other options if you require (see the documentation here).

I prefer to wrap this into a RunOutputBuild.cmd batch file that I can store with the code in the repo and fire up when I want to host my transpiled build output files.

REM Script to launch IIS Express and host the build folder
echo "Launching IIS Express"
cmd /K "c:\program files (x86)\IIS Express\iisexpress.exe" /path:%~dp0build

This assumes the IIS Express installation location is the default one and that the script lives in root of the repo as does the \build folder. The useful %~dp0 key resolves to the local directory where the command script was run from.

I can then just run the command file and browse to the compiled site. Its also possible to add compilation steps and one to fire up the browser automatically if required. Alternatively you could write an NPM Script or Gulp/Grunt step that replicates this functionality to launch IIS Express.

Break your site out of Internet Explorer Compatibility View

Break your site out of Internet Explorer Compatibility View

Internet Explorer Compatibility mode is a feature of IE that allows you to choose to render sites that targeted older versions of IE when they were developed. It essentially pretends to be IE 8 during rendering which can correct many issues. Microsoft maintains a list of sites that require this compatibility mode and allows users to choose additional sites that should be rendered using this mode. For many large enterprises that were suck on IE 6 because of the need to old legacy systems built to IE6 standards this feature proved very valuable as it enabled them to move their workstations to newer supported version of IE whilst they built replacements for their legacy systems. You can choose to enable Compatibility mode for specific sites or all intranet sites.

alt text

The Problem

So what if you know that the majority of the users of your modern web application are using IE11 but with Compatibility mode on which makes their browser pretend its IE8 and thus unable to make use of new browser features? Unless you build in support for very old browsers via polyfills then those users will see errors and unexpected behaviors.

The Solution

If you want to ensure that users of IE11 or Edge are not Restricted by Compatibility mode then you need to disable it for your site and this is possible by adding a meta tag to your pages. Add the below meta tag in your head tag:

<head>
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
</head>

The page will then disable the Compatibility mode and render the page as Edge compliant modern standards. This is a very useful way to target modern browser features without having to turn off compatibility settings on each client and possibly causing issues with other sites.

For more information checkout these links here and here

Some Recommended VS Code Extensions

Some Recommended VS Code Extensions

One of the things that makes Visual Studio Code (VSCode) such a great editor is the many extensions that have been built for it. Extensions in VSCode are explained here. As a reference for myself when building new machines,and anyone else who might find this useful, below is a list of my most used extensions:

  • Bracket pair colorizer – Colours your brackets and braces for easy identification. I avoid many missing bracket errors with this one!
  • XML Tools – XML Formatting, XQuery, and XPath Tools.
  • ESLint – Extension to integrate ESLint into the IDE.
  • SonarLint – Sonar Rules in VSCode to check your code quality as you go.
  • Prettier – Integrate Prettier into your IDE
  • GitLens – Extend the Git capabilities of VSCode with this tool.
  • PowerShell – Develop PowerShell scripts inside VSCode.
  • Docker – Develop Dockers scripts inside VSCode. Adds syntax highlighting, commands, hover tips, and linting for Dockerfile and docker-compose files.
  • REST Client – Allows you to send HTTP requests and view the response directly in VSCode.
  • JS Refactor – Automated refactoring tools to smooth your JavaScript development workflow.

Check out more on the VSCode marketplace.

What are you using?

Razor Pages Fixes to Tag Helpers Issues

Razor Pages Fixes to Tag Helpers Issues

Recently when adding Razor Pages to an existing ASP.net Core MVC web application I had issues with the Tag Helpers not working. No markup was being produced. Not only were the tag helpers (i.e. asp-for) not doing their job of but I also noticed that the markup was not being formatted in bold in Visual Studio as it should be.

At this point I checked for a _ViewImports.cshtml file which I found before checking some other things (see the list below), however I failed to notice that as this was an MVC application with Razor Views there is already a _ViewImports.cshtml file but in the wrong place for my Razor Pages. The _ViewImports.cshtml file must be in the root of the Pages folder where your Razor pages reside, and so you will need one in both the Pages folder for your Razor Pages and also in the Views folder for your MVC Razor Views.

The _ViewImports.cshtml file must contain:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Adding a new _ViewImports.cshtml file under the Pages folder resolved my problem, but in the meantime here are some additional things to try if you have other Tag Helper problems:

  • Update all dependency Packages
  • Add/re-add Microsoft.AspNetCore.MVC.TagHelpers package if its missing
  • Check your _ViewImports.cshtml file is in the Pages folder or a parent folder of your Razor Pages. You may need one in the Areas folder if you have one.
  • Check that the _ViewImports.cshtml file includes a reference to Microsoft.AspNetCore.Mvc.TagHelpers. If it does try removing it, rebuilding the solution and then re-adding it, and rebuilding again.
  • Check the namespace in the _ViewImports.cshtml file is correct.
  • Should all these fail, try turning on the developer exception page and see if that helps to narrow down the problem.