SonarQube Analysis

Posted on December 23, 2016

This is a guest post by Cedd Burge, Software Developer Lead at RES.

SonarQube / SonarSource analyzes code, highlights quality issues and calculates metrics such as technical debt. More information is available on SonarSource.com.

This post is written from the point of view of someone (me) who is already proficient in C#, and had even used SonarQube, but was new to AppVeyor and integrating SonarQube with GitHub.

It contains from scratch steps to run the SonarQube analysis on a sample project and to publish the results to the publicly available Nemo instance of SonarQube. You can look at the repo I created to test this post if you get stuck.

Create a new GitHub repository

If you are new to GitHub, see this getting started guide, otherwise simply create a new repo and git clone it somewhere convenient.

Create a new project

In my version of Visual Studio (Community 2015), you can do this by clicking on “File - New - Project” on the main menu, then “Class Library” from “Templates - Visual C#”. Give it a interesting name, which I will assume to be YourProjectName for the rest of this post.

Add some code that has some quality issues (e.g. a variable that is declared but never used). You can use the the full list of SonarQube C# issues for inspiration. Alternatively you can copy and paste some of mine.

Install the SonarLint Visual Studio Plugin. This highlights quality issues in your code as you type and gives you a chance to fix them before committing.

Integrate with AppVeyor

You will need to link an AppVeyor account to your GitHub one, so let’s do that:

  • Navigate to your repo in GitHub
  • Click “Settings” on the repo
  • Click “Integrations and services”
  • Click “Browse Directory”
  • Click “AppVeyor”
  • Click “Configure”
  • Click “Grant Access”

Now Log in to AppVeyor.com, probably using your GitHub account

  • Click “Projects”
  • Click “New Project”
  • Choose your GitHub repository and click “Add”

Sign up with SonarQube and generate an Authentication Token

Run SonarQube Analysis Locally

When working with AppVeyor, it always makes sense to test on your own computer first. The feedback is immediate and you iterate very quickly. It takes a lot longer to modify the appveyor.yml file, push it and wait for a build to go through. Also, if it works locally but doesn’t work on AppVeyor, you know the problem is a configuration difference between your computer and the AppVeyor environment (e.g. a different version of msbuild).

Instead of committing SonarQube executables to the repo, we will download them during the build using Chocolatey.

Install chocolatey

  • Install Chocolatey from an administrator command prompt / powershell.
  • Close the command prompt

Install SonarQube MSBuild Runner

  • Open a new administrator command prompt / powershell.
  • choco install "msbuild-sonarqube-runner" -y

Analyze and upload to SonarQube

MSBuild.SonarQube.Runner.exe begin /k:"**YourUniqueProjectName**" /d:"sonar.host.url=https://sonarqube.com" /d:"sonar.login=**YourSonarQubeToken**"
"**YourPathToMSBuild**\MSBuild.exe" "**YourProjectName**.sln"
MSBuild.SonarQube.Runner.exe end /d:"sonar.login=**YourSonarQubeToken**"

When finished, you will be able to see the results at sonarqube.com/. If it isn’t working, make sure you are using MSBuild 14 and Java 1.8 or later. The SonarQube Getting Started page is excellent if these instructions become out of date.

Run SonarQube Analysis on AppVeyor

Now that this is working locally, we can run it on AppVeyor.

Add and commit an appveyor.yml file to the root of the repository as follows

before_build:
  - nuget restore
build_script:
  - choco install "msbuild-sonarqube-runner" -y
  - MSBuild.SonarQube.Runner.exe begin /k:"YourUniqueProjectName" /d:"sonar.host.url=https://sonarqube.com" /d:"sonar.login=YourSonarQubeToken"
  - msbuild "YourProjectName.sln"
  - MSBuild.SonarQube.Runner.exe end /d:"sonar.login=YourSonarQubeToken"

Again, you can check the results at sonarqube.com.

Add a SonarQube badge to the repo

There are are variety of Quality Gate and Metrics badges available.

To add a standard Quality Gatebadge, add the following to readme.md.

[![Quality Gate](https://sonarqube.com/api/badges/gate?key=YourUniqueProjectName)](https://sonarqube.com/dashboard/index/YourUniqueProjectName)

Integrate SonarQube with Pull Requests

SonarQube can analyze Pull Requests for quality issues, which you can see on this pull request.

This requires a GitHub authentication token, which must be secured, secure variables to be enabled in pull requests and a differential build for Pull Requests.

Get a GitHub Authentication token

Go to your profile and click “Edit Profile”. Click on “Personal access tokens” in the “Developer settings” section. Give the token any name and tick on the “public_repo” scope. Make a note of the created token (GitHubAuthToken from now on)

Secure the GitHub Authentication token

Anyone with access to this token can alter your data, contact information and billing data, so we don’t want that.

On AppVeyor, click your user name in the top right hand corner and then click “Encrypt data” from the drop down menu. Enter GitHubAuthToken in to “Value to encrypt” and click “Encrypt”. AppVeyor will then display a token which you can use in place of the real value (EncryptedGitHubAuthToken from now on).

Allowing Secure Variables in Pull Requests

Normally AppVeyor will not decrypt secure variables in Pull Requests, as in this case a Hacker could send you a PR and then read all of your secure data. However, for SonarQube to analyze Pull Requests, it is necessary. You need to decide whether you can live with this.

If you can, go to AppVeyor, click on your project, click “Settings”, tick “Enable secure variables in Pull Requests from the same repository only” and click “Save”.

Create a Pull Request Build

Modify AppVeyor.yml to ask SonarQube to publish results on standard builds, and to integrate with pull request builds. To achieve this, extra parameters are given to the SonarQube runner when if ($env:APPVEYOR_PULL_REQUEST_NUMBER) detects a Pull Request build.

environment:
  github_auth_token:
    secure: EncryptedGitHubAuthToken
before_build:
  - nuget restore
build_script:
  - choco install "msbuild-sonarqube-runner" -y
  - ps: if ($env:APPVEYOR_PULL_REQUEST_NUMBER) { MSBuild.SonarQube.Runner.exe begin /k:"YourUniqueProjectName" /d:"sonar.host.url=https://sonarqube.com" /d:"sonar.login=YourSonarQubeToken" /d:"sonar.analysis.mode=preview" /d:"sonar.github.pullRequest=$env:APPVEYOR_PULL_REQUEST_NUMBER" /d:"sonar.github.repository=YourRepositoryUrl" /d:"sonar.github.oauth=$env:EncryptedGitHubAuthToken" }
  - ps: if (-Not $env:APPVEYOR_PULL_REQUEST_NUMBER) { MSBuild.SonarQube.Runner.exe begin /k:"YourUniqueProjectName" /d:"sonar.host.url=https://sonarqube.com" /d:"sonar.login=YourSonarQubeToken" }
  - msbuild "YourProjectName.sln"
  - MSBuild.SonarQube.Runner.exe end /d:"sonar.login=YourSonarQubeToken"

Wrapping Up

SonarQube is maturing fast and is becoming industry standard, and happily it is easy to integrate Open Source projects with the publicly available SonarQube server and AppVeyor. The SonarLint Visual Studio Plugin is fantastic at spotting problems before you commit them, and the GitHub integration allows you to control the quality of contributions.

Best regards,
Cedd Burge

Follow Cedd on Twitter: @cuddlyburger
Follow AppVeyor on Twitter: @appveyor

Creating a Signed and ZipAligned APK (for Google Play) from Xamarin

Posted on November 22, 2016

Introduction

This is a guest post by Cedd Burge, Software Developer Lead at RES.

This post is written from the point of view of someone (me) who is already proficient in C#, but was new to Xamarin, Mobile phone development, and AppVeyor.

It contains from scratch steps to create a Xamarin Android application (in Visual Studio), to build it on AppVeyor and to publish it to the Play Store. You can look at the repo I created to test this post if you get stuck.

First, install Xamarin from https://www.xamarin.com/download.

Create a new repository on GitHub

If you are new to GitHub, see this getting started guide, otherwise simply create a new repo and git clone it somewhere convenient.

Create a new Xamarin Portable Class Library (PCL) project

In my version of Visual Studio (Community 2015), this is done by clicking “File - New - Project” on the main menu and then selecting “Blank App (Xamarin.Forms Portable)” from “Templates - Visual C# - Cross-Platform”. Give it a interesting name, which I will assume to be YourAppName for the rest of this post.

Run the app!

Select the YourAppName.Droid project and run it. This should show the bare bones app in an emulator.

If you have Hyper-V enabled (maybe you use Docker), then you might get an Deployment Error when doing this. Disable Hyper-V and restart your machine to fix this.

You might also run in to compile errors due to ridiculous dependency weirdness.

Create APK file manually

To tell Google about your app, you have to make some changes to the Properties\AndroidManifest.xml file of the YourAppName.Droid project.

  • Add a package="com.yourappname" (or similar) attribute to the root manifest node. The package name must be unique on Google Play and must follow normal java package name conventions. Most people use their url in reverse (eg com.yourappname instead of yourappname.com) and stick to lower case.
  • Add an android:versionCode="1" attribute to the root manifest node. This is an integer and it must be incremented every time you upload an apk on Google Play.
  • Add an android:versionName="0.1 attribute to the root manifest node. This value can be anything you like and is displayed in Google Play.
  • Change the label attribute on the application node to YourAppName.

Visual studio has some tools to create an APK, and they seem to be in constant churn, but at the time of writing, the process is as follows.

  • Change the “Build Configuration” to “App Store”.
  • Select the YourAppName.droid project and click “Build - Archive” from the main menu.
  • The archive manager window will appear and build your app.
  • Click “Distribute”, which will pop up the Distribute window.
  • Initially you won’t have a signing identity, so click on the green plus button and fill in the details to create one.
  • Once created, double click on it and note where it is on disk (YourKeyStoreFilename from now on)
  • Click “Save As” to create an APK.

Upload the APK to Google Play

  • Create a Developer Account on Google Play Developer Console (this costs $25)
  • Click “Add New Application” and add YourAppName
  • Upload the APK that you saved in the previous step

Publish the App on Google Play (probably just to Alpha or Beta)

There are some requirements when publishing an application to Google Play, and these are likely to change, but happily google tells you what they all are. If you click on “Why can’t I publish?”, near the top right corner of the page, you will get a list of things to do.

It’s all simple stuff that can be done within the Developer Console. Some screenshots and pictures are required. If you just want to get a test version up quickly, then feel free to use mine temporarily.

There are a lot of optional things you can do as well, which can be worthwhile if you want to publish a killer app. The Google Launch Checklist, is comprehensive, but takes a long time to read.

Automate APK creation locally

When working with appveyor, it always makes sense to test on your own computer first. The feedback is immediate and you iterate very quickly. It takes a lot longer to modify the appveyor.yml file, push it and wait for a build to go through. Also, if it works locally but doesn’t work on AppVeyor, you know the problem is a configuration difference between your computer and the AppVeyor environment (eg a different version of msbuild).

Being as we are making a new version of the apk, we need to increment android:versionCode in Properties/AndroidManifest.xml.

There are some Xamarin MSBuild targets, which we can use to create a Signed and ZipAligned apk as below.

There are 2 passwords required in the command because java KeyStores can contain multiple Alias’. So the first password is to access the KeyStore, and the second one is to access the specific alias. Visual studio hides this complexity from you and assigns the same password to both places.

I do a lot of work in GIT Bash, but this statement only works in Batch (the windows command line), I think because of parameter escaping.

MSBuild "/t:SignAndroidPackage" "/p:Configuration=Release" "/p:AndroidKeyStore=true" "/p:AndroidSigningKeyAlias=YourKeyAlias" "/p:AndroidSigningKeyPass=YourKeyStorePassword" "/p:AndroidSigningKeyStore=YourKeyStoreFilename" "/p:AndroidSigningStorePass=YourKeyStorePassword" "YourAppName.csproj"

This will create com.yourappname-Signed.apk in the bin\release folder. Upload this to Google Play to make sure that everything is working properly.

Automate APK creation on AppVeyor

You will need to link an AppVeyor account to your GitHub one, so let’s do that:

  • Navigate to your repo in GitHub
  • Click “Settings” on the repo
  • Click “Integrations and services”
  • Click “Browse Directory”
  • Click “AppVeyor”
  • Click “Configure”
  • Click “Grant Access”

Now Log in to AppVeyor.com, probably using your GitHub account

  • Click “Projects”
  • Click “New Project”
  • Choose your GitHub repository and click “Add”

MSBuild needs to access your KeyStore file in order to sign the apk, so copy YourKeyStoreFilename in to the folder of YourAppName.Droid project (called YourKeyStoreLocalFilename from now on).

When we created the apk from the command line, we entered in some passwords, and we obviously can’t save these passwords to a public Git repository. Happily AppVeyor have thought of this, and you can convert passwords in to tokens that can be exposed publically.

To do this, click your user name in the top right hand corner and then click “Encrypt data” from the drop down menu. Enter YourKeyStorePassword in to “Value to encrypt” and click “Encrypt”. AppVeyor will then display a token which you can use in place of the real value.

Now that we have everything we need, add an appveyor.yml file to the root of your repository as below. Note that YourLocalKeyStoreFilename is relative to the csproj file being built (the YourAppName.Droid folder below).

environment:
  keystore-password:
    secure: DSwAr4fYt3Q35Sjob5qAN5uj # YourPassword for keystore
before_build:
  - nuget restore
build_script:
  - msbuild "/t:SignAndroidPackage" "/p:Configuration=Release" "/p:AndroidKeyStore=true" "/p:AndroidSigningKeyAlias=YourKeyAlias" "/p:AndroidSigningKeyPass=%keystore-password%" "/p:AndroidSigningKeyStore=YourLocalKeyStoreFilename" "/p:AndroidSigningStorePass=%keystore-password%"  "YourAppName.Droid\YourAppName.csproj"
artifacts:
  - path: YourAppName.Droid\bin\Release\com.yourappname-Signed.apk

Remember to update android:versionCode and then push to GitHub. This will trigger a build on AppVeyor. The build_script section will call msbuild to create the signed and zipaligned apk file, and the artifacts section will archive the apk file so we can download it later.

Go to AppVeyor.com, click on your project, click on “Artifacts”, download the apk file, and then upload it to google to check that everything has worked properly.

Conclusion

There is a lot to learn to get everything working, and I couldn’t find a single source for all of these things, but having done it once, the process is actually quite simple, and the tools and services involved are generally a pleasure to work with.

Best regards,
Cedd Burge

Follow Cedd on Twitter: @cuddlyburger
Follow AppVeyor on Twitter: @appveyor

AWS Elastic Beanstalk

Posted on November 07, 2016

Appveyor does not support AWS Elastic Beanstalk deployment out of the box right now. However it can be automated in Appveyor with help of some scripting. Here is small guide based on this support forum discussion.

  • In the root folder of your web application create text file named awsdeploy.txt.
  • Add the following to awsdeploy.txt:

    Template = ElasticBeanstalk
    Container.ApplicationHealthcheckPath = /healthcheck
    
  • Add AWSAccessKeyId as environment variable and AWSSecretKey as secure environment variable.
  • Set Package Web Applications for XCopy deployment in build stage.
  • Set the following as a deployment script:

    $packageweb = $artifacts.values | Where-Object { $_.path -like '*WebApplication1.zip' }
    $exe = "C:\Program Files (x86)\AWS Tools\Deployment Tool\awsdeploy.exe"
    &$exe -r "-DDeploymentPackage=$($packageweb.path)" "-DEnvironment.Name=MyAppWeb-test123" "-DApplication.Name=MyAppWeb123" "-DRegion=eu-west-1" "-DAWSAccessKey=$env:AWSAccessKeyId" "-DAWSSecretKey=$env:AWSSecretKey" "C:\projects\WebApplication1\awsdeploy.txt"
    

Note that this script assumes that application was already deployed at least once to Beanstalk, otherwise you need to replace -r switch with -w for single first deployment.

Here is an example YAML (only relevant parts):

environment:
  AWSAccessKeyId: AKIAIODIUCY3ETD6TEST
  AWSSecretKey:
    secure: LEvzbXpiLkWVvswonFHnAYV9ZS6fEFL3wswjTcIQ6ZXC5j1nynd6N0Bs/VFtest
build:
  publish_wap_xcopy: true
deploy_script:
  - ps: >-
    $packageweb = $artifacts.values | Where-Object { $_.path -like '*WebApplication1.zip' }
    $exe = "C:\Program Files (x86)\AWS Tools\Deployment Tool\awsdeploy.exe"
    &$exe -r "-DDeploymentPackage=$($packageweb.path)" "-DEnvironment.Name=MyAppWeb-test123" "-DApplication.Name=MyAppWeb123" "-DRegion=eu-west-1" "-DAWSAccessKey=$env:AWSAccessKeyId" "-DAWSSecretKey=$env:AWSSecretKey" "C:\projects\WebApplication1\awsdeploy.txt"

Here is an example web application folder structure:

Directory of C:\Projects\WebApplication1

09/15/2016  02:48 AM    <DIR>          .
09/15/2016  02:48 AM    <DIR>          ..
07/17/2016  12:34 PM               505 .gitattributes
07/17/2016  12:34 PM             2,858 .gitignore
09/15/2016  02:40 AM                80 awsdeploy.txt
08/30/2016  03:22 PM    <DIR>          WebApplication1
07/21/2016  06:51 PM             1,012 WebApplication1.sln

Enjoy!

The new build cache

Posted on September 28, 2016

AppVeyor runs every build on a clean virtual machine. Virtual machine state is not preserved between builds which means every build downloads sources, installs NuGet packages, Node.js modules, Ruby gems or pulls dependencies. Build cache allows you to preserve contents of selected directories and files between project builds.

AppVeyor was the first hosted CI to introduce a build cache and over the time it became a very popular build tool and important infrastructure component. There were some limitations though, such as maximum cache entry size of 500 MB and intermittent save/restore lags due to ever changing networking conditions.

Increasing requirements from larger customers running builds with “heavy” dependencies made us to re-visit cache architecture and thus the new and updated build cache was born! The new build cache lives close to build worker VMs, it’s fast and offers virtually unlimited possibilities for scale and has lower update/restore times.

Cache size

With the introduction of the new cache we are also changing the way it’s metered.

The total size of build cache is limited per account and depends on the plan:

FreeBasicProPremium
1 GB1 GB5 GB20 GB

It’s a hard quota which means the build will fail while trying to upload cache item exceeding the quota. The maximum size of a single cache entry cannot be larger than the size of cache.

Cache speed vs size

The new cache uses 7z to compress/uncompress files before transferring them to the cache storage. We chose 7z over built-in .NET compression library because it’s generally faster, produces smaller archives and works with hidden files out-of-the-box.

While compressing cache item, by default AppVeyor uses 7z with zip algorithm and compression level 1 (“Fastest”) thus producing archive faster, but with larger size (-tzip -mx=1 args). However, you can change compression behavior of 7z by providing your own command line args in APPVEYOR_CACHE_ENTRY_ZIP_ARGS environment variable. For example, to enable LZMA compression method with the highest possible compression ratio set this variable to -t7z -m0=lzma -mx=9.

Availability

The new build cache is currently in beta. It’s automatically enabled for all new accounts.

We are rolling out new cache to existing accounts in batches while observing performance. If you want participate in beta sooner or noticed any issues with the build cache please let us know.

Best regards,
AppVeyor team

Follow us on Twitter: @appveyor

Migrating build environment to RackSpace

Posted on July 16, 2016

Dear customers,

We have great news! Today we moved all open-source and most private accounts to a new build environment hosted at RackSpace.

For open-source projects that means their builds will start and run faster and private projects may notice better performance as well.

Virtual machines in the new environment have 2 CPU cores and up to 4 GB of RAM. The new public IP address for that environment is 74.205.54.20 - you may need to update your firewalls.

We are still going to maintain Google Compute Engine (GCE) environment for selected accounts and as a backup build cloud. If your private builds were previously running on GCE they will remain there.

Some open-source projects may experience issues while building on a new environment. Due to implementation differences between GCE and Hyper-V platforms we have separate build worker images for GCE and Hyper-V environments, so there might be minor discrepancies in installed software. Please report any issues you notice - your help with fixing those issues is much appreciated.

We have a good reason for this move as some customers already reported 10x performance increase!

We would love to hear your feedback!

Best regards,
AppVeyor team

Follow us on Twitter: @appveyor