TFS Release Management trigger script fails after upgrade from 2013 to 2015 (Update 3)

We are using TFS 2013 Release Management to do deployements. This works great after some modifications (the out-of-box product isn’t that good). One of the modifications is that we use a PowerShell script to trigger releases instead of the option Can trigger release from build

Our 2013 script is:

 <#
        .NOTES
        #------------------------------------------------------------------------------------------------------------
        # Date		    : 08-01-2016
        # Script name  	    : Start-ReleaseManagerBuild.ps1
        # Description  	    : Starts a build from a TFS build.
        #
        # Created by        : Ralph Jansen 
        # Extra module      : 
        # Copyright         : ©2015 all rights reserved.
        # History           : RJA 08-01-2016 Initial version
        #
        #------------------------------------------------------------------------------------------------------------
        
        .DESCRIPTION
        Starts a build from a TFS build.
        
#>

param(
    [string]$releasetemplatename = $Args[0],
    [string]$releasename = $Args[1],  
    [string]$targetstagename = $Args[2])   

cls

$username = "<domain>\<username>"
$password = "<password>"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr


$rmServer = "tfs" 

$builddefinition = [System.Uri]::EscapeDataString($env:TF_BUILD_BUILDDEFINITIONNAME)
$build = [System.Uri]::EscapeDataString($env:TF_BUILD_BUILDNUMBER)

$baseEndpointUrl = "http://$($rmServer):1000/account/releaseManagementService/_apis/releaseManagement" 
$configurationServiceUrl = "$baseEndpointUrl/ConfigurationService" 
$releaseDefinitionServiceUrl = "$baseEndpointUrl/ReleaseDefinitionService" 
$orchestratorServiceUrl = "$baseEndpointUrl/OrchestratorService" 

$escapedUsername = [System.Uri]::EscapeDataString($credentials.UserName) 
$responseXml = Invoke-RestMethod -Method Post -Credential $credentials -Uri "$configurationServiceUrl/GetUserByUserName?userName=$escapedUsername&api-version=3.0" 
$userId = $responseXml.Result.User.Id 


$body = "<Filter StatusId='2' IsDeleted='0' UserId='$userId' />" 
$responseXml = Invoke-RestMethod -Method Post -Credential $credentials -Uri "$releaseDefinitionServiceUrl/ListReleaseDefinitions?api-version=3.0" -Body $body 
$applicationVersionElt = $responseXml.ApplicationVersionList.ApplicationVersion |  
Where-Object { $_.Name -eq "$releaseTemplateName" } 
$applicationVersionId = $applicationVersionElt.Id 
$releasePathId = $applicationVersionElt.ReleasePathId 


$body = "<Filter ApplicationVersionId='$applicationVersionId' LockRequested='1' LockRequestedById='$userId' />" 
$responseXml = Invoke-RestMethod -Method Post -Credential $credentials -Uri "$configurationServiceUrl/GetApplicationVersion?api-version=3.0" -Body $body 
$componentNames = $responseXml.ApplicationVersion.Components.Component.Name 


$responseXml = Invoke-RestMethod -Method Post -Credential $credentials -Uri "$configurationServiceUrl/GetReleasePath?id=$releasePathId&api-version=3.0" 
$targetStageElt = $responseXml.ReleasePath.Stages.Stage |  
Where-Object { $_.StageTypeName -eq $targetStageName } 
$targetStageId = $targetStageElt.Id 


if ("$releaseName" -eq $null) {$releaseName = "Release: $([DateTime]::Now.ToString('G'))"}
 

$genericProperties = @( 

 """ReleaseName"":""$releaseName""", 

 """ReleaseBuild"":null", 

 """ReleaseBuildChangeset"":null", 

 """TargetStageId"":""$targetStageId""" 

) 

$componentProperties = ($componentNames | ForEach-Object { """$($_):Build"":""$build""" }) 
$json = "{" + ($genericProperties + $componentProperties -join ",`n") + "}" 

