PrivateFunctions/Upload-ChecksToApi.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Function Upload-ChecksToApi
{
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory=$True)]
    [ValidateNotNull()]
    [Object[]] $ChecksToUpload,

    [Parameter(Mandatory=$True)]
    [ValidateNotNullOrEmpty()]
    [String] $CheckStatementRootPath
  )

  Validate-Context

  [Array]$ExistingCustomChecks = Get-DqChecks -CustomOnly

  $Imported = 0;
  Write-Verbose "Uploaden van controles naar DQ Monitor API..."

  ForEach($Check in $ChecksToUpload)
  {
    $ExistingCheck = $ExistingCustomChecks | Where-Object { $_.Name -eq $Check.check.name }
    $CheckData = [System.Text.Encoding]::UTF8.GetBytes(($Check | ConvertTo-Json))

    Try
    {
      Write-Verbose "Controle '$($Check.check.name)' uploaden..."      
      If ($ExistingCheck)
      {
        $Url = "$($DqContext.GetCheckControllerUrl())/$($ExistingCheck.id)"
        $Response = Invoke-WebRequest -UseBasicParsing -Uri $Url -Method Put -Header $DqContext.Headers -Body $CheckData
      }
      Else
      {
        $Response = Invoke-WebRequest -UseBasicParsing -Uri $DqContext.GetCheckControllerUrl() -Method Post -Header $DqContext.Headers -Body $CheckData
      }
      
      If ($ExistingCheck)
      {
        Write-Host "Controle '$($Check.Check.Name)' is geüpdatet."
      }
      Else 
      {
        Write-Host "Controle '$($Check.Check.Name)' is opgevoerd."
      }

      $Imported += 1;
    }
    Catch [System.Net.WebException]
    {
      $Stream = $_.Exception.Response.GetResponseStream()
      $StreamReader = New-Object System.IO.StreamReader($Stream)
      $StreamReader.BaseStream.Position = 0
      $ResponseBody = $StreamReader.ReadToEnd() | ConvertFrom-Json -ErrorAction SilentlyContinue
      $StreamReader.Close()
   
      $ErrorMessage = "Fout bij opvoeren/uploaden controle '$($Check.check.name)': '$($_.Exception.Message)'."
      If ($ResponseBody -and $ResponseBody.Message)
      {
        $ErrorMessage = $ErrorMessage + [char]10 + [char]13 + " + DetailedMessage: $($ResponseBody.Message)"
      }
            
      Write-Warning $ErrorMessage
    }
  }

  Write-Host "$($Imported) controle(s) opgevoerd."
}