But it works on my PC!

The random thoughts of Richard Fennell on technology and software development

Reprint: Migrating a TFS TFVC based team project to a Git team project - a practical example

This article was first published on the Microsoft’s UK Developers site Migrating a TFS TFVC based team project to a Git team project - a practical example on August the 15th 2014

In the past I've written on the theory behind migrating TFVC to Git with history. I've recently done this for real, as opposed to as a proof of concept, and this post documents my experiences. The requirement was to move a TFS 2013.2 Scrum Team Project using TFVC to another TFS 2013.2 Scrum Team Project using Git. The process used was as follows:

Create new team project

On the target server create a new team project using the Scrum 2013.2 process template. As we were using the same non-customised process template for both the source and the target we did not have to worry over any work item customisation. However, if you were changing process template this is where you would do any customisation required.

Adding a field to all Work Item Types

We need to be able to associate the old work item ID with the new migrated one. The TFS Integration Platform has a feature to do this automatically, but it suffers a bug. It is meant to automatically add a field for this purpose, but it actually needs it to be manually added prior to the migration.

To do this edit we need to either

  • Edit the process templates in place using the Process Template Editor Power Tool
  • Export the WIT with WITADMIN.exe and edit them in Notepad and re-import them

    In either case the field to add to ALL WORK ITEM TYPES is as follows

    <FIELD refname="TfsMigrationTool.ReflectedWorkItemId" name="ReflectedWorkItemId" type="String">     

    Once the edit is made the revised work item types need to be re-imported back into the new Team project.

    The Work Item Migration

    The actual work item migration is done using the TFS Integration Platform. This will move over all work item types from the source team project to the target team project.

    The process is as follows...

    1. Install TFS Integration Platform.
    2. Load TFS Integration Platform, as it seems it must be loaded after the team project is created, else it gets confused!
    3. Select 'Create New'.
    4. Pick the 'Team Foundation Server\WorkItemTracking' template. As we are migrating with the same process template this is OK. If you need to change field mappings use the template for field matching and look at the TFS Integration Mapper tool.
    5. Provide a sensible name for the migration. Not really needed for a one-off migration, but if testing, it is easy to end up with many test runs all of the same name, which is confusing in the logs.
    6. Pick the source server and team project as the left server.
    7. Pick the target server and team project as the right server.
    8. Accept the defaults and save to database.
    9. On the left menu select Start. The UI on this tool is not great. Avoid looking on the output tab as this seems to slow the process. Also altering the refresh time on the options for once a minute seems to help process performance. All details of actions are placed in log files so nothing is lost by these changes.
    10. The migration should complete without any issues, assuming there are no outstanding template issues that need to be resolved.

    Article image

    Add the New ID to the Changsets on the source server

    The key to this migration process to retain the links between the work items and source code checkins. This is done using the technique I outlined in the previous post i.e. editing the comments field of the changeset on the source team project prior to migration the source to add #123 style references to point to the new work items on the target server.

    To do this I used some PowerShell

            function Update-TfsCommentWithMigratedId
            This function is used as part of the migration for TFVC to Git to help retain checkin associations to work items
            This function takes two team project references and looks up changset association in the source team project, it then looks for 
            the revised work itme IT in the new team project and updates the source changeset
            .PARAMETER SourceCollectionUri
            Source TFS Collection URI
            .PARAMETER TargetCollectionUri
            Target TFS Collection URI
            .PARAMETER SourceTeamProject
            Source Team Project Name
            Update-TfsCommentWithMigratedId -SourceCollectionUri "http://server1:8080/tfs/defaultcollection" -TargetCollectionUri "http://server2:8080/tfs/defaultcollection" -SourceTeamProject "Scrumproject"
                [uri] $SourceCollectionUri, 
                [uri] $TargetCollectionUri,
                [string] $SourceTeamProject
                # get the source TPC
                $sourceTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($sourceCollectionUri)
                # get the TFVC repository
                $vcService = $sourceTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
                # get the target TPC
                $targetTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($targetCollectionUri)
                #Get the work item store
                $wiService = $targetTeamProjectCollection.GetService([Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore])
                # Find all the changesets for the selected team project on the source server
                foreach ($cs in $vcService.QueryHistory(”$/$SourceTeamProject”, [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full, [Int32]::MaxValue))
                    if ($cs.WorkItems.Count -gt 0)
                        foreach ($wi in $cs.WorkItems)
                            "Changeset {0} linked to workitem {1}" -f $cs.ChangesetId, $wi.Id
                            # find new id for each changeset on the target server
                            foreach ($newwi in $wiService.Query("select id  FROM WorkItems WHERE [TfsMigrationTool.ReflectedWorkItemId] = '" + $wi.id + "'"))
                                # if ID found update the source server if the tag has not already been added
                                # we have to esc the [ as gets treated as a regular expression
                                # we need the white space around between the [] else the TFS agent does not find the tags 
                                if ($cs.Comment -match "\[ Migrated ID #{0} \]" -f $newwi.Id)
                                    Write-Output ("New Id {0} already associated with changeset {1}" -f $newwi.Id , $cs.ChangesetId)
                                } else {
                                    Write-Output ("New Id {0} being associated with changeset {1}" -f $newwi.Id, $cs.ChangesetId )
                                    $cs.Comment += "[ Migrated ID #{0} ]" -f $newwi.Id

    With the usage

    Update-TfsCommentWithMigratedId -SourceCollectionUri "http://localhost:8080/tfs/defaultcollection" -TargetCollectionUri "http://localhost:8080/tfs/defaultcollection" -SourceTeamProject "Old team project"


    NOTE: This script is written so that it can be run multiple times, but only adds the migration entries once for any given changeset. This means both it and TFS Integration Platform can be run repeatedly on the same migration to do a staged migration e.g. get the bulk of the content over first whilst the team is using the old team project, then do a smaller migration of the later changes when the actual swap over happens.

    When this script is run expect to see output similar to:

    Article image

    You can see the impact of the script in Visual Studio Team Explorer or the TFS web client when looking at changesets in the old team project. Expect to see a changeset comment in the form shown below with new [ Migrated ID #123 ] blocks in the comment field. When 123 is the work item ID on the new team project. Also note the changeset is still associated with the old work item ID on the source server.

    Article image

    NOTE: The space after the #123 is vital. If it is not there then the TFS job agent cannot find the tag to associate the commit to a work item after the migration.

    Source code migration

    The source code can now be migrated. This is done by cloning the TFVC code to a local Git repo and then pushing it up to the new TFS Git repo using Git TF. We clone the source to a local repo in the folder localrepo with the -deep option is used to retain history.

    git tf clone http://typhoontfs:8080/tfs/defaultcollection '$/Scrum TFVC Source/Main' localrepo --deep

    NOTE: I have seen problems with this command. On larger code bases we saw the error 'TF 400732 server cancelled error' as files were said to be missing or we had no permission - neither of which was true. This problem was repeated on a number of machines, including one that had in the past managed to do the clone. It was thought the issue was on the server connectivity, but no errors were logged.

    As a work around the Git-TFS tool was used. This older community tool uses the .NET TFS API, unlike the Microsoft one which uses the Java TFS API. It was hoped this would not suffer the same issue. However it also gave TF400732 errors, but did provide a suggested command line to retry continue, which continued from where it errored.

    The command to do the clone was:

    Git tfs clone http://typhoontfs:8080/tfs/defaultcollection $/Scrum TFVC Source/main e:\repo1

    The command to continue after an error was (from within the repo folder)

    Git tfs fetch

    It should be noted that Git-TFS seems a good deal faster than Git TF, presumably due to being a native .NET client as opposed to using the Java VM.

    Once the clone was complete, we need to add the TFS Git repo as a remote target and then push the changes up to the new team project. The exact commands for this stage are shown on the target TFS server. Load the web client, go to the code section and you should see the commands needed e.g.

    git remote add origin http://typhoontfs:8080/tfs/DefaultCollection/_git/newproject
    git push -u origin --all      

    Once this stage is complete the new TFS Git repo can be used. The Git commits should have the correct historic date and work item associations as shown below. Note now that the migration id comments match the work item associations.

    Article image

    NOTE: There may be a lack in the associations being show immediately after the git push. This is because the associations are done by a background TFS job process which may take a while to catch up when there are a lot of commits. On one system I worked on this took days not hours! Be patient.

    Shared Test Steps

    At this point all work items have been moved over and their various associations with source commits are retained e.g. PBIs link to test cases and tasks. However there is a problem that any test cases that have shared steps will be pointing to the old shared set work items. As there is already an open source tool to do this update there was no immediate need to rewrite it as a PowerShell tool. So to use the open source tool use the command line:

    UpdateSharedStep.exe http://localhost:8080/tfs/defaultcollection myproject

    Test Plans and Suites

    Historically in TFS, test plans and suites are not work items (a change coming in TFS 2013.3). This means if you need these moved over too there is more PowerShell needed.

    This script moves the three test suite types as follows:

  • Static - Creates a new suite, finds the migrated IDs of the test cases on the source suite and adds them to the new suite.
  • Dynamic - Creates a new suite using the existing work item query. IMPORTANT - The query is NOT edited so may or may not work depending on what it actually contained. So these suites will need to be checked by a tester manually in all cases and their queries probably 'tweaked'.
  • Requirements - Create a new suite based on the migrated IDs of the requirement work items. This is the only test suite type where we edit the name to make it consistent with the new requirement ID not the old.

    The script is:


            function Update-TestPlanAfterMigration
            This function migrates a test plan and all its child test suites to a different team project
            This function migrates a test plan and all its child test suites to a different team project, reassign work item IDs as required
            .PARAMETER SourceCollectionUri
            Source TFS Collection URI
            .PARAMETER SourceTeamProject
            Source Team Project Name
            .PARAMETER SourceCollectionUri
            Target TFS Collection URI
            .PARAMETER SourceTeamProject
            Targe Team Project Name
            Update-TestPlanAfterMigration -SourceCollectionUri "http://server1:8080/tfs/defaultcollection" -TargetCollectionUri "http://serrver2:8080/tfs/defaultcollection"  -SourceTeamProjectName "Old project" -TargetTeamProjectName "New project"
                [uri] $SourceCollectionUri,
                [string] $SourceTeamProjectName,
                [uri] $TargetCollectionUri,
                [string] $TargetTeamProjectName
                # Get TFS connections
                $sourcetfs = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($SourceCollectionUri)
                    Write-Error "Error occurred trying to connect to project collection: $_ "
                    exit 1
                $targettfs = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($TargetCollectionUri)
                    Write-Error "Error occurred trying to connect to project collection: $_ "
                    exit 1
                # get the actual services
                $sourcetestService = $sourcetfs.GetService("Microsoft.TeamFoundation.TestManagement.Client.ITestManagementService")
                $targettestService = $targettfs.GetService("Microsoft.TeamFoundation.TestManagement.Client.ITestManagementService")
                $sourceteamproject = $sourcetestService.GetTeamProject($sourceteamprojectname)
                $targetteamproject = $targettestService.GetTeamProject($targetteamprojectname)
                # Get the work item store
                $wiService = $targettfs.GetService([Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore])
                # find all the plans in the source
                 foreach ($plan in $sourceteamproject.TestPlans.Query("Select * From TestPlan"))
                     if ($plan.RootSuite -ne $null -and $plan.RootSuite.Entries.Count -gt 0)
                        # copy the plan to the new tp
                        Write-Host("Migrating Test Plan - {0}" -f $plan.Name) 
                        $newplan = $targetteamproject.TestPlans.Create();
                        $newplan.Name = $plan.Name
                        $newplan.AreaPath = $plan.AreaPath
                        $newplan.Description = $plan.Description
                        $newplan.EndDate = $plan.EndDate
                        $newplan.StartDate = $plan.StartDate
                        $newplan.State = $plan.State
                        # we use a function as it can be recursive
                        MoveTestSuite -sourceSuite $plan.RootSuite -targetSuite $newplan.RootSuite -targetProject $targetteamproject -targetPlan $newplan -wiService $wiService
                        # and have to save the test plan again to persit the suites
            # - is missing in name so this method is not exposed when module loaded
            function MoveTestSuite
            This function migrates a test suite and all its child test suites to a different team project
            This function migrates a test suite and all its child test suites to a different team project, it is a helper function Move-TestPlan and will probably not be called directly from the command line
            .PARAMETER SourceSuite
            Source TFS test suite
            .PARAMETER TargetSuite
            Target TFS test suite
            .PARAMETER TargetPlan
            The new test plan the tests suite are being created in
            .PARAMETER targetProject
            The new team project test suite are being created in
            .PARAMETER WiService
            Work item service instance used for lookup
            Move-TestSuite -sourceSuite $plan.RootSuite -targetSuite $newplan.RootSuite -targetProject $targetteamproject -targetPlan $newplan -wiService $wiService
                foreach ($suite_entry in $sourceSuite.Entries)
                   # get the suite to a local variable to make it easier to pass around
                   $suite = $suite_entry.TestSuite
                   if ($suite -ne $null)
                       # we have to build a suite of the correct type
                       if ($suite.IsStaticTestSuite -eq $true)
                            Write-Host("    Migrating static test suite - {0}" -f $suite.Title)      
                            $newsuite = $targetProject.TestSuites.CreateStatic()
                            $newsuite.Title = $suite.Title
                            $newsuite.Description = $suite.Description 
                            $newsuite.State = $suite.State 
                            # need to add the suite to the plan else you cannot add test cases
                            $targetSuite.Entries.Add($newSuite) >$nul # sent to null as we get output
                            foreach ($test in $suite.TestCases)
                                $migratedTestCaseIds = $targetProject.TestCases.Query("Select * from [WorkItems] where [TfsMigrationTool.ReflectedWorkItemId] = '{0}'" -f $Test.Id)
                                # we assume we only get one match
                                if ($migratedTestCaseIds[0] -ne $null)
                                    Write-Host ("        Test {0} has been migrated to {1} and added to suite {2}" -f $Test.Id , $migratedTestCaseIds[0].Id, $newsuite.Title)
                                    $newsuite.Entries.Add($targetProject.TestCases.Find($migratedTestCaseIds[0].Id))  >$nul # sent to null as we get output
                       if ($suite.IsDynamicTestSuite -eq $true)
                           Write-Host("    Migrating query based test suite - {0} (Note - query may need editing)" -f $suite.Title)      
                           $newsuite = $targetProject.TestSuites.CreateDynamic()
                           $newsuite.Title = $suite.Title
                           $newsuite.Description = $suite.Description 
                           $newsuite.State = $suite.State 
                           $newsuite.Query = $suite.Query
                           $targetSuite.Entries.Add($newSuite) >$nul # sent to null as we get output
                           # we don't need to add tests as this is done dynamically
                       if ($suite.IsRequirementTestSuite -eq $true)
                           $newwis = $wiService.Query("select *  FROM WorkItems WHERE [TfsMigrationTool.ReflectedWorkItemId] = '{0}'" -f $suite.RequirementId)  
                           if ($newwis[0] -ne $null)
                                Write-Host("    Migrating requirement based test suite - {0} to new requirement ID {1}" -f $suite.Title, $newwis[0].Id )    
                                $newsuite = $targetProject.TestSuites.CreateRequirement($newwis[0])
                                $newsuite.Title = $suite.Title -replace $suite.RequirementId, $newwis[0].Id
                                $newsuite.Description = $suite.Description 
                                $newsuite.State = $suite.State 
                                $targetSuite.Entries.Add($newSuite) >$nul # sent to null as we get output
                                # we don't need to add tests as this is done dynamically
                       # look for child test cases
                       if ($suite.Entries.Count -gt 0)
                             MoveTestSuite -sourceSuite $suite -targetSuite $newsuite -targetProject $targetteamproject -targetPlan $newplan -wiService $wiService

    NOTE: This script needs PowerShell 3.0 installed. This appears to be because some the TFS assemblies are .NET 4.5 which is not supported by previous PowerShell versions. If the version is wrong the test suite migration will fail as the TestPlan (ITestPlanHelper) object will be null.

    The command run to do the migration of test plans is:

    Update-TestPlanAfterMigration -SourceCollectionUri "http://typhoontfs:8080/tfs/defaultcollection" -TargetCollectionUri "http://typhoontfs:8080/tfs/defaultcollection" -SourceTeamProjectName "Scrum TFVC Source" -TargetTeamProjectName "NewProject”

    This will create the new set of test plans and suites in addition to any already in place on the target server. It should give an output similar to:

    Article image


    So once all this is done you should have migrated TFVC team project on a new team project based on Git retaining as much history as is possible.

    Hope you find this of use.

    This article was first published on the Microsoft’s UK Developers site Migrating a TFS TFVC based team project to a Git team project - a practical example on August the 15th 2014

  • Listing all the PBIs that have no acceptance criteria

    Update 24 Aug 2014:  Changed the PowerShell to use a pipe based filter as opposed to nested foreach loops

    The TFS Scrum process template’s Product Backlog Item work item type has an acceptance criteria field. It is good practice to make sure any PBI has this field completed; however it is not always possible to enter this content when the work item is initially create i.e. before it is approved. We oftan find we add a PBI that is basically a title and add the summary and acceptance criteria as the product is planned.

    It would be really nice to have a TFS work item query that listed all the PBIs that did not have the acceptance criteria field complete. Unfortunately there is not way to check a rich text or html field is empty in TFS queries It has been requested via UserVoice, but there is no sign of it appearing in the near future.

    So we are left the TFS API to save the day, the following PowerShell function does the job, returning a list of non-completed PBI work items that have empty Acceptance Criteria.


    # Load the one we have to find, might be more than we truly need for this single function
    # but I usually keep all these functions in a single module so share the references
    $ReferenceDllLocation = "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0\"
    Add-Type -Path $ReferenceDllLocation"Microsoft.TeamFoundation.Client.dll" -ErrorAction Stop -Verbose
    Add-Type -Path $ReferenceDllLocation"Microsoft.TeamFoundation.Common.dll" -ErrorAction Stop -Verbose
    Add-Type -Path $ReferenceDllLocation"Microsoft.TeamFoundation.WorkItemTracking.Client.dll"  -ErrorAction Stop –Verbose


    function Get-TfsPBIWIthNoAcceptanceCriteria { <# .SYNOPSIS This function get the list of PBI work items that have no acceptance criteria .DESCRIPTION This function allows a check to be made that all PBIs have a set of acceptance criteria .PARAMETER CollectionUri TFS Collection URI .PARAMETER TeamProject Team Project Name .EXAMPLE Get-TfsPBIWIthNoAcceptanceCriteria -CollectionUri "http://server1:8080/tfs/defaultcollection" -TeamProject "My Project" #> Param ( [Parameter(Mandatory=$true)] [uri] $CollectionUri , [Parameter(Mandatory=$true)] [string] $TeamProject ) # get the source TPC $teamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($CollectionUri) try { $teamProjectCollection.EnsureAuthenticated() } catch { Write-Error "Error occurred trying to connect to project collection: $_ " exit 1 } #Get the work item store $wiService = $teamProjectCollection.GetService([Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore]) # find each work item, we can't check for acceptance crieria state in the query $pbi = $wiService.Query("SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = '{0}' AND [System.WorkItemType] = 'Product Backlog Item' AND [System.State] <> 'Done' ORDER BY [System.Id]" -f $teamproject) $pbi |  where-Object { $_.fields | where-object {$_.ReferenceName -eq 'Microsoft.VSTS.Common.AcceptanceCriteria' -and $_.Value -eq ""}} # Using a single piped line to filter the wi # this is equivalent to the following nested loops for those who like a more winded structure # $results = @() # foreach ($wi in $pbi) # { # foreach ($field in $wi.Fields) # { # if ($field.ReferenceName -eq 'Microsoft.VSTS.Common.AcceptanceCriteria' -and $field.Value -eq "") # { # $results += $wi # } # } # } # $results }

    Why is my TFS report not failing when I really think it should ?

    Whilst creating some custom reports for a client we hit a problem that though the reports worked on my development system and their old TFS server it failed on their new one. The error being that the Microsoft_VSTS_Scheduling_CompletedWork was an invalid column name


    Initially I suspected the problem was a warehouse reprocessing issue, but other reports worked so it could not have been that.

    It must really be the column is missing, and that sort of makes sense. On the new server the team was using the Scrum process template, the Microsoft_VSTS_Scheduling_CompletedWork  and Microsoft_VSTS_Scheduling_OriginalEstimate fields are not included in this template, the plan had been to add them to allow some analysis of estimate accuracy. This had been done on my development system, but not on the client new server. Once these fields were added to the Task work item the report leapt into life.

    The question is then, why did this work on the old TFS server? The team project on the old server being used to test the reports also did not have the customisation either. However, remember the OLAP cube for the TFS warehouse is shared between ALL team projects on a server, so as one of these other team projects was using the MSF Agile template the fields are present, hence the report worked.

    Remember that shared OLAP cube, it can trip you up over and over again

    Getting the Typemock TFS build activities to work on a TFS build agent running in interactive mode

    Windows 8 store applications need to be built on a TFS build agent running in interactive mode if you wish to run any tests. So whilst rebuilding all our build systems I decided to try to have all the agents running interactive. As we tend to run one agent per VM this was not going to be a major issue I thought.

    However, whilst testing we found that any of our builds that use the Typemock build activities failed when the build agent was running interactive, but work perfectly when it was running as a service. The error was


    Exception Message: Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\TypeMock' is denied. (type UnauthorizedAccessException)
    Exception Stack Trace:    at Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str)
       at Microsoft.Win32.RegistryKey.CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, Object registrySecurityObj, RegistryOptions registryOptions)
       at Microsoft.Win32.RegistryKey.CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck)
       at Configuration.RegistryAccess.CreateSubKey(RegistryKey reg, String subkey)
       at TypeMock.Configuration.IsolatorRegistryManager.CreateTypemockKey()
       at TypeMock.Deploy.AutoDeployTypeMock.Deploy(String rootDirectory)
       at TypeMock.CLI.Common.TypeMockRegisterInfo.Execute()
       at TypeMock.CLI.Common.TypeMockRegisterInfo..ctor()   at System.Activities.Statements.Throw.Execute(CodeActivityContext context)
       at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
       at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)


    So the issue was registry access. Irrespective of whether running interactive or as a service I used the same domain service account, which was a local admin on the build agent. The only thing that changed as the mode of running.

    After some thought I focused on UAC being the problem, but disabling this did not seem to fix the issue. I was stuck or so I thought.

    However, Robert Hancock unknown to me, was suffering a similar problem with a TFS build that included a post build event that was failing to xcopy a Biztalk custom functoid DLL to ‘Program Files’. He kept getting an ‘exit code 4 access denied’ error when the build agent was running interactive. Turns out the solution he found on Daniel Petri Blog also fixed my issues as they were both UAC/desktop interaction related.

    The solution was to create a group policy for the build agent VMs that set the following

    • User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode - Set its value to Elevate without prompting.
    • User Account Control: Detect application installations and prompt for elevation - Set its value to Disabled.
    • User Account Control: Only elevate UIAccess applications that are installed in secure locations - Set its value to Disabled.
    • User Account Control: Run all administrators in Admin Approval Mode - Set its value to Disabled.

    Once this GPO was pushed out to the build agent VMs and they were rebooted my Typemock based build and Robert Biztalk builds all worked as expected

    AddBizTalkHiddenReferences error in TFS build when installing ProjectBuildComponent via a command line setup

    I have been trying to script the installation of all the tools and SDKs we need on our TFS Build Agent VMs. This included BizTalk. A quick check on MSDN showed the setup command line parameter I need to install the build components was


    /ADDLOCAL ProjectBuildComponent

    So I ran this via my VMs setup PowerShell script, all appeared OK, but when I tried a build I got the error


    C:\Program Files (x86)\MSBuild\Microsoft\BizTalk\BizTalkCommon.targets (189): The "AddBizTalkHiddenReferences" task failed unexpectedly.
    System.ArgumentNullException: Value cannot be null.
    Parameter name: path1
       at System.IO.Path.Combine(String path1, String path2)
       at Microsoft.VisualStudio.BizTalkProject.Base.HiddenReferencesHelper.InitializeHiddenReferences()
       at Microsoft.VisualStudio.BizTalkProject.Base.HiddenReferencesHelper.get_HiddenReferences()
       at Microsoft.VisualStudio.BizTalkProject.Base.HiddenReferencesHelper.GetHiddenReferencesNotAdded(IList`1 projectReferences)
       at Microsoft.VisualStudio.BizTalkProject.BuildTasks.AddBizTalkHiddenReferences.Execute()
       at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
       at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__20.MoveNext()

    The strange thing is, if I run the BizTalk installer via the UI and select just the ‘Project Build Components’ my build did not give this error.

    On checking the Biztalk setup logs I saw that the UI based install does not run


    /ADDLOCAL ProjectBuildComponent



    /ADDLOCAL WMI,BizTalk,AdditionalApps,ProjectBuildComponent

    Once this change was made to my PowerShell script the TFS build worked OK

    TFS 2013 wizard allows you to proceed to verification even if you have no SQL admin access

    Had an interesting issue during and upgrade from TFS 2012 to 2013.2 today. The upgrade of the files proceeded as expect and the wizard ran. It picked up the correct Data Tier, found the tfs_configuration Db and I was able to fill in the service account details.

    However, when I got to the reporting section it found the report server URLs, but when it tried to find the tfs_warehouse DB it seemed to lock up, though the test of the SQL instance on the same page worked OK.

    In the end I used task manager to kill the config wizard.

    I then re-ran the wizard, switching off the reporting. This time it got to the verification step, but seemed to hang again. After a very long wait it came back with an error that the account being using to do the upgrade did not have SysAdmin rights on the SQL instance.

    On checking this turned out to be true, the user’s rights had been removed since the system was originally installed by a DBA. Once the rights were re-added the upgrade proceed perfectly; though interestingly the first page where you confirm the tfs_configuration DB now also had a check box about Always On, which it had not before.

    So the strange things was not that it failed, I would expect that, but that any of the wizard worked at all. I would have expected a failure to even find the tfs_configuration DB at the start of the wizard. Not have to wait until the verification (or reporting) step

    Why is the Team Project drop down in Release Management empty?

    The problem

    Today I found I had a problem when trying to associate a Release Management 2013.2 release pipeline with a TFS build. When I tried to select a team project the drop down for the release properties was empty.


    The strange thing was this installation of Release Management has been working OK last week. What had changed?

    I suspected an issue connecting to TFS, so in the Release Management Client’s ‘Managing TFS’ tab I tried to verify the  active TFS server linked to the Release Management. As soon as I tried this I got the following error that the TFS server was not available.


    I switched the TFS URL to HTTP from HTTPS and retired the verification and it worked. Going back to my release properties I could now see the build definitions again in the drop down. So I knew I had an SSL issue.

    The strange thing was we use SSL as out default connection, and none of our developers were complaining they could not connect via HTTPS.

    However, on checking I found on some of our build VMs there was an issue. If on those VMs I tried to connect to TFS in a browser with an HTTPS URL you got a certificate chain error.

    But stranger, on my PC, where I was running the Release Management client, I could access TFS over HTTPS from a browser and Visual Studio, but the Release Management verification failed.

    The solution

    It turns out the issue was we had an intermediate cert issue with our TFS server. An older Digicert intermediate certificate had expired over the weekend, and though the new cert was in place, and had been for a good few months since we renewed our wildcard cert, the active wildcard cert insisted on using the old version of the intermediate cert on some machines.

    As an immediate fix we ended up having to delete the old intermediate cert manually on machines showing the error. Once this was done the HTTPS connect worked again.

    Turns the real culprit was a group policy used to push out intermediate certs that are required to be trusted for some document automation we use. This old group policy was pushing the wrong version of the cert to some server VMs. Once this policy was update with the correct cert and pushed out it overwrote the problem cert and the problem went away.

    One potentially confusing thing here is that the ‘verity the TFS link’ in Release Management verifies that the Release Management server can see the TFS server, not the PC running the Release Management client. It was on the Release Management server I had to delete the dead cert (run a gpupdate /force to get the new policy). Hence why I was confused by my own PC working for Visual Studio and not for Release Management

    So I suspect the issue with drop down being empty is always going to really mean the Release Management server cannot see the TFS server for some reason, so check certs, permissions or basic network failure.

    Automating TFS Build Server deployment with SCVMM and PowerShell

    Rik recently posted about the work we have done to automatically provision TFS build agent VMs. This has come out of us having about 10 build agents on our TFS server all doing different jobs, with different SDKs etc. When we needed to increase capacity for a given build type we had a problems, could another agent run the build? what exactly was on the agent anyway? An audit of the boxes made for horrible reading, there were very inconsistent.

    So Rik automated the provision of new VMs and I looked at providing a PowerShell script to install the base tools we needed  on our build agents, knowing this list is going to change a good deal over time. After some thought, for our first attempt we picked

    • TFS itself (to provide the 2013.2 agent)
    • Visual Studio 2013.2 – you know you always end up installing it in the end to get SSDT, SDK and MSBuild targets etc.
    • WIX 3.8
    • Azure SDK 2.3 for Visual Studio 2013.2 – Virtually all our current projects need this. This is actually why we have had capacity issue on the old build agents as this was only installed on one.

    Given this basic set of tools we can build probably 70-80% of our solutions. If we use this as the base for all build boxes we can then add extra tools if required manually, but we expect we will just end up adding to the list of items installed on all our build boxes, assuming the cost of installing the extra tools/SDKs is not too high. Also we will try to auto deploy tools as part of our build templates where possible, again reducing what needs to be placed on any given build agent.

    Now the script I ended up with is a bit rough and ready but it does the job. I think in the future a move to DSC might help in this process, but I did not have time to write the custom resources now. I am assuming this script is going to be a constant work in progress as it is modified for new releases and tools.  I did make the effort to make all the steps check to see if they needed to be done, thus allowing the re-running of the script to ‘repair’ the build agent. All the writing to the event log is to make life easier for Rik when working out what is going on with the script, especially useful due to the installs from ISOs being a bit slow to run.


    # make sure we have a working event logger with a suitable source
    Create-EventLogSource -logname "Setup" -source "Create-TfsBuild"
    write-eventlog -logname Setup -source Create-TfsBuild -eventID 6 -entrytype Information -message "Create-Tfsbuild started"

    # add build service as local admin, not essential but make life easier for some projects
    Add-LocalAdmin -domain "ourdomain" -user "Tfsbuilder"

    # Install TFS, by mounting the ISO over the network and running the installer

    # The command ‘& $isodrive + ":\tfs_server.exe" /quiet’ is run

    # In the function use a while loop to see when the tfconfig.exe file appears and assume the installer is done – dirty but works

    # allow me to use write-progress to give some indication the install is done.
    Write-Output "Installing TFS server"
    Add-Tfs "\\store\ISO Images\Visual Studio\2013\2013.2\en_visual_studio_team_foundation_server_2013_with_update_2_x86_x64_dvd_4092433.iso"

    Write-Output "Configuring TFS Build"
    # clear out any old config – I found this helped avoid error when re-running script

    # A System.Diagnostics.ProcessStartInfo object is used to run the tfsconfig command with the argument "setup /uninstall:All"

    # ProcessStartInfo is used so we can capture the error output and log it to the event log if required

    # and reconfigure, again using tfsconfig, this time with the argument "unattend /configure  /unattendfile:config.ini", where

    # the config.ini has been created with tfsconfig unattend /create flag (check MSDN for the details)
    Configure-Tfs "\\store\ApplicationInstallers\TFSBuild\configsbuild.ini"

    # install vs2013, again by mounting the ISO running the installer, with a loop to check for a file appearing
    Write-Output "Installing Visual Studio"
    Add-VisualStudio "\\store\ISO Images\Visual Studio\2013\2013.2\en_visual_studio_premium_2013_with_update_2_x86_dvd_4238022.iso"

    # install wix by running the exe with the –q options via ProcessStartInfo again.
    Write-Output "Installing Wix"
    Add-Wix "\\store\ApplicationInstallers\wix\wix38.exe"

    # install azure SDK using the Web Platform Installer, checking if the Web PI is present first and installing it if needed

    # The Web PI installer lets you ask to reinstall a package, if it is it just ignores the request, so you don’t need to check if Azure is already installed
    Write-Output "Installing Azure SDK"
    Add-WebPIPackage "VWDOrVs2013AzurePack"

    write-eventlog -logname Setup -source Create-TfsBuild -eventID 7 -entrytype Information -message "Create-Tfsbuild ended"
    Write-Output "End of script"


    So for a first pass this seems to work, I now need to make sure all our build can use this cut down build agent, if they can’t do I need to modify the build template? or do I need to add more tools to our standard install? or decide if it is going to need a special agent definition?

    Once this is all done the hope is that when all the TFS build agents need patching for TFS 2013.x we will just redeploy new VMs or run a modified script to silently do the update. We shall see if this delivers on that promise

    Could not load file or assembly 'Microsoft.TeamFoundation.WorkItemTracking.Common, Version=’ when running a build on a new build agent on TFS 2013.2

    I am currently rebuilding our TFS build infrastructure, we have too many build agents that are just too different, they don’t need to be. So I am looking at a standard set of features on a build agent and the ability to auto provision new instances to make scaling easier. More on this in a future post…

    Anyway whilst testing a new agent I had a problem. A build that had worked on a previous test agent failed with the error

    Could not load file or assembly 'Microsoft.TeamFoundation.WorkItemTracking.Common, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

    The log showed it was failing to even do a get latest of the files to build, or anything on the build agent.



    Turns out the issue was the PowerShell script that installed all the TFS build components and SDKs had failed when trying to install the Azure SDK for VS2013, the Web Deploy Platform was not installed so when it tried to use the command line installer to add this package it failed.

    I fixed the issues for the Web PI tools and re-ran the command line to installed the Azure SDK and all was OK.

    Not sure why this happened, maybe a missing pre-req put on by Web PI itself was the issue. I know older versions did have a .NET 3.5 dependency. Once to keep an eye on