PrivateFunctions/Get-ConnectionSettings.ps1

Function Get-ConnectionSettings
{
  [OutputType([DqConnection])]
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory=$True, position=1)]
    [String] $PortalUrl
  )
  
  Write-Verbose "Requesting connection settings from '$($PortalUrl)'..." 
  Try 
  {
    $WebResponse = Invoke-WebRequest -UseBasicParsing -Uri $PortalUrl -Method Get
  }
  Catch [System.Net.WebException]
  {
    $ResponseBody = ""
    If ($_.Exception.Response)
    {
      $Stream = $_.Exception.Response.GetResponseStream()
      $StreamReader = New-Object System.IO.StreamReader($Stream)
      $StreamReader.BaseStream.Position = 0
      $ResponseBody = $StreamReader.ReadToEnd() | ConvertFrom-Json -ErrorAction SilentlyContinue
      $StreamReader.Close()
    }

    Write-Host "Connectie naar '$($PortalUrl)' niet gelukt: '$($_.Exception.Message)'." -ForegroundColor Red
    If ($WebResponse -and $ResponseBody.Message)
    {
      Write-Warning "Gedetaileerde informatie: $($ResponseBody.Message)"
    }

    Return;
  }

  If (-not($WebResponse))
  {
    Write-Host "Connectie naar '$($PortalUrl)' niet gelukt. Controleer of de url juist is. Bij twijfel neem contact op met uw systeembeheerder of een consultant van CNS." -ForegroundColor Red
    Return;
  } 

  Write-Verbose "Searching for connection settings within webpage content..."
  $WebContent = $WebResponse.Content -replace '\n', '' -replace '\r', '' -replace '\s{2,}', ' '
  If ($WebContent -match "Application\.start\(\'(http.*)\',\s\'(http.*)\'\)")
  {
    $ApiUrl = $Matches.1
    $StsUrl = $Matches.2 

    If (-not($ApiUrl.EndsWith('/'))) { $ApiUrl = $ApiUrl + "/" }

    Write-Verbose "Connection settings found: ApiUrl: $($ApiUrl), StsUrl: $($StsUrl)."
    Return [DqConnection]::New($PortalUrl, $ApiUrl, $StsUrl)
  }
  Else 
  {
    Write-Host "Connectie naar '$($PortalUrl)' geslaagd maar geen connectiegegevens gevonden. Controleer of de url juist is. Bij twijfel neem contact op met uw systeembeheerder of een consultant van CNS." -ForegroundColor Red
    Return;
  }
}