$escapedReleaseTemplateName = [System.Uri]::EscapeDataString($releaseTemplateName)
$propertyBag = [System.Uri]::EscapeDataString($json)
$releaseId = Invoke-RestMethod -Method Post -Credential $credentials -Uri "$orchestratorServiceUrl/InitiateRelease?releaseTemplateName=$escapedReleaseTemplateName&deploymentPropertyBag=$propertyBag&api-version=3.0"


$statusId = Invoke-RestMethod -Credential $credentials -Uri "$orchestratorServiceUrl/ReleaseStatus?releaseId=$releaseId"
$statusMapping = @("?", "NotStarted", "InProgress", "Released", "Stopped", "Rejected", "Abandoned" )
$statusMapping[$statusId]

PasteBIN url

Since the upgrade to 2015 U3 this script doesn’t work anymore and gave a “Permission Denied” error in the PowerShell window.

In the Event Log of the TFS server there was an entry:

Event code: 3005 
Event message: An unhandled exception has occurred. 
Event time: 11/23/2016 4:56:06 PM 
Event time (UTC): 11/23/2016 3:56:06 PM 
Event ID: 8de0118d17904ffd9031c36c4373480f 
Event sequence: 13983 
Event occurrence: 42 
Event detail code: 0 
 
Application information: 
    Application domain: /LM/W3SVC/3/ROOT-1-131243652270020196 
    Trust level: Full 
    Application Virtual Path: / 
    Application Path: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Release Management\services\ 
    Machine name: <server> 
 
Process information: 
    Process ID: 5380 
    Process name: w3wp.exe 
    Account name: <account>
 
Exception information: 
    Exception type: IncompatibleVersionException 
    Exception message: Current client version (3) is not compatible with the server version (7.0). You must upgrade the client.
   at Microsoft.TeamFoundation.Release.Services.WebRequestValidators.HttpRequestValidator.IsRequestAuthorized(HttpRequestBase httpRequestBase)
   at Microsoft.TeamFoundation.Release.Services.WebRequestValidators.ServiceModuleAuthorizer.OnAuthorize(HttpContextBase httpContextBase, Action completeRequest)
   at Microsoft.TeamFoundation.Release.Services.ServiceModule.<>c__DisplayClass0_0.<Init>b__1(Object sender, EventArgs e)
   at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

 
 
Request information: 
    Request URL: http://<server>:1000/account/releaseManagementService/_apis/releaseManagement/ReleaseDefinitionService/ListReleaseDefinitions?api-version=3.0 
    Request path: /account/releaseManagementService/_apis/releaseManagement/ReleaseDefinitionService/ListReleaseDefinitions 
    User host address: <ip address>
    User: <username>
    Is authenticated: True 
    Authentication Type: Negotiate 
    Thread account name: <username>
 
Thread information: 
    Thread ID: 8 
    Thread account name: <username>
    Is impersonating: False 
    Stack trace:    at Microsoft.TeamFoundation.Release.Services.WebRequestValidators.HttpRequestValidator.IsRequestAuthorized(HttpRequestBase httpRequestBase)
   at Microsoft.TeamFoundation.Release.Services.WebRequestValidators.ServiceModuleAuthorizer.OnAuthorize(HttpContextBase httpContextBase, Action completeRequest)
   at Microsoft.TeamFoundation.Release.Services.ServiceModule.<>c__DisplayClass0_0.<Init>b__1(Object sender, EventArgs e)
   at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
 
 
Custom event details: 

The Current client version (3) line triggered me to change this in the script to version 7.0. So the trigger script now is:


 <#
        .NOTES
        #------------------------------------------------------------------------------------------------------------
        # Date		    : 23-11-2016
        # Script name  	    : Start-ReleaseManagerBuild.ps1
        # Description  	    : Starts a build from a TFS build for Release Management 2015 (U3)
        #
        # Created by        : Ralph Jansen
        # Extra module      : 
        # Copyright         : ©2015 All rights reserved.
        # History           : RJA 08-01-2016 Initial version
        #
        #------------------------------------------------------------------------------------------------------------
        
        .DESCRIPTION
        Starts a build from a TFS build.
        
#>

param(
    [string]$releasetemplatename = $Args[0],
    [string]$releasename = $Args[1],  
    [string]$targetstagename = $Args[2])   

cls

$username = "<account>"
$password = "<password>"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr


$rmServer = "<servername>" 

$builddefinition = [System.Uri]::EscapeDataString($env:TF_BUILD_BUILDDEFINITIONNAME)
$build = [System.Uri]::EscapeDataString($env:TF_BUILD_BUILDNUMBER)

$baseEndpointUrl = "http://$($rmServer):1000/account/releaseManagementService/_apis/releaseManagement" 
$configurationServiceUrl = "$baseEndpointUrl/ConfigurationService" 
$releaseDefinitionServiceUrl = "$baseEndpointUrl/ReleaseDefinitionService" 
$orchestratorServiceUrl = "$baseEndpointUrl/OrchestratorService" 

$escapedUsername = [System.Uri]::EscapeDataString($credentials.UserName) 
$responseXml = Invoke-RestMethod -Method Post -Credential $credentials -Uri "$configurationServiceUrl/GetUserByUserName?userName=$escapedUsername&api-version=3.0" 
$userId = $responseXml.Result.User.Id 


$body = "<Filter StatusId='2' IsDeleted='0' UserId='$userId' />" 
$responseXml = Invoke-RestMethod -Method Post -Credential $credentials -Uri "$releaseDefinitionServiceUrl/ListReleaseDefinitions?api-version=7.0" -Body $body 
$applicationVersionElt = $responseXml.ApplicationVersionList.ApplicationVersion |  
Where-Object { $_.Name -eq "$releaseTemplateName" } 
$applicationVersionId = $applicationVersionElt.Id 
$releasePathId = $applicationVersionElt.ReleasePathId 


$body = "<Filter ApplicationVersionId='$applicationVersionId' LockRequested='1' LockRequestedById='$userId' />" 
$responseXml = Invoke-RestMethod -Method Post -Credential $credentials -Uri "$configurationServiceUrl/GetApplicationVersion?api-version=7.0" -Body $body 
$componentNames = $responseXml.ApplicationVersion.Components.Component.Name 


$responseXml = Invoke-RestMethod -Method Post -Credential $credentials -Uri "$configurationServiceUrl/GetReleasePath?id=$releasePathId&api-version=7.0" 
$targetStageElt = $responseXml.ReleasePath.Stages.Stage |  
Where-Object { $_.StageTypeName -eq $targetStageName } 
$targetStageId = $targetStageElt.Id 


if ("$releaseName" -eq $null) {$releaseName = "Release: $([DateTime]::Now.ToString('G'))"}
 

$genericProperties = @( 

 """ReleaseName"":""$releaseName""", 

 """ReleaseBuild"":null", 

 """ReleaseBuildChangeset"":null", 

 """TargetStageId"":""$targetStageId""" 

) 

$componentProperties = ($componentNames | ForEach-Object { """$($_):Build"":""$build""" }) 
$json = "{" + ($genericProperties + $componentProperties -join ",`n") + "}" 

$escapedReleaseTemplateName = [System.Uri]::EscapeDataString($releaseTemplateName)
$propertyBag = [System.Uri]::EscapeDataString($json)
$releaseId = Invoke-RestMethod -Method Post -Credential $credentials -Uri "$orchestratorServiceUrl/InitiateRelease?releaseTemplateName=$escapedReleaseTemplateName&deploymentPropertyBag=$propertyBag&api-version=3.0"


$statusId = Invoke-RestMethod -Credential $credentials -Uri "$orchestratorServiceUrl/ReleaseStatus?releaseId=$releaseId"
$statusMapping = @("?", "NotStarted", "InProgress", "Released", "Stopped", "Rejected", "Abandoned" )
$statusMapping[$statusId]

PasteBIN URL

Now it works fine, so changing the version is necessary to fix the script.

Advertisements
This entry was posted in Scripts and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s