Ensure all projects use the same nuget versions

If you’re using nuget packages in Sitecore helix it’s very easy to inadvertently use different versions of nuget packages between separate helix layers. This can cause very strange and hard to diagnose issues. However with a little validation we can avoid this problem entirely before it hits your webroot. Applying a little powershell script validation method to your publish process we can get clear and concise output of what the problem is.

function NuGetPackageValidation {
	param(
		[string]$solutionPath
	)
	write-host "Beginning Nuget validation."
	$tracker = @{}
	Get-ChildItem (split-path $solutionPath) -recurse packages.config | ForEach-Object {
	  $fullFileName = $_.FullName
	  $csProjName = Split-Path (Resolve-Path "$(Split-Path $fullFileName)\*.csproj").Path -Leaf
	  [xml]$curConfigFile = Get-Content $fullFilename
	  $curConfigFile.packages.package | ForEach-Object {
		  if ($null -eq $tracker[$_.id]){
			$tracker[$_.id] = @{
				id = $_.id
				versions = @{}
				}
			$tracker[$_.id].versions[$_.version] = @{
				version = $_.version
				project = @($csProjName)
				}
			}
			elseif ($null -eq $tracker[$_.id].versions[$_.version]){
				$tracker[$_.id].versions[$_.version] = @{
					version = $_.version
					project = @($csProjName)
					}
			}else{
				$tracker[$_.id].versions[$_.version].project += $csProjName
			}
	  }
	}
	$ret = $true
	$tracker.Keys | ForEach-Object {
		if ($tracker[$_].versions.Count -gt 1){
			if ($ret){
				Write-Host "Problems found with Nuget packages, ensure that the same Nuget package versions are used across projects."
			}
			$ret = $false
			Write-Host @"
----------------------------------
  $_
----------------------------------
"@
			$versions = $tracker[$_].versions
			$versions.Keys | ForEach-Object{
				Write-Host $versions[$_].version
				$versions[$_].project | ForEach-Object {
					Write-Host "      $_"
				}
				Write-Host ""
			}
		}
	}
	return $ret
  }

You can then take the results from this function and halt the build with some detailed results for what projects are involved in the mismatch. You can expect to see results like this:

nugetValidation

Using this data, you can easily track down and fix anomalies before they become hard to diagnose problems.