d365ce.integrations.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = '0.3.1'

$Script:TimeSignals = @{}

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName d365ce.integrations.Import.DoDotSource -Fallback $false
if ($d365ce.integrations_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName d365ce.integrations.Import.IndividualFiles -Fallback $false
if ($d365ce.integrations_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    if ($doDotSource) { . (Resolve-Path $Path) }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText((Resolve-Path $Path)))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\preimport.ps1"
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\postimport.ps1"
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'd365ce.integrations' -Language 'en-US'


<#
    .SYNOPSIS
        Add content to a Web Request
         
    .DESCRIPTION
        Add the payload as content into the Web Request object
         
    .PARAMETER WebRequest
        The Web Request object that you want to add the content to
         
    .PARAMETER Payload
        The entire string contain the json object that you want to pass to the D365CE environment
         
    .EXAMPLE
        PS C:\> $request = New-WebRequest -Url "https://usnconeboxax1aos.cloud.onebox.dynamics.com/api/connector/ack/123456789" -Action "POST" -AuthenticationToken "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi....."
        PS C:\> Add-WebRequestContentFromFile -WebRequest $request -Payload '{"CorrelationId": "5acd8121-d4e1-4cf8-b31f-9713de3e3627", "PopReceipt": "AgAAAAMAAAAAAAAA3XpSEQ0b1QE=", "DownloadLocation": "https://usnconeboxax1aos.cloud.onebox.dynamics.com/api/connector/download/%7Bb0b5401e-56ca-4dc8-b566-84389a001236%7D?correlation-id=5acd8121-d4e1-4cf8-b31f-9713de3e3627&blob=c5fbcc38-4f1e-4a81-af27-e6684d9fc217", "IsDownLoadFileExist": True, "FileDownLoadErrorMessage": ""}'
         
        This will add the payload content to the Web Request.
        It will create a new Web Request object.
        It will use the '{"CorrelationId": "5acd8121-d4e1-4cf8-b31f-9713de3e3627", "PopReceipt": "AgAAAAMAAAAAAAAA3XpSEQ0b1QE=", "DownloadLocation": "https://usnconeboxax1aos.cloud.onebox.dynamics.com/api/connector/download/%7Bb0b5401e-56ca-4dc8-b566-84389a001236%7D?correlation-id=5acd8121-d4e1-4cf8-b31f-9713de3e3627&blob=c5fbcc38-4f1e-4a81-af27-e6684d9fc217", "IsDownLoadFileExist": True, "FileDownLoadErrorMessage": ""}' as the payload content to add to the web request.
         
    .LINK
        New-WebRequest
         
    .NOTES
        Tags: Request, DMF, Package, Packages
         
        Author: Mötz Jensen (@Splaxi)
         
#>

#
function Add-WebRequestContent {
    [CmdletBinding()]
    [OutputType()]
    param (
        [Parameter(Mandatory = $true)]
        [System.Net.WebRequest] $WebRequest,
        
        [Parameter(Mandatory = $true)]
        [string] $Payload
    )

    Write-PSFMessage -Level Verbose -Message "Parsing the payload and adding it to the web request." -Target $JobId

    try {
        $WebRequest.ContentLength = [System.Text.Encoding]::UTF8.GetByteCount($Payload)
        $stream = $WebRequest.GetRequestStream()
        $streamWriter = new-object System.IO.StreamWriter($stream)
        $streamWriter.Write([string]$Payload)
        $streamWriter.Flush()
        $streamWriter.Close()
    }
    catch {
        Write-PSFMessage -Level Critical -Message "Exception while creating WebRequest $RequestUrl" -Exception $_.Exception
        Stop-PSFFunction -Message "Stopping" -StepsUpward 1
    }
}


<#
    .SYNOPSIS
        Handle time measurement
         
    .DESCRIPTION
        Handle time measurement from when a cmdlet / function starts and ends
         
        Will write the output to the verbose stream (Write-PSFMessage -Level Verbose)
         
    .PARAMETER Start
        Switch to instruct the cmdlet that a start time registration needs to take place
         
    .PARAMETER End
        Switch to instruct the cmdlet that a time registration has come to its end and it needs to do the calculation
         
    .EXAMPLE
        PS C:\> Invoke-TimeSignal -Start
         
        This will start the time measurement for any given cmdlet / function
         
    .EXAMPLE
        PS C:\> Invoke-TimeSignal -End
         
        This will end the time measurement for any given cmdlet / function.
        The output will go into the verbose stream.
         
    .NOTES
        Author: Mötz Jensen (@Splaxi)
         
#>

function Invoke-TimeSignal {
    [CmdletBinding(DefaultParameterSetName = 'Start')]
    param (
        [Parameter(Mandatory = $true, ParameterSetName = 'Start', Position = 1 )]
        [switch] $Start,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'End', Position = 2 )]
        [switch] $End
    )

    $Time = (Get-Date)

    $Command = (Get-PSCallStack)[1].Command

    if ($Start) {
        if ($Script:TimeSignals.ContainsKey($Command)) {
            Write-PSFMessage -Level Debug -Message "The command '$Command' was already taking part in time measurement. The entry has been update with current date and time."
            $Script:TimeSignals[$Command] = $Time
        }
        else {
            $Script:TimeSignals.Add($Command, $Time)
        }
    }
    else {
        if ($Script:TimeSignals.ContainsKey($Command)) {
            $TimeSpan = New-TimeSpan -End $Time -Start (($Script:TimeSignals)[$Command])

            Write-PSFMessage -Level Verbose -Message "Total time spent inside the function was $TimeSpan" -Target $TimeSpan -FunctionName $Command -Tag "TimeSignal"
            $null = $Script:TimeSignals.Remove($Command)
        }
        else {
            Write-PSFMessage -Level Debug -Message "The command '$Command' was never started to take part in time measurement."
        }
    }
}


<#
    .SYNOPSIS
        Create batch content
         
    .DESCRIPTION
        Create a valid batch content that can be used in a HTTP batch request
         
    .PARAMETER Url
        URL / URI that the batch content should be valid for
         
        Normally the final URL / URI for the OData endpoint that the content is to be imported into
         
    .PARAMETER AuthenticationToken
        The token value that should be used to authenticate against the URL / URI endpoint
         
    .PARAMETER Payload
        The entire string contain the json object that you want to import into the D365CE environment
         
    .PARAMETER Count
        The index number that the content should be stamped with, to be valid in the entire batch request content
         
    .EXAMPLE
        PS C:\> New-BatchContent -Url "https://usnconeboxax1aos.cloud.onebox.dynamics.com/data/ExchangeRates" -AuthenticationToken "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi....." -Payload '{"@odata.type" :"Microsoft.Dynamics.DataEntities.ExchangeRate", "RateTypeName": "TEST", "FromCurrency": "DKK", "ToCurrency": "EUR", "StartDate": "2019-01-03T00:00:00Z", "Rate": 745.10, "ConversionFactor": "Hundred", "RateTypeDescription": "TEST"}' -Count 1
         
        This will create a new batch content string.
        It will use "https://usnconeboxax1aos.cloud.onebox.dynamics.com/data/ExchangeRates" as the endpoint for the content.
        It will use the "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi....." as the bearer token for the endpoint.
        It will use '{"@odata.type" :"Microsoft.Dynamics.DataEntities.ExchangeRate", "RateTypeName": "TEST", "FromCurrency": "DKK", "ToCurrency": "EUR", "StartDate": "2019-01-03T00:00:00Z", "Rate": 745.10, "ConversionFactor": "Hundred", "RateTypeDescription": "TEST"}' as the payload that needs to be included in the batch content.
        Iw will use 1 as the counter in the batch content number sequence.
         
    .NOTES
        Tags: OData, Data Entity, Batchmode, Batch, Batch Content, Multiple
         
        Author: Mötz Jensen (@Splaxi)
        Author: Rasmus Andersen (@ITRasmus)
         
#>


function New-BatchContent {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    param(
        
        [Parameter(Mandatory = $true, Position = 1)]
        [string] $Url,
        [Parameter(Mandatory = $true, Position = 2)]
        [string] $AuthenticationToken,
        [Parameter(Mandatory = $true, Position = 3)]
        [string] $Payload,
        [Parameter(Mandatory = $true, Position = 4)]
        [string] $Count
    )

    $dataBuilder = [System.Text.StringBuilder]::new()
    
    $null = $dataBuilder.AppendLine("Content-Type: application/http")
    $null = $dataBuilder.AppendLine("Content-Transfer-Encoding: binary")
    $null = $dataBuilder.AppendLine("Content-ID: $Count")
    $null = $dataBuilder.AppendLine("") #On purpose!
    $null = $dataBuilder.AppendLine("POST $Url HTTP/1.1")
    
    $null = $dataBuilder.AppendLine("OData-Version: 4.0")
    $null = $dataBuilder.AppendLine("OData-MaxVersion: 4.0")

    $null = $dataBuilder.AppendLine("Content-Type: application/json;odata.metadata=minimal")
    
    $null = $dataBuilder.AppendLine("Authorization: $AuthenticationToken")
    $null = $dataBuilder.AppendLine("") #On purpose!
    
    $null = $dataBuilder.AppendLine("$Payload")

    $dataBuilder.ToString()
}


<#
    .SYNOPSIS
        Get a new bearer token
         
    .DESCRIPTION
        Obtain a new bearer token to be used for the different HTTP request against the Dynamics 365 for Finance & Operations environment
         
    .PARAMETER Url
        URL / URI for web endpoint that you want the token to be valid for
         
    .PARAMETER ClientId
        The ClientId obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER ClientSecret
        The ClientSecret obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER Tenant
        Azure Active Directory (AAD) tenant id (Guid) that the D365CE environment is connected to, that you want to authenticate against
         
    .EXAMPLE
        PS C:\> New-BearerToken -Url "https://usnconeboxax1aos.cloud.onebox.dynamics.com" -ClientId "dea8d7a9-1602-4429-b138-111111111111" -ClientSecret "Vja/VmdxaLOPR+alkjfsadffelkjlfw234522" -Tenant "e674da86-7ee5-40a7-b777-1111111111111"
         
        This will obtain a new and valid bearer token.
        It will use "https://usnconeboxax1aos.cloud.onebox.dynamics.com" as the resource url that you want the token to be valid for.
        It will use "dea8d7a9-1602-4429-b138-111111111111" as the ClientId.
        It will use "Vja/VmdxaLOPR+alkjfsadffelkjlfw234522" as ClientSecret
        It will use "e674da86-7ee5-40a7-b777-1111111111111" as the Azure Active Directory guid.
         
    .NOTES
        Tags: OAuth, OAuth 2.0, Token, Bearer, JWT
         
        Author: Mötz Jensen (@Splaxi)
#>


function New-BearerToken {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    [OutputType()]
    param (
        [Parameter(Mandatory = $true)]
        [Alias('Uri')]
        [string] $Url,

        [Parameter(Mandatory = $true)]
        [string] $ClientId,

        [Parameter(Mandatory = $true)]
        [string] $ClientSecret,

        [Parameter(Mandatory = $true)]
        [string] $Tenant

    )

    Invoke-TimeSignal -Start

    Write-PSFMessage -Level Verbose -Message "Building request for fetching the bearer token." -Target $Var
    $bearerParms = @{
        Resource     = $Url
        ClientId     = $ClientId
        ClientSecret = $ClientSecret
    }

    $azureUri = $Script:AzureTenantOauthToken
    
    $bearerParms.AuthProviderUri = $azureUri -f $Tenant

    Write-PSFMessage -Level Verbose -Message "Fetching the bearer token." -Target ($bearerParms -join ", ")

    Invoke-ClientCredentialsGrant @bearerParms | Get-BearerToken

    Invoke-TimeSignal -End
}


<#
    .SYNOPSIS
        Create a webrequest
         
    .DESCRIPTION
        Create a webrequest with the needed details handled
         
    .PARAMETER Url
        URL / URI for web endpoint you want to work against
         
    .PARAMETER Action
        HTTP action instructing the cmdlet how to build the request
         
    .PARAMETER AuthenticationToken
        The token value that should be used to authenticate against the URL / URI endpoint
         
    .PARAMETER ContentType
        HTTP valid content type value that the cmdlet should use while building the request
         
    .EXAMPLE
        PS C:\> New-WebRequest -Url "https://usnconeboxax1aos.cloud.onebox.dynamics.com/api/connector/dequeue/123456789" -Action "GET" -AuthenticationToken "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi....."
         
        This will create a new webrequest.
        It will use the "https://usnconeboxax1aos.cloud.onebox.dynamics.com/api/connector/dequeue/123456789" as the webrequest endpoint address.
        It will use the "Get" as HTTP Action.
        It will use the "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi....." as the bearer token for the HTTP Authorization header.
         
    .NOTES
        Tags: Request, DMF, Package, Packages
         
        Author: Mötz Jensen (@Splaxi)
#>


function New-WebRequest {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    [OutputType([System.Net.WebRequest])]
    param(
        [Parameter(Mandatory = $true)]
        [string] $Url,

        [Parameter(Mandatory = $true)]
        [string] $Action,

        [Parameter(Mandatory = $true)]
        [string] $AuthenticationToken,

        [Parameter(Mandatory = $false)]
        [string] $ContentType
    )

    Write-PSFMessage -Level Debug -Message "New Request $Url, $Action, $AuthenticationToken, $ContentType "
    
    $request = [System.Net.WebRequest]::Create($Url)
    $request.Headers["Authorization"] = $AuthenticationToken
    $request.Method = $Action

    if ($Action -eq 'POST') {
        $request.ContentType = $ContentType
    }

    $request
}


<#
    .SYNOPSIS
        The multiple paths
         
    .DESCRIPTION
        Easy way to test multiple paths for public functions and have the same error handling
         
    .PARAMETER Path
        Array of paths you want to test
         
        They have to be the same type, either file/leaf or folder/container
         
    .PARAMETER Type
        Type of path you want to test
         
        Either 'Leaf' or 'Container'
         
    .PARAMETER Create
        Instruct the cmdlet to create the directory if it doesn't exist
         
    .PARAMETER ShouldNotExist
        Instruct the cmdlet to return true if the file doesn't exists
         
    .PARAMETER DontBreak
        Instruct the cmdlet NOT to break execution whenever the test condition normally should
         
    .EXAMPLE
        PS C:\> Test-PathExists "c:\temp","c:\temp\dir" -Type Container
         
        This will test if the mentioned paths (folders) exists and the current context has enough permission.
         
    .NOTES
        Author: Mötz Jensen (@splaxi)
         
#>

function Test-PathExists {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "")]
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param (
        [Parameter(Mandatory = $True, Position = 1 )]
        [string[]] $Path,

        [ValidateSet('Leaf', 'Container')]
        [Parameter(Mandatory = $True, Position = 2 )]
        [string] $Type,

        [switch] $Create,

        [switch] $ShouldNotExist,

        [switch] $DontBreak
    )
    
    $res = $false

    $arrList = New-Object -TypeName "System.Collections.ArrayList"
         
    foreach ($item in $Path) {
        Write-PSFMessage -Level Verbose -Message "Testing the path: $item" -Target $item
        $temp = Test-Path -Path $item -Type $Type

        if ((-not $temp) -and ($Create) -and ($Type -eq "Container")) {
            Write-PSFMessage -Level Verbose -Message "Creating the path: $item" -Target $item
            $null = New-Item -Path $item -ItemType Directory -Force -ErrorAction Stop
            $temp = $true
        }
        elseif ($ShouldNotExist) {
            Write-PSFMessage -Level Verbose -Message "The should NOT exists: $item" -Target $item
        }
        elseif (-not $temp ) {
            Write-PSFMessage -Level Host -Message "The <c='em'>$item</c> path wasn't found. Please ensure the path <c='em'>exists</c> and you have enough <c='em'>permission</c> to access the path."
        }
        
        $null = $arrList.Add($temp)
    }

    if ($arrList.Contains($false) -and (-not $ShouldNotExist)) {
        if (-not $DontBreak) {
            Stop-PSFFunction -Message "Stopping because of missing paths." -StepsUpward 1
        }
    }
    elseif ($arrList.Contains($true) -and $ShouldNotExist) {
        if (-not $DontBreak) {
            Stop-PSFFunction -Message "Stopping because file exists." -StepsUpward 1
        }
    }
    else {
        $res = $true
    }

    $res
}


<#
    .SYNOPSIS
        Update the broadcast message config variables
         
    .DESCRIPTION
        Update the active broadcast message config variables that the module will use as default values
         
    .EXAMPLE
        PS C:\> Update-BroadcastVariables
         
        This will update the broadcast variables.
         
    .NOTES
        Author: Mötz Jensen (@Splaxi)
#>


function Update-ODataVariables {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "")]
    [CmdletBinding()]
    [OutputType()]
    param ( )
    
    $configName = (Get-PSFConfig -FullName "d365ce.integrations.active.odata.config.name").Value

    if (([string]::IsNullOrEmpty($configName))) {
        return
    }

    $configName = $configName.ToString().ToLower()
    
    if (-not ($configName -eq "")) {
        $configHash = Get-D365CeActiveODataConfig -OutputAsHashtable
        foreach ($item in $configHash.Keys) {
            if ($item -eq "name") { continue }
            
            $name = "OData" + (Get-Culture).TextInfo.ToTitleCase($item)
        
            $valueMessage = $configHash[$item]

            if ($item -like "*client*" -and $valueMessage.Length -gt 20)
            {
                $valueMessage = $valueMessage.Substring(0,18) + "[...REDACTED...]"
            }

            Write-PSFMessage -Level Verbose -Message "$name - $valueMessage" -Target $valueMessage
            Set-Variable -Name $name -Value $configHash[$item] -Scope Script
        }
    }
}


<#
    .SYNOPSIS
        Update module variables from the configuration store
         
    .DESCRIPTION
        Update all module variables that are based on the PSF configuration store
         
    .EXAMPLE
        PS C:\> Update-PsfConfigVariables
         
        This will update all module variables based on the configuration store.
         
    .NOTES
        Tags: Variable, Variables
         
        Author: Mötz Jensen (@Splaxi)
#>


function Update-PsfConfigVariables {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]

    [CmdletBinding()]
    [OutputType()]
    param ()

    foreach ($config in Get-PSFConfig -FullName "d365ce.integrations.azure.*") {
        $item = $config.FullName.Replace("d365ce.integrations.", "")
        $name = (Get-Culture).TextInfo.ToTitleCase($item).Replace(".","")
        
        Write-PSFMessage -Level Verbose -Message "$name" -Target $($config.Value)
        Set-Variable -Name $name -Value $config.Value -Scope Script
    }
}


<#
    .SYNOPSIS
        Save an OData config
         
    .DESCRIPTION
        Adds an OData config to the configuration store
         
    .PARAMETER Name
        The logical name of the OData configuration you are about to register in the configuration store
         
    .PARAMETER Tenant
        Azure Active Directory (AAD) tenant id (Guid) that the D365CE environment is connected to, that you want to access through OData
         
    .PARAMETER Url
        URL / URI for the D365CE environment you want to access through OData
         
    .PARAMETER ClientId
        The ClientId obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER ClientSecret
        The ClientSecret obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER Temporary
        Instruct the cmdlet to only temporarily add the OData configuration in the configuration store
         
    .PARAMETER Force
        Instruct the cmdlet to overwrite the OData configuration with the same name
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Add-D365CeODataConfig -Name "UAT" -Tenant "e674da86-7ee5-40a7-b777-1111111111111" -Url "https://usnconeboxax1aos.cloud.onebox.dynamics.com" -ClientId "dea8d7a9-1602-4429-b138-111111111111" -ClientSecret "Vja/VmdxaLOPR+alkjfsadffelkjlfw234522"
         
        This will create an new OData configuration with the name "UAT".
        It will save "e674da86-7ee5-40a7-b777-1111111111111" as the Azure Active Directory guid.
        It will save "https://usnconeboxax1aos.cloud.onebox.dynamics.com" as the D365CE environment.
        It will save "dea8d7a9-1602-4429-b138-111111111111" as the ClientId.
        It will save "Vja/VmdxaLOPR+alkjfsadffelkjlfw234522" as ClientSecret.
         
    .NOTES
        Tags: Integrations, Integration, Bearer Token, Token, OData, Configuration
         
        Author: Mötz Jensen (@Splaxi)
         
    .LINK
        Get-D365CeODataConfig
         
    .LINK
        Get-D365CeActiveODataConfig
         
    .LINK
        Set-D365CeActiveODataConfig
#>


function Add-D365CeODataConfig {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [string] $Name,

        [Parameter(Mandatory = $false, Position = 1)]
        [Alias('$AADGuid')]
        [string] $Tenant,

        [Parameter(Mandatory = $false, Position = 2)]
        [Alias('Uri')]
        [string] $Url,

        [Parameter(Mandatory = $false, Position = 3)]
        [string] $ClientId,

        [Parameter(Mandatory = $false, Position = 4)]
        [string] $ClientSecret,

        [switch] $Temporary,

        [switch] $Force,

        [switch] $EnableException
    )

    Write-PSFMessage -Level Verbose -Message "Testing if configuration with the name already exists or not." -Target $configurationValue

    if (((Get-PSFConfig -FullName "d365ce.integrations.odata.*.name").Value -contains $Name) -and (-not $Force)) {
        $messageString = "An OData configuration with <c='em'>$Name</c> as name <c='em'>already exists</c>. If you want to <c='em'>overwrite</c> the current configuration, please supply the <c='em'>-Force</c> parameter."
        Write-PSFMessage -Level Host -Message $messageString
        Stop-PSFFunction -Message "Stopping because an OData configuration already exists with that name." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>','')))
        return
    }

    $configName = $Name.ToLower()

    #The ':keys' label is used to have a continue inside the switch statement itself
    :keys foreach ($key in $PSBoundParameters.Keys) {
        
        $configurationValue = $PSBoundParameters.Item($key)
        $configurationName = $key.ToLower()
        $fullConfigName = ""

        Write-PSFMessage -Level Verbose -Message "Working on $key with $configurationValue" -Target $configurationValue
        
        switch ($key) {
            "Name" {
                $fullConfigName = "d365ce.integrations.odata.$configName.name"
            }

            {"Temporary","Force" -contains $_} {
                continue keys
            }
            
            Default {
                $fullConfigName = "d365ce.integrations.odata.$configName.$configurationName"
            }
        }

        Write-PSFMessage -Level Verbose -Message "Setting $fullConfigName to $configurationValue" -Target $configurationValue
        
        Set-PSFConfig -FullName $fullConfigName -Value $configurationValue
        
        if (-not $Temporary) { Register-PSFConfig -FullName $fullConfigName -Scope UserDefault }
    }
}


<#
    .SYNOPSIS
        Enable exceptions to be thrown
         
    .DESCRIPTION
        Change the default exception behavior of the module to support throwing exceptions
         
        Useful when the module is used in an automated fashion, like inside Azure DevOps pipelines and large PowerShell scripts
         
    .EXAMPLE
        PS C:\>Enable-D365CeException
         
        This will for the rest of the current PowerShell session make sure that exceptions will be thrown.
         
    .NOTES
        Tags: Exception, Exceptions, Warning, Warnings
         
        Author: Mötz Jensen (@Splaxi)
#>


function Enable-D365CeException {
    [CmdletBinding()]
    param ()

    Write-PSFMessage -Level Verbose -Message "Enabling exception across the entire module." -Target $configurationValue

    $PSDefaultParameterValues['*:EnableException'] = $true
}


<#
    .SYNOPSIS
        Get the active OData configuration
         
    .DESCRIPTION
        Get the active OData configuration from the configuration store
         
    .PARAMETER OutputAsHashtable
        Instruct the cmdlet to return a hashtable object
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Get-D365CeActiveODataConfig
         
        This will get the active OData configuration.
         
    .NOTES
        Tags: OData, Environment, Config, Configuration, ClientId, ClientSecret
         
        Author: Mötz Jensen (@Splaxi)
         
    .LINK
        Add-D365CeODataConfig
         
    .LINK
        Get-D365CeODataConfig
         
    .LINK
        Set-D365CeActiveODataConfig
#>


function Get-D365CeActiveODataConfig {
    [CmdletBinding()]
    [OutputType()]
    param (
        [switch] $OutputAsHashtable,

        [switch] $EnableException
    )

    $configName = (Get-PSFConfig -FullName "d365ce.integrations.active.odata.config.name").Value

    if ($configName -eq "") {
        $messageString = "It looks like there <c='em'>isn't configured</c> an active OData configuration."
        Write-PSFMessage -Level Host -Message $messageString
        Stop-PSFFunction -Message "Stopping because an active OData configuration wasn't found." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>','')))
        return
    }

    Get-D365CeODataConfig -Name $configName -OutputAsHashtable:$OutputAsHashtable
}


<#
    .SYNOPSIS
        Get OData configs
         
    .DESCRIPTION
        Get all OData configuration objects from the configuration store
         
    .PARAMETER Name
        The name of the OData configuration you are looking for
         
        Default value is "*" to display all OData configs
         
    .PARAMETER OutputAsHashtable
        Instruct the cmdlet to return a hashtable object
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Get-D365CeODataConfig
         
        This will display all OData configurations on the machine.
         
    .EXAMPLE
        PS C:\> Get-D365CeODataConfig -OutputAsHashtable
         
        This will display all OData configurations on the machine.
        Every object will be output as a hashtable, for you to utilize as parameters for other cmdlets.
         
    .EXAMPLE
        PS C:\> Get-D365CeODataConfig -Name "UAT"
         
        This will display the OData configuration that is saved with the name "UAT" on the machine.
         
    .NOTES
        Tags: OData, Environment, Config, Configuration, ClientId, ClientSecret
         
        Author: Mötz Jensen (@Splaxi)
         
    .LINK
        Add-D365CeODataConfig
         
    .LINK
        Get-D365CeActiveODataConfig
         
    .LINK
        Set-D365CeActiveODataConfig
         
#>


function Get-D365CeODataConfig {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseOutputTypeCorrectly', '')]
    [CmdletBinding()]
    [OutputType('PSCustomObject')]
    param (
        [string] $Name = "*",

        [switch] $OutputAsHashtable,

        [switch] $EnableException
    )
    
    Write-PSFMessage -Level Verbose -Message "Fetch all configurations based on $Name" -Target $Name

    $Name = $Name.ToLower()
    $configurations = Get-PSFConfig -FullName "d365ce.integrations.odata.$Name.name"

    if($($configurations.count) -lt 1) {
        $messageString = "No configurations found <c='em'>with</c> the name."
        Write-PSFMessage -Level Host -Message $messageString
        Stop-PSFFunction -Message "Stopping because no configuration found." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>','')))
        return
    }

    foreach ($configName in $configurations.Value.ToLower()) {
        Write-PSFMessage -Level Verbose -Message "Working against the $configName configuration" -Target $configName
        $res = @{}

        $configName = $configName.ToLower()

        foreach ($config in Get-PSFConfig -FullName "d365ce.integrations.odata.$configName.*") {
            $propertyName = $config.FullName.ToString().Replace("d365ce.integrations.odata.$configName.", "")
            $res.$propertyName = $config.Value
        }
        
        if($OutputAsHashtable) {
            $res
        } else {
            [PSCustomObject]$res
        }
    }
}


<#
    .SYNOPSIS
        Get data from an Data Entity using OData
         
    .DESCRIPTION
        Get data from an Data Entity using the OData endpoint of the Dynamics 365 Customer Engagement
         
    .PARAMETER EntityName
        Name of the Data Entity you want to work against
         
        The parameter is Case Sensitive, because the OData endpoint in D365CE is Case Sensitive
         
        Remember that most Data Entities in a D365CE environment is named by its singular name, but most be retrieve using the plural name
         
        E.g. The account Data Entity is named "account", but can only be retrieving using "accounts"
         
        Use the XRMToolBox (https://www.xrmtoolbox.com) to help you identify the names of the Data Entities that you are looking for
         
    .PARAMETER EntitySetName
        Name of the Data Entity you want to work against
         
        The parameter is created specifically to be used when piping from Get-D365CeODataPublicEntity
         
    .PARAMETER ODataQuery
        Valid OData query string that you want to pass onto the D365 OData endpoint while retrieving data
         
        OData specific query options are:
        $filter
        $expand
        $select
        $orderby
        $top
        $skip
         
        Each option has different characteristics, which is well documented at: http://docs.oasis-open.org/odata/odata/v4.0/odata-v4.0-part2-url-conventions.html
         
    .PARAMETER Charset
        The charset / encoding that you want the cmdlet to use while fetching the odata entity
         
        The default value is: "UTF8"
         
        The charset has to be a valid http charset like: ASCII, ANSI, ISO-8859-1, UTF-8
         
    .PARAMETER Tenant
        Azure Active Directory (AAD) tenant id (Guid) that the D365CE environment is connected to, that you want to access through OData
         
    .PARAMETER Url
        URL / URI for the D365CE environment you want to access through OData
         
    .PARAMETER ClientId
        The ClientId obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER ClientSecret
        The ClientSecret obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER FullODataMeta
        Instruct the cmdlet to request all metadata to be filled into the payload
         
        Useful when you are looking for navigation properties and linked entities
         
    .PARAMETER TraverseNextLink
        Instruct the cmdlet to keep traversing the NextLink if the result set from the OData endpoint is larger than what one round trip can handle
         
        The system default is 5,000 (5 thousands) at the time of writing this feature in February 2022
         
    .PARAMETER ThrottleSeed
        Instruct the cmdlet to invoke a thread sleep between 1 and ThrottleSeed value
         
        This is to help to mitigate the 429 retry throttling on the OData endpoints
         
        It will only be available in combination with the TraverseNextLink parameter
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .PARAMETER RawOutput
        Instructs the cmdlet to include the outer structure of the response received from OData endpoint
         
        The output will still be a PSCustomObject
         
    .PARAMETER OutputAsJson
        Instructs the cmdlet to convert the output to a Json string
         
    .EXAMPLE
        PS C:\> Get-D365CeODataEntityData -EntityName accounts -ODataQuery '$top=1'
         
        This will get Accounts from the OData endpoint.
        It will use the "Account" entity, and its EntitySetName / CollectionName "accounts".
        It will get the top 1 results from the list of accounts.
         
        It will use the default OData configuration details that are stored in the configuration store.
         
    .EXAMPLE
        PS C:\> Get-D365CeODataEntityData -EntityName accounts -ODataQuery '$top=1' -FullODataMeta
         
        This will get Accounts, and include all metadata, from the OData endpoint.
        It will use the "Account" entity, and its EntitySetName / CollectionName "accounts".
        It will get the top 1 results from the list of accounts.
         
        It will use the default OData configuration details that are stored in the configuration store.
         
    .EXAMPLE
        PS C:\> Get-D365CeODataEntityData -EntityName accounts -ODataQuery '$top=10&$filter=address1_city eq ''New York'''
         
        This will get Accounts from the OData endpoint.
        It will use the Account entity, and its EntitySetName / CollectionName "Accounts".
        It will get the top 10 results from the list of accounts.
        It will filter the entities for records where the "address1_city" is 'New York'.
         
        It will use the default OData configuration details that are stored in the configuration store.
         
    .EXAMPLE
        PS C:\> Get-D365CeODataEntityData -EntityName accounts -TraverseNextLink
         
        This will get Accounts from the OData endpoint.
        It will use the Account entity, and its EntitySetName / CollectionName "Accounts".
        It will traverse all NextLink that will occur while fetching data from the OData endpoint.
         
        It will use the default OData configuration details that are stored in the configuration store.
         
    .EXAMPLE
        PS C:\> Get-D365CeODataEntityData -EntityName accounts -TraverseNextLink -ThrottleSeed 2
         
        This will get Accounts from the OData endpoint, and sleep/pause between 1 and 2 seconds for each NextLink.
        It will use the Account entity, and its EntitySetName / CollectionName "Accounts".
        It will traverse all NextLink that will occur while fetching data from the OData endpoint.
        It will use the ThrottleSeed 2 to sleep/pause the execution, to mitigate the 429 pushback from the endpoint.
         
        It will use the default OData configuration details that are stored in the configuration store.
         
    .LINK
        Add-D365CeODataConfig
         
    .LINK
        Get-D365CeActiveODataConfig
         
    .LINK
        Set-D365CeActiveODataConfig
         
    .NOTES
        The OData standard is using the $ (dollar sign) for many functions and features, which in PowerShell is normally used for variables.
         
        Whenever you want to use the different query options, you need to take the $ sign and single quotes into consideration.
         
        Example of an execution where I want the top 1 result only, with a specific city filled out.
        This example is using single quotes, to help PowerShell not trying to convert the $ into a variable.
        Because the OData standard is using single quotes as text qualifiers, we need to escape them with multiple single quotes.
         
        -ODataQuery '$top=1&$filter=address1_city eq ''New York'''
         
        Tags: OData, Data, Entity, Query
         
        Author: Mötz Jensen (@Splaxi)
         
#>


function Get-D365CeODataEntityData {
    [CmdletBinding(DefaultParameterSetName = "Default")]
    [OutputType()]
    param (
        [Parameter(Mandatory = $true, ParameterSetName = "Default")]
        [Parameter(Mandatory = $true, ParameterSetName = "NextLink")]

        [Alias('Name')]
        [string] $EntityName,

        [Parameter(Mandatory = $false)]
        [string] $ODataQuery,

        [string] $Charset = "UTF-8",
        
        [Parameter(Mandatory = $false)]
        [Alias('$AADGuid')]
        [string] $Tenant = $Script:ODataTenant,

        [Parameter(Mandatory = $false)]
        [Alias('URI')]
        [string] $URL = $Script:ODataUrl,

        [Parameter(Mandatory = $false)]
        [string] $ClientId = $Script:ODataClientId,

        [Parameter(Mandatory = $false)]
        [string] $ClientSecret = $Script:ODataClientSecret,

        [switch] $FullODataMeta,

        [Parameter(Mandatory = $true, ParameterSetName = "NextLink")]
        [switch] $TraverseNextLink,

        [Parameter(ParameterSetName = "NextLink")]
        [int] $ThrottleSeed,

        [switch] $EnableException,

        [switch] $RawOutput,

        [switch] $OutputAsJson

    )

    begin {
        $bearerParms = @{
            Url          = $Url
            ClientId     = $ClientId
            ClientSecret = $ClientSecret
            Tenant       = $Tenant
        }

        $bearer = New-BearerToken @bearerParms

        $headerParms = @{
            URL         = $URL
            BearerToken = $bearer
        }

        $headers = New-AuthorizationHeaderBearerToken @headerParms

        $apiPath = Get-PSFConfigValue -FullName "d365ce.integrations.api.version"

        $Charset = $Charset.ToLower()
        if ($Charset -like "utf*" -and $Charset -notlike "utf-*") {
            $Charset = $Charset -replace "utf", "utf-"
        }

        $SystemUrl = $URL
    }

    process {
        Invoke-TimeSignal -Start

        Write-PSFMessage -Level Verbose -Message "Building request for the OData endpoint for entity: $entity." -Target $entity

        [System.UriBuilder] $odataEndpoint = $URL
        
        $odataEndpoint.Path = "$apiPath/$EntityName"

        if (-not ([string]::IsNullOrEmpty($ODataQuery))) {
            $odataEndpoint.Query = "$ODataQuery"
        }

        if ($FullODataMeta) {
            $headers.Add("Content-Type", "application/json; odata.metadata=full; charset=$Charset")
        }
        else {
            $headers.Add("Content-Type", "application/json; charset=$Charset")
        }
        
        try {
            [System.Collections.Generic.List[System.Object]] $resArray = @()

            $localUri = $odataEndpoint.Uri.AbsoluteUri
            do {

                Write-PSFMessage -Level Verbose -Message "Executing http request against the OData endpoint." -Target $localUri
                $resGet = Invoke-RestMethod -Method Get -Uri $localUri -Headers $headers

                if (Test-PSFFunctionInterrupt) { return }

                if (-not $RawOutput) {
                    $resArray.AddRange($resGet.Value)

                    Write-PSFMessage -Level Verbose -Message "Total number of objects: $($resArray.Count)"
                }
                else {
                    $res = $resGet
                }
                
                if ($($resGet.'@odata.nextLink') -match ".*(/api/data/.*)") {
                    $localUri = "$SystemUrl$($Matches[1])"
                }

                if ($ThrottleSeed) {
                    Start-Sleep -Seconds $(Get-Random -Minimum 1 -Maximum $ThrottleSeed)
                }
            }while ($TraverseNextLink -and $resGet.'@odata.nextLink')

            if ($resArray.Count -gt 0) {
                $res = $resArray.ToArray()
            }

            if ($OutputAsJson) {
                $res | ConvertTo-Json -Depth 10
            }
            else {
                $res
            }
        }
        catch {
            $messageString = "Something went wrong while retrieving data from the OData endpoint for the entity: $EntityName"
            Write-PSFMessage -Level Host -Message $messageString -Exception $PSItem.Exception -Target $EntityName
            Stop-PSFFunction -Message "Stopping because of errors." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>', ''))) -ErrorRecord $_
            return
        }

        Invoke-TimeSignal -End
    }
}


<#
    .SYNOPSIS
        Get data from an Data Entity using OData, providing a key
         
    .DESCRIPTION
        Get data from an Data Entity, by providing a key, using the OData endpoint of the Dynamics 365 Customer Engagement
         
    .PARAMETER EntityName
        Name of the Data Entity you want to work against
         
        The parameter is Case Sensitive, because the OData endpoint in D365CE is Case Sensitive
         
        Remember that most Data Entities in a D365CE environment is named by its singular name, but most be retrieve using the plural name
         
        E.g. The builtin account Data Entity is named Account, but can only be retrieving using accounts
         
    .PARAMETER Key
        A string value that contains all needed fields and value to be a valid OData key
         
        The key needs to be a valid http encoded value and each datatype needs to handled appropriately
         
    .PARAMETER ODataQuery
        Valid OData query string that you want to pass onto the D365 OData endpoint while retrieving data
         
        OData specific query options are:
        $filter
        $expand
        $select
        $orderby
        $top
        $skip
         
        Each option has different characteristics, which is well documented at: http://docs.oasis-open.org/odata/odata/v4.0/odata-v4.0-part2-url-conventions.html
         
    .PARAMETER Charset
        The charset / encoding that you want the cmdlet to use while fetching the odata entity
         
        The default value is: "UTF8"
         
        The charset has to be a valid http charset like: ASCII, ANSI, ISO-8859-1, UTF-8
         
    .PARAMETER Tenant
        Azure Active Directory (AAD) tenant id (Guid) that the D365CE environment is connected to, that you want to access through OData
         
    .PARAMETER Url
        URL / URI for the D365CE environment you want to access through OData
         
    .PARAMETER ClientId
        The ClientId obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER ClientSecret
        The ClientSecret obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER FullODataMeta
        Instruct the cmdlet to request all metadata to be filled into the payload
         
        Useful when you are looking for navigation properties and linked entities
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .PARAMETER OutputAsJson
        Instructs the cmdlet to convert the output to a Json string
         
    .EXAMPLE
        PS C:\> Get-D365CeODataEntityDataByKey -EntityName accounts -Key "accountid=4b306dc7-ab04-4ddf-b18d-d75ffa2dba2c"
         
        This will get the specific Account from the OData endpoint.
        It will use the "Account" entity, and its EntitySetName / CollectionName "accounts".
        It will use the "accountid=4b306dc7-ab04-4ddf-b18d-d75ffa2dba2c" as key to identify the unique Account record.
         
        It will use the default OData configuration details that are stored in the configuration store.
         
    .EXAMPLE
        PS C:\> Get-D365CeODataEntityDataByKey -EntityName accounts -Key "accountid=4b306dc7-ab04-4ddf-b18d-d75ffa2dba2c" -FullODataMeta
         
        This will get the specific Account, and include all metadata, from the OData endpoint.
        It will use the "Account" entity, and its EntitySetName / CollectionName "accounts".
        It will use the "accountid=4b306dc7-ab04-4ddf-b18d-d75ffa2dba2c" as key to identify the unique Account record.
         
        It will use the default OData configuration details that are stored in the configuration store.
         
    .NOTES
        Tags: OData, Data, Entity, Query
         
        Author: Mötz Jensen (@Splaxi)
         
    .LINK
        Add-D365CeODataConfig
         
    .LINK
        Get-D365CeActiveODataConfig
         
    .LINK
        Set-D365CeActiveODataConfig
         
#>


function Get-D365CeODataEntityDataByKey {
    [CmdletBinding(DefaultParameterSetName = "Default")]
    [OutputType()]
    param (
        [Parameter(Mandatory = $true, ParameterSetName = "Specific")]
        [Alias('Name')]
        [string] $EntityName,

        [Parameter(Mandatory = $true, ParameterSetName = "Specific")]
        [string] $Key,

        [Parameter(Mandatory = $false)]
        [string] $ODataQuery,

        [string] $Charset = "UTF-8",
        
        [Parameter(Mandatory = $false)]
        [Alias('$AADGuid')]
        [string] $Tenant = $Script:ODataTenant,

        [Parameter(Mandatory = $false)]
        [Alias('URI')]
        [string] $URL = $Script:ODataUrl,

        [Parameter(Mandatory = $false)]
        [string] $ClientId = $Script:ODataClientId,

        [Parameter(Mandatory = $false)]
        [string] $ClientSecret = $Script:ODataClientSecret,

        [switch] $FullODataMeta,
        
        [switch] $EnableException,

        [switch] $OutputAsJson

    )

    begin {
        $bearerParms = @{
            Url          = $Url
            ClientId     = $ClientId
            ClientSecret = $ClientSecret
            Tenant       = $Tenant
        }

        $bearer = New-BearerToken @bearerParms

        $headerParms = @{
            URL         = $URL
            BearerToken = $bearer
        }

        $headers = New-AuthorizationHeaderBearerToken @headerParms

        $apiPath = Get-PSFConfigValue -FullName "d365ce.integrations.api.version"

        $Charset = $Charset.ToLower()
        if ($Charset -like "utf*" -and $Charset -notlike "utf-*") {
            $Charset = $Charset -replace "utf", "utf-"
        }
    }

    process {
        Invoke-TimeSignal -Start

        Write-PSFMessage -Level Verbose -Message "Building request for the OData endpoint for entity: $entity." -Target $entity

        [System.UriBuilder] $odataEndpoint = $URL
        
        $odataEndpoint.Path = "$apiPath/$EntityName($Key)"

        if (-not ([string]::IsNullOrEmpty($ODataQuery))) {
            $odataEndpoint.Query = "$ODataQuery"
        }
        
        if ($FullODataMeta) {
            $headers.Add("Content-Type", "application/json; odata.metadata=full; charset=$Charset")
        }
        else {
            $headers.Add("Content-Type", "application/json; charset=$Charset")
        }
        
        try {
            Write-PSFMessage -Level Verbose -Message "Executing http request against the OData endpoint." -Target $($odataEndpoint.Uri.AbsoluteUri)
            $res = Invoke-RestMethod -Method Get -Uri $odataEndpoint.Uri.AbsoluteUri -Headers $headers

            if ($OutputAsJson) {
                $res | ConvertTo-Json -Depth 10
            }
            else {
                $res
            }
        }
        catch [System.Net.WebException] {
            $webException = $_.Exception
            
            if (($webException.Status -eq [System.Net.WebExceptionStatus]::ProtocolError) -and (-not($null -eq $webException.Response))) {
                $resp = [System.Net.HttpWebResponse]$webException.Response

                if ($resp.StatusCode -eq [System.Net.HttpStatusCode]::NotFound) {
                    $messageString = "It seems that the OData endpoint was unable to locate the desired entity: $EntityName, based on the key: <c='em'>$key</c>. Please make sure that the key is <c='em'>valid</c> or try using the <c='em'>Get-D365CeOdataEntityData</c> cmdlet to search for the correct entity first."
                    Write-PSFMessage -Level Host -Message $messageString -Exception $PSItem.Exception -Target $EntityName
                    Stop-PSFFunction -Message "Stopping because of HTTP error 404." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>', ''))) -ErrorRecord $_
                    return
                }
                else {
                    $messageString = "Something went wrong while retrieving data from the OData endpoint for the entity: $EntityName"
                    Write-PSFMessage -Level Host -Message $messageString -Exception $PSItem.Exception -Target $EntityName
                    Stop-PSFFunction -Message "Stopping because of errors." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>', ''))) -ErrorRecord $_
                    return
                }
            }
        }
        catch {
            $messageString = "Something went wrong while retrieving data from the OData endpoint for the entity: $EntityName"
            Write-PSFMessage -Level Host -Message $messageString -Exception $PSItem.Exception -Target $EntityName
            Stop-PSFFunction -Message "Stopping because of errors." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>', ''))) -ErrorRecord $_
            return
        }

        Invoke-TimeSignal -End
    }
}


<#
    .SYNOPSIS
        Import a Data Entity into Dynamics 365 Customer Engagement
         
    .DESCRIPTION
        Imports a Data Entity, defined as a json payload, using the OData endpoint of the Dynamics 365 Customer Engagement
         
    .PARAMETER EntityName
        Name of the Data Entity you want to work against
         
        The parameter is Case Sensitive, because the OData endpoint in D365CE is Case Sensitive
         
        Remember that most Data Entities in a D365CE environment is named by its singular name, but most be retrieve using the plural name
         
        E.g. The account Data Entity is named "account", but can only be retrieving using "accounts"
         
        Use the XRMToolBox (https://www.xrmtoolbox.com) to help you identify the names of the Data Entities that you are looking for
         
    .PARAMETER Payload
        The entire string contain the json object that you want to import into the D365CE environment
         
        Remember that json is text based and can use either single quotes (') or double quotes (") as the text qualifier, so you might need to escape the different quotes in your payload before passing it in
         
    .PARAMETER PayloadCharset
        The charset / encoding that you want the cmdlet to use while importing the odata entity
         
        The default value is: "UTF8"
         
        The charset has to be a valid http charset like: ASCII, ANSI, ISO-8859-1, UTF-8
         
    .PARAMETER RefPath
        Path for working with the referene capabilities of the OData endpoint
         
        Can be used to map / assiociate an entity to another, like systemuser to a role
         
    .PARAMETER Tenant
        Azure Active Directory (AAD) tenant id (Guid) that the D365CE environment is connected to, that you want to access through OData
         
    .PARAMETER Url
        URL / URI for the D365CE environment you want to access through OData
         
    .PARAMETER ClientId
        The ClientId obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER ClientSecret
        The ClientSecret obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Import-D365CeODataEntity -EntityName "ExchangeRates" -Payload '{"@odata.type" :"Microsoft.Dynamics.DataEntities.ExchangeRate", "RateTypeName": "TEST", "FromCurrency": "DKK", "ToCurrency": "EUR", "StartDate": "2019-01-03T00:00:00Z", "Rate": 745.10, "ConversionFactor": "Hundred", "RateTypeDescription": "TEST"}'
         
        This will import a Data Entity into Dynamics 365 Customer Engagement using the OData endpoint.
        The EntityName used for the import is ExchangeRates.
        The Payload is a valid json string, containing all the needed properties.
         
    .EXAMPLE
        PS C:\> $Payload = '{"@odata.type" :"Microsoft.Dynamics.DataEntities.ExchangeRate", "RateTypeName": "TEST", "FromCurrency": "DKK", "ToCurrency": "EUR", "StartDate": "2019-01-03T00:00:00Z", "Rate": 745.10, "ConversionFactor": "Hundred", "RateTypeDescription": "TEST"}'
        PS C:\> Import-D365CeODataEntity -EntityName "ExchangeRates" -Payload $Payload
         
        This will import a Data Entity into Dynamics 365 Customer Engagement using the OData endpoint.
        First the desired json data is put into the $Payload variable.
        The EntityName used for the import is ExchangeRates.
        The $Payload variable is passed to the cmdlet.
         
    .EXAMPLE
        PS C:\> $Payload = '{"@odata.id":"[Organization URI]/api/data/v9.0/roles(00000000-0000-0000-0000-000000000001)"}'
        PS C:\> Import-D365CeODataEntity -EntityName "systemusers" -Payload $Payload -RefPath '(00000000-0000-0000-0000-000000000002)/systemuserroles_association/$ref'
         
        This will create a referene between the systemusers Data Entity and the systemuserroles in Dynamics 365 Customer Engagement using the OData endpoint.
        First the desired json data is put into the $Payload variable.
        The EntityName used for the import is systemusers.
        The RefPath '(00000000-0000-0000-0000-000000000002)/systemuserroles_association/$ref' is the systemuser "00000000-0000-0000-0000-000000000002" which you want to associate with the role "00000000-0000-0000-0000-000000000001"
        The $Payload variable is passed to the cmdlet.
         
    .NOTES
        Tags: OData, Data, Entity, Import, Upload
         
        Author: Mötz Jensen (@Splaxi)
         
        The reference parameter was implemented based on the details on this stackoverflow post: https://stackoverflow.com/questions/51238107/associate-role-to-a-user-microsoft-dynamics-crm-rest-api
         
    .LINK
        Add-D365CeODataConfig
         
    .LINK
        Get-D365CeActiveODataConfig
         
    .LINK
        Set-D365CeActiveODataConfig
#>


function Import-D365CeODataEntity {
    [CmdletBinding()]
    [OutputType()]
    param (
        [Parameter(Mandatory = $true)]
        [string] $EntityName,

        [Parameter(Mandatory = $true)]
        [Alias('Json')]
        [AllowEmptyString()]
        [string] $Payload,

        [string] $PayloadCharset = "UTF-8",

        [string] $RefPath,

        [Alias('$AADGuid')]
        [string] $Tenant = $Script:ODataTenant,

        [Alias('URI')]
        [string] $URL = $Script:ODataUrl,

        [string] $ClientId = $Script:ODataClientId,

        [string] $ClientSecret = $Script:ODataClientSecret,

        [switch] $EnableException

    )

    begin {
        $bearerParms = @{
            Url          = $Url
            ClientId     = $ClientId
            ClientSecret = $ClientSecret
            Tenant       = $Tenant
        }

        $bearer = New-BearerToken @bearerParms

        $headerParms = @{
            URL         = $URL
            BearerToken = $bearer
        }

        $headers = New-AuthorizationHeaderBearerToken @headerParms

        $apiPath = Get-PSFConfigValue -FullName "d365ce.integrations.api.version"

        $PayloadCharset = $PayloadCharset.ToLower()
        if ($PayloadCharset -like "utf*" -and $PayloadCharset -notlike "utf-*") {
            $PayloadCharset = $PayloadCharset -replace "utf", "utf-"
        }
    }

    process {
        Invoke-TimeSignal -Start

        Write-PSFMessage -Level Verbose -Message "Building request for the OData endpoint for entity named: $EntityName." -Target $EntityName
        
        [System.UriBuilder] $odataEndpoint = $URL

        $odataEndpoint.Path = "$apiPath/$EntityName" + $RefPath

        try {
            Write-PSFMessage -Level Verbose -Message "Executing http request against the OData endpoint." -Target $($odataEndpoint.Uri.AbsoluteUri)
            Invoke-RestMethod -Method POST -Uri $odataEndpoint.Uri.AbsoluteUri -Headers $headers -ContentType "application/json;charset=$PayloadCharset" -Body $Payload
        }
        catch {
            $messageString = "Something went wrong while importing data through the OData endpoint for the entity: $EntityName"
            Write-PSFMessage -Level Host -Message $messageString -Exception $PSItem.Exception -Target $EntityName
            Stop-PSFFunction -Message "Stopping because of errors." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>', ''))) -ErrorRecord $_
            return
        }

        Invoke-TimeSignal -End
    }
}


<#
    .SYNOPSIS
        Import a set of Data Entities into Dynamics 365 Customer Engagement
         
    .DESCRIPTION
        Imports a set of Data Entities, defined as a json payloads, using the OData endpoint of the Dynamics 365 Customer Engagement
         
        The entire payload will be batched into a single request against the OData endpoint
         
    .PARAMETER EntityName
        Name of the Data Entity you want to work against
         
        The parameter is Case Sensitive, because the OData endpoint in D365CE is Case Sensitive
         
        Remember that most Data Entities in a D365CE environment is named by its singular name, but most be retrieve using the plural name
         
        E.g. The account Data Entity is named "account", but can only be retrieving using "accounts"
         
        Use the XRMToolBox (https://www.xrmtoolbox.com) to help you identify the names of the Data Entities that you are looking for
         
    .PARAMETER Payload
        The entire string contain the json objects that you want to import into the D365CE environment
         
        Payload supports multiple json objects, that needs to be batched together
         
    .PARAMETER Tenant
        Azure Active Directory (AAD) tenant id (Guid) that the D365CE environment is connected to, that you want to access through OData
         
    .PARAMETER Url
        URL / URI for the D365CE environment you want to access through OData
         
    .PARAMETER ClientId
        The ClientId obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER ClientSecret
        The ClientSecret obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER RawOutput
        Instructs the cmdlet to output the raw json string directly
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Import-D365CeODataEntityBatchMode -EntityName "ExchangeRates" -Payload '{"@odata.type" :"Microsoft.Dynamics.DataEntities.ExchangeRate", "RateTypeName": "TEST", "FromCurrency": "DKK", "ToCurrency": "EUR", "StartDate": "2019-01-03T00:00:00Z", "Rate": 745.10, "ConversionFactor": "Hundred", "RateTypeDescription": "TEST"}','{"@odata.type" :"Microsoft.Dynamics.DataEntities.ExchangeRate", "RateTypeName": "TEST", "FromCurrency": "DKK", "ToCurrency": "EUR", "StartDate": "2019-01-04T00:00:00Z", "Rate": 745.10, "ConversionFactor": "Hundred", "RateTypeDescription": "TEST"}'
         
        This will import a set of Data Entities into Dynamics 365 Customer Engagement using the OData endpoint.
        The EntityName used for the import is ExchangeRates.
        The Payload is an array containing valid json strings, each containing all the needed properties.
         
    .EXAMPLE
        PS C:\> $Payload = '{"@odata.type" :"Microsoft.Dynamics.DataEntities.ExchangeRate", "RateTypeName": "TEST", "FromCurrency": "DKK", "ToCurrency": "EUR", "StartDate": "2019-01-03T00:00:00Z", "Rate": 745.10, "ConversionFactor": "Hundred", "RateTypeDescription": "TEST"}','{"@odata.type" :"Microsoft.Dynamics.DataEntities.ExchangeRate", "RateTypeName": "TEST", "FromCurrency": "DKK", "ToCurrency": "EUR", "StartDate": "2019-01-04T00:00:00Z", "Rate": 745.10, "ConversionFactor": "Hundred", "RateTypeDescription": "TEST"}'
        PS C:\> Import-D365CeODataEntityBatchMode -EntityName "ExchangeRates" -Payload $Payload
         
        This will import a set of Data Entities into Dynamics 365 Customer Engagement using the OData endpoint.
        First the desired json data is put into the $Payload variable.
        The EntityName used for the import is ExchangeRates.
        The $Payload variable is passed to the cmdlet.
         
    .NOTES
        Tags: OData, Data, Entity, Import, Upload
         
        Author: Mötz Jensen (@Splaxi)
         
    .LINK
        Add-D365CeODataConfig
         
    .LINK
        Get-D365CeActiveODataConfig
         
    .LINK
        Set-D365CeActiveODataConfig
#>


function Import-D365CeODataEntityBatchMode {
    [CmdletBinding()]
    [OutputType('System.String')]
    param (
        [Parameter(Mandatory = $true)]
        [string] $EntityName,

        [Parameter(Mandatory = $true)]
        [Alias('Json')]
        [string[]] $Payload,

        [Parameter(Mandatory = $false)]
        [Alias('$AADGuid')]
        [string] $Tenant = $Script:ODataTenant,

        [Parameter(Mandatory = $false)]
        [Alias('URI')]
        [string] $URL = $Script:ODataUrl,

        [Parameter(Mandatory = $false)]
        [string] $ClientId = $Script:ODataClientId,

        [Parameter(Mandatory = $false)]
        [string] $ClientSecret = $Script:ODataClientSecret,

        [switch] $RawOutput,

        [switch] $EnableException

    )

    begin {
        $bearerParms = @{
            Url          = $Url
            ClientId     = $ClientId
            ClientSecret = $ClientSecret
            Tenant       = $Tenant
        }

        $bearer = New-BearerToken @bearerParms

        $headerParms = @{
            URL         = $URL
            BearerToken = $bearer
        }

        $headers = New-AuthorizationHeaderBearerToken @headerParms

        $dataBuilder = [System.Text.StringBuilder]::new()

        $apiPath = Get-PSFConfigValue -FullName "d365ce.integrations.api.version"
    }

    process {
        Invoke-TimeSignal -Start

        Write-PSFMessage -Level Verbose -Message "Building batch request for the OData endpoint for entity named: $EntityName." -Target $EntityName

        $idbatch = $(New-Guid).ToString()
        $idchangeset = $(New-Guid).ToString()
    
        $batchPayload = "--batch_$idbatch"
        $changesetPayload = "--changeset_$idchangeset"
        
        $request = [System.Net.WebRequest]::Create("$URL/$apiPath/`$batch")
        $request.Headers["Authorization"] = $headers.Authorization
        $request.Method = "POST"
        $request.ContentType = "multipart/mixed; boundary=batch_$idBatch"

        $dataBuilder.Clear()

        $null = $dataBuilder.AppendLine("--$batchPayLoad ") #Space is important!
        $null = $dataBuilder.AppendLine("Content-Type: multipart/mixed; boundary=changeset_$idchangeset {0}" -f [System.Environment]::NewLine)
        $null = $dataBuilder.AppendLine("$changeSetPayLoad ") #Space is important!

        $localEntity = $EntityName
        $payLoadEnumerator = $PayLoad.GetEnumerator()
        $counter = 0
        while ($payLoadEnumerator.MoveNext()) {

            Write-PSFMessage -Level Verbose -Message "Parsing the payload for the batch request."

            $counter ++
            $localPayload = $payLoadEnumerator.Current.Trim()

            $null = $dataBuilder.Append((New-BatchContent -Url "$URL/data/$localEntity" -AuthenticationToken $bearer -Payload $LocalPayload -Count $counter))

            if ($PayLoad.Count -eq $counter) {
                $null = $dataBuilder.AppendLine("$changesetPayload--")
            }
            else {
                $null = $dataBuilder.AppendLine("$changesetPayload")
            }
        }
    
        $null = $dataBuilder.Append("$batchPayload--")
        $data = $dataBuilder.ToString()

        Write-PSFMessage -Level Debug -Message "Parsing data to debug log next."

        Write-PSFMessage -Level Debug -Message $data
        
        Add-WebRequestContent -WebRequest $request -Payload $data
    
        try {
            Write-PSFMessage -Level Verbose -Message "Executing batch http request against the OData endpoint."

            $response = $request.GetResponse()
        }
        catch {
            $messageString = "Something went wrong while importing batch data through the OData endpoint for the entity: $EntityName"
            Write-PSFMessage -Level Host -Message $messageString -Exception $PSItem.Exception -Target $EntityName
            Stop-PSFFunction -Message "Stopping because of errors." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>', ''))) -ErrorRecord $_
            return
        }
    
        #Might need to be something else than OK and Created
        if ($response.StatusCode -ne [System.Net.HttpStatusCode]::Ok -and $response.StatusCode -ne [System.Net.HttpStatusCode]::Created) {
            Write-PSFMessage -Level Verbose -Message "Status code not 'Ok' and not 'Created', Description $($response.StatusDescription)"
            Stop-PSFFunction -Message "Stopping" -Exception $([System.Exception]::new("Returned status code indicates that the request was unsuccessful."))
            return
        }

        $stream = $response.GetResponseStream()
    
        $streamReader = New-Object System.IO.StreamReader($stream)
        
        $res = $streamReader.ReadToEnd()
        $streamReader.Close();

        if ($RawOutput) {
            $res
        }
        else {
            
        }

        Invoke-TimeSignal -End
    }
}


<#
    .SYNOPSIS
        Remove a Data Entity from Dynamics 365 Customer Engagement
         
    .DESCRIPTION
        Removes a Data Entity, defined by the EntityKey, using the OData endpoint of the Dynamics 365 Customer Engagement
         
    .PARAMETER EntityName
        Name of the Data Entity you want to work against
         
        The parameter is Case Sensitive, because the OData endpoint in D365CE is Case Sensitive
         
        Remember that most Data Entities in a D365CE environment is named by its singular name, but most be retrieve using the plural name
         
        E.g. The account Data Entity is named "account", but can only be retrieving using "accounts"
         
        Use the XRMToolBox (https://www.xrmtoolbox.com) to help you identify the names of the Data Entities that you are looking for
         
    .PARAMETER Key
        The key that will select the desired Data Entity uniquely across the OData endpoint
         
        The key would most likely be made up from multiple values, but can also be a single value
         
    .PARAMETER RefPath
        Path for working with the referene capabilities of the OData endpoint
         
        Can be used to unmap / deassiociate an entity from another, like removing a systemuser from a role
         
    .PARAMETER Tenant
        Azure Active Directory (AAD) tenant id (Guid) that the D365CE environment is connected to, that you want to access through OData
         
    .PARAMETER Url
        URL / URI for the D365CE environment you want to access through OData
         
    .PARAMETER ClientId
        The ClientId obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER ClientSecret
        The ClientSecret obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Remove-D365CeODataEntity -EntityName ExchangeRates -EntityKey "RateTypeName='TEST'","FromCurrency='DKK'","ToCurrency='EUR'","StartDate=2019-01-13T12:00:00Z"
         
        This will remove a Data Entity from the D365CE environment through OData.
        It will use the ExchangeRate entity, and its EntitySetName / CollectionName "ExchangeRates".
        It will use the "RateTypeName='TEST'","FromCurrency='DKK'","ToCurrency='EUR'","StartDate=2019-01-13T12:00:00Z" as the unique key for the entity.
         
        It will use the default OData configuration details that are stored in the configuration store.
         
    .EXAMPLE
        PS C:\> Remove-D365CeODataEntity -EntityName "systemusers" -Key "00000000-0000-0000-0000-000000000002" -RefPath '/systemuserroles_association(00000000-0000-0000-0000-000000000001)/$ref'
         
        This will remove the mapping / association between 2 Data Entities from the D365CE environment through OData.
        The EntityName is "systemusers" which is the user, that you want to remove from a role.
        The Key "00000000-0000-0000-0000-000000000002" is the unique systemuserid for the user that you want to work against.
        The RefPath '/systemuserroles_association(00000000-0000-0000-0000-000000000001)/$ref' points to the unique roleid that you want to remove the user from.
         
        It will use the default OData configuration details that are stored in the configuration store.
         
    .NOTES
        Tags: OData, Data, Entity, Import, Upload
         
        Author: Mötz Jensen (@Splaxi)
         
    .LINK
        Add-D365CeODataConfig
         
    .LINK
        Get-D365CeActiveODataConfig
         
    .LINK
        Set-D365CeActiveODataConfig
#>


function Remove-D365CeODataEntity {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    [OutputType()]
    param (
        [Parameter(Mandatory = $true)]
        [string] $EntityName,

        [Parameter(Mandatory = $true)]
        [string] $Key,

        [string] $RefPath,

        [Parameter(Mandatory = $false)]
        [Alias('$AADGuid')]
        [string] $Tenant = $Script:ODataTenant,

        [Parameter(Mandatory = $false)]
        [Alias('URI')]
        [string] $URL = $Script:ODataUrl,

        [Parameter(Mandatory = $false)]
        [string] $ClientId = $Script:ODataClientId,

        [Parameter(Mandatory = $false)]
        [string] $ClientSecret = $Script:ODataClientSecret,

        [switch] $EnableException

    )

    begin {
        $bearerParms = @{
            Url     = $Url
            ClientId     = $ClientId
            ClientSecret = $ClientSecret
            Tenant = $Tenant
        }

        $bearer = New-BearerToken @bearerParms

        $headerParms = @{
            URL         = $URL
            BearerToken = $bearer
        }

        $headers = New-AuthorizationHeaderBearerToken @headerParms

        $apiPath = Get-PSFConfigValue -FullName "d365ce.integrations.api.version"
    }

    process {
        Invoke-TimeSignal -Start

        Write-PSFMessage -Level Verbose -Message "Building request for removing data entity through the OData endpoint for entity named: $EntityName." -Target $EntityName

        [System.UriBuilder] $odataEndpoint = $URL

        $odataEndpoint.Path = "$apiPath/$EntityName($Key)" + $RefPath

        try {
            Write-PSFMessage -Level Verbose -Message "Executing http request against the OData endpoint." -Target $($odataEndpoint.Uri.AbsoluteUri)
            Invoke-RestMethod -Method DELETE -Uri $odataEndpoint.Uri.AbsoluteUri -Headers $headers -ContentType 'application/json'
        }
        catch {
            $messageString = $((ConvertFrom-Json $_).Error.InnerError | ConvertTo-Json -Depth 10)
            Write-PSFMessage -Level Host -Message $messageString -Exception $PSItem.Exception -Target $EntityName
            Stop-PSFFunction -Message "Stopping because of errors." -Exception $([System.Exception]::new($messageString)) -ErrorRecord $_
            return
        }
        
        Invoke-TimeSignal -End
    }
}


<#
         
    .SYNOPSIS
        Set the active broadcast message configuration
         
    .DESCRIPTION
        Updates the current active broadcast message configuration with a new one
         
    .PARAMETER Name
        Name of the broadcast message configuration you want to load into the active broadcast message configuration
         
    .PARAMETER Temporary
        Instruct the cmdlet to only temporarily override the persisted settings in the configuration store
         
    .EXAMPLE
        PS C:\> Set-D365CeActiveBroadcastMessageConfig -Name "UAT"
         
        This will set the broadcast message configuration named "UAT" as the active configuration.
         
    .NOTES
        Tags: Servicing, Message, Users, Environment, Config, Configuration, ClientId, ClientSecret, OnPremise
         
        Author: Mötz Jensen (@Splaxi)
         
    .LINK
        Add-D365CeODataConfig
         
    .LINK
        Get-D365CeActiveODataConfig
         
    .LINK
        Get-D365CeODataConfig
         
    .LINK
        Set-D365CeActiveODataConfig
         
#>


function Set-D365CeActiveODataConfig {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    [OutputType()]
    param (
        [Parameter(Mandatory = $true, Position = 1)]
        [string] $Name,

        [switch] $Temporary
    )

    if($Name -match '\*') {
        $messageString = "The name cannot contain <c='em'>wildcard character</c>."
        Write-PSFMessage -Level Host -Message $messageString
        Stop-PSFFunction -Message "Stopping because the name contains wildcard character." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>','')))
        return
    }

    if (-not ((Get-PSFConfig -FullName "d365ce.integrations.odata.*.name").Value -contains $Name)) {
        $messageString = "An OData configuration with that name <c='em'>doesn't exists</c>."
        Write-PSFMessage -Level Host -Message $messageString
        Stop-PSFFunction -Message "Stopping because an OData message configuration with that name doesn't exists." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>','')))
        return
    }

    Set-PSFConfig -FullName "d365ce.integrations.active.odata.config.name" -Value $Name
    if (-not $Temporary) { Register-PSFConfig -FullName "d365ce.integrations.active.odata.config.name"  -Scope UserDefault }

    Update-ODataVariables
}


<#
    .SYNOPSIS
        Update a Data Entity in Dynamics 365 Customer Engagement
         
    .DESCRIPTION
        Updates a Data Entity, defined as a json payload, using the OData endpoint of the Dynamics 365 Customer Engagement platform
         
    .PARAMETER EntityName
        Name of the Data Entity you want to work against
         
        The parameter is Case Sensitive, because the OData endpoint in D365CE is Case Sensitive
         
        Remember that most Data Entities in a D365CE environment is named by its singular name, but most be retrieve using the plural name
         
        E.g. The account Data Entity is named "account", but can only be retrieving using "accounts"
         
        Use the XRMToolBox (https://www.xrmtoolbox.com) to help you identify the names of the Data Entities that you are looking for
         
    .PARAMETER Key
        The key that will select the desired Data Entity uniquely across the OData endpoint
         
        The key would most likely be made up from multiple values, but can also be a single value
         
    .PARAMETER Payload
        The entire string contain the json object that you want to import into the D365CE environment
         
        Remember that json is text based and can use either single quotes (') or double quotes (") as the text qualifier, so you might need to escape the different quotes in your payload before passing it in
         
    .PARAMETER PayloadCharset
        The charset / encoding that you want the cmdlet to use while updating the odata entity
         
        The default value is: "UTF8"
         
        The charset has to be a valid http charset like: ASCII, ANSI, ISO-8859-1, UTF-8
         
    .PARAMETER PayloadCharset
        The charset / encoding that you want the cmdlet to use while importing the odata entity
         
        The default value is: "UTF8"
         
        The charset has to be a valid http charset like: ASCII, ANSI, ISO-8859-1, UTF-8
         
    .PARAMETER Tenant
        Azure Active Directory (AAD) tenant id (Guid) that the D365CE environment is connected to, that you want to access through OData
         
    .PARAMETER Url
        URL / URI for the D365CE environment you want to access through OData
         
    .PARAMETER ClientId
        The ClientId obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER ClientSecret
        The ClientSecret obtained from the Azure Portal when you created a Registered Application
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Update-D365CeODataEntity -EntityName "accounts" -Key "accountid=4b306dc7-ab04-4ddf-b18d-d75ffa2dba2c" -Payload '{"address2_city": "Chicago"}'
         
        This will update a Data Entity in Dynamics 365 Customer Engagement using the OData endpoint.
        The EntityName used for the import is "accounts".
        It will use the "accountid=4b306dc7-ab04-4ddf-b18d-d75ffa2dba2c" as key to identify the unique Account record.
        The Payload is a valid json string, containing the needed properties that we want to update.
         
        It will use the default OData configuration details that are stored in the configuration store.
         
    .EXAMPLE
        PS C:\> $Payload = '{"address2_city": "Chicago"}'
        PS C:\> Update-D365CeODataEntity -EntityName "accounts" -Key "accountid=4b306dc7-ab04-4ddf-b18d-d75ffa2dba2c" -Payload $Payload
         
        This will update a Data Entity in Dynamics 365 Customer Engagement using the OData endpoint.
        First the desired json data is put into the $Payload variable.
        The EntityName used for the import is "accounts".
        It will use the "accountid=4b306dc7-ab04-4ddf-b18d-d75ffa2dba2c" as key to identify the unique Account record.
        The $Payload variable is passed to the cmdlet.
         
        It will use the default OData configuration details that are stored in the configuration store.
         
    .NOTES
        Tags: OData, Data, Entity, Update, Upload
         
        Author: Mötz Jensen (@Splaxi)
         
    .LINK
        Add-D365CeODataConfig
         
    .LINK
        Get-D365CeActiveODataConfig
         
    .LINK
        Set-D365CeActiveODataConfig
#>


function Update-D365CeODataEntity {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    [OutputType()]
    param (
        [Parameter(Mandatory = $true)]
        [string] $EntityName,

        [Parameter(Mandatory = $true)]
        [string] $Key,

        [Parameter(Mandatory = $true)]
        [Alias('Json')]
        [string] $Payload,

        [string] $PayloadCharset = "UTF-8",
        
        [Parameter(Mandatory = $false)]
        [Alias('$AADGuid')]
        [string] $Tenant = $Script:ODataTenant,

        [Parameter(Mandatory = $false)]
        [Alias('URI')]
        [string] $URL = $Script:ODataUrl,

        [Parameter(Mandatory = $false)]
        [string] $ClientId = $Script:ODataClientId,

        [Parameter(Mandatory = $false)]
        [string] $ClientSecret = $Script:ODataClientSecret,

        [switch] $EnableException

    )

    begin {
        $bearerParms = @{
            Url          = $Url
            ClientId     = $ClientId
            ClientSecret = $ClientSecret
            Tenant       = $Tenant
        }

        $bearer = New-BearerToken @bearerParms

        $headerParms = @{
            URL         = $URL
            BearerToken = $bearer
        }

        $headers = New-AuthorizationHeaderBearerToken @headerParms

        $apiPath = Get-PSFConfigValue -FullName "d365ce.integrations.api.version"

        $PayloadCharset = $PayloadCharset.ToLower()
        if ($PayloadCharset -like "utf*" -and $PayloadCharset -notlike "utf-*") {
            $PayloadCharset = $PayloadCharset -replace "utf", "utf-"
        }
    }

    process {
        Invoke-TimeSignal -Start

        Write-PSFMessage -Level Verbose -Message "Building request for the OData endpoint for entity named: $EntityName." -Target $EntityName

        [System.UriBuilder] $odataEndpoint = $URL
        
        $odataEndpoint.Path = "$apiPath/$EntityName($Key)"

        try {
            Write-PSFMessage -Level Verbose -Message "Executing http request against the OData endpoint." -Target $($odataEndpoint.Uri.AbsoluteUri)
            Invoke-RestMethod -Method Patch -Uri $odataEndpoint.Uri.AbsoluteUri -Headers $headers -ContentType "application/json;charset=$PayloadCharset" -Body $Payload
        }
        catch [System.Net.WebException] {
            $webException = $_.Exception
            
            if (($webException.Status -eq [System.Net.WebExceptionStatus]::ProtocolError) -and (-not($null -eq $webException.Response))) {
                $resp = [System.Net.HttpWebResponse]$webException.Response

                if ($resp.StatusCode -eq [System.Net.HttpStatusCode]::NotFound) {
                    $messageString = "It seems that the OData endpoint was unable to locate the desired entity: $EntityName, based on the key: <c='em'>$key</c>. Please make sure that the key is <c='em'>valid</c> or try using the <c='em'>Get-D365CeOdataEntityData</c> cmdlet to search for the correct entity first."
                    Write-PSFMessage -Level Host -Message $messageString -Exception $PSItem.Exception -Target $EntityName
                    Stop-PSFFunction -Message "Stopping because of HTTP error 404." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>', ''))) -ErrorRecord $_
                    return
                }
                else {
                    $messageString = "Something went wrong while updating the data entity through the OData endpoint for the entity: $EntityName"
                    Write-PSFMessage -Level Host -Message $messageString -Exception $PSItem.Exception -Target $EntityName
                    Stop-PSFFunction -Message "Stopping because of errors." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>', ''))) -ErrorRecord $_
                    return
                }
            }
        }
        catch {
            $messageString = "Something went wrong while updating the data entity through the OData endpoint for the entity: $EntityName"
            Write-PSFMessage -Level Host -Message $messageString -Exception $PSItem.Exception -Target $EntityName
            Stop-PSFFunction -Message "Stopping because of errors." -Exception $([System.Exception]::new($($messageString -replace '<[^>]+>', ''))) -ErrorRecord $_
            return
        }

        Invoke-TimeSignal -End
    }
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'd365ce.integrations' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'd365ce.integrations' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'd365ce.integrations' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

Set-PSFConfig -FullName "d365ce.integrations.azure.tenant.oauth.token" -Value "https://login.microsoftonline.com/{0}/oauth2/token" -Initialize -Description "URI / URL for the Azure Active Directory OAuth 2.0 endpoint for tokens, prepped for the tenant value to be inserted."

Set-PSFConfig -FullName "d365ce.integrations.api.version" -Value "api/data/v9.0" -Initialize -Description "Setting to select the api version of the odata endpoint to work against."


<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'd365ce.integrations.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "d365ce.integrations.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name d365ce.integrations.alcohol
#>


New-PSFLicense -Product 'd365ce.integrations' -Manufacturer 'Motz' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2019-06-27") -Text @"
Copyright (c) 2019 Motz
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@


Update-ODataVariables

Update-PsfConfigVariables
#endregion Load compiled code