Deploy WebAPI with TFS Build Definition

To deploy and Publish a WebAPI or MVC application, these 2 steps should work most of the time:

  1. Visual Studio Build
  2. Publish Build Artifacts

If you right-click on your WebAPI Project, go to “Package/Publish Web” tab and check the Items to deploy drop-down, the default value selected is:
Only files needed to run this application

The below solution produces the same output as when you build the WebAPI in Visual Studio.

This is the cue, that let me find the solution to build my WebAPI Project. The WebAPI Project consists of multiple Class Libraries with Business and DAL layers as well.

Follow the steps as below:

  • Add /p:DeployOnBuild=true /p:OutDir=”$(build.artifactstagingdirectory)\” arguments in Visual Studio Build step:
  • Change “Path to Publish” of Publish Build Artifacts task to $(build.artifactstagingdirectory)\_PublishedWebsites\ProjectName:

I’ve written another post on Creating Build Definition here.

Continuous Deployment execute database scripts with TFS

In another post, we’ve learned how we can use a Build definition and Release Management in a CI/CD pipeline. Please go through the articles if you need more information on these topics.

In this post, I’ll explain how we can use Release Definition to execute database scripts as part of the continuous deployment strategy. We will add a task to execute PowerShell script to achieve this.

Create Release definition

The task to be added is PowerShell under Utility. This task should be added before the Application files are deployed in the CD pipeline.

Create a Release definition for your Release pipeline as shown below, the path for the PowerShell script should be a shared path and the database Server is accessible.

Add the below code snippet to the PowerShell script. The script should be modified as per the requirement.

$localScriptRoot = "C:\Scripts"
$Server = "dbserver"
$scripts = Get-ChildItem $localScriptRoot | Where-Object {$_.Extension -eq ".sql"} | Sort-Object -Property Name
$qt = 0
foreach ($s in $scripts)
        Write-Host "Running Script : " $s.Name -BackgroundColor DarkGreen -ForegroundColor White
        $script = $s.FullName	
        Invoke-Sqlcmd -ServerInstance $Server -InputFile $script -username "TFSBuildUser" -password "****" -querytimeout $qt
Write-Verbose "scripts executed successfully" -verbose

The scripts to be executed are present at the location C:\Scripts with extension “.sql”. The password can be also passed as an argument to the PowerShell script and added to the Release Definition secret variable.

Use the Triggers tab to link to the required Build definition of your Project so that the Release definition is integrated with the Build pipeline. The linking can also be done using the Artifacts tab.

You can setup multiple environments using this strategy like Dev, POC and Production.