$global:logfile=""
$NEWSETTING = "###CTP8###"
$BatchService = "DynamicsAxBatch"
$PrintService = "DynamicsAXPrintService"
$DataSigningCertThumbprintLegacyKey="DataAccess.DataSigningCertificateThumbprintLegacy"
$DataEncryptionCertThumbprintLegacyKey="DataAccess.DataEncryptionCertificateThumbprintLegacy"
$DataSigningCertThumbprintKey="DataAccess.DataSigningCertificateThumbprint"
$DataEncryptionCertThumbprintKey="DataAccess.DataEncryptionCertificateThumbprint"
$configEncryptor="Microsoft.Dynamics.AX.Framework.ConfigEncryptor.exe"
$InternalServiceCertThumbprints="Infrastructure.InternalServiceCertificateThumbprints"
$DataAccessAxAdminSqlPwd="DataAccess.AxAdminSqlPwd"
$DataAccessAxAdminSqlUser="DataAccess.AxAdminSqlUser"

$ErrorActionPreference="Stop"

function Initialize-Log([string]$log)
{
    if(Test-Path -Path $log)
    {
        Write-Output "Removing the existing log file '$log'."
        Remove-Item -Path $log -Force|Out-Null
    }

    Write-Output "Creating the log file '$log'."
    New-Item -Path $log -ItemType File -Force|out-null
    $global:logfile=$log
}

function Write-Log([string]$message)
{
    $datetime=Get-Date -Format "MM-dd-yyyy:HH:mm:ss"
    Add-Content -Path $global:logfile -Value "$datetime`: $message"|out-null
    Write-Output "$datetime`: $message"
}

function Log-Error([string]$error,[switch]$throw)
{
    Write-Error $error
    if($throw)
    {
        throw $error
    }
}

function Create-Backup([string]$webroot,[string]$backupdir)
{
    $orig_webconfig= Join-Path -Path $webroot -ChildPath "web.config"
    $orig_wifconfig= Join-Path -Path $webroot -ChildPath "wif.config"
    $orig_wifservicesconfig=Join-Path -Path $webroot -ChildPath "wif.services.config"

    $backup_webconfig= Join-Path -Path $backupdir -ChildPath "web.config.backup"
    $backup_wifconfig= Join-Path -Path $backupdir -ChildPath "wif.config.backup"
    $backup_wifservicesconfig=Join-Path -Path $backupdir -ChildPath "wif.services.config.backup"
    
    Copy-Item -Path $orig_webconfig -Destination $backup_webconfig -Force|out-null
    Write-Log "Copied '$orig_webconfig' to '$backup_webconfig."

    Copy-item -Path $orig_wifconfig -Destination $backup_wifconfig -Force|out-null
    Write-Log "Copied '$orig_wifconfig' to '$backup_wifconfig'."

    Copy-item -Path $orig_wifservicesconfig -Destination $backup_wifservicesconfig -Force|out-null
    Write-Log "Copied '$orig_wifservicesconfig' to '$backup_wifservicesconfig'."
}

function Upgrade-Web-Config([string]$webroot,[string]$ctp8configdir)
{
    Decrypt-Config -webroot:$webroot
    Upgrade-App-Settings -webroot:$webroot -parentdir:$ctp8configdir
    Upgrade-Bindings -webroot:$webroot -parentdir:$ctp8configdir
    Upgrade-Service-Behaviors -webroot:$webroot -parentdir:$ctp8configdir
    Update-Machine-Config-Keys -webroot:$webroot -parenrdir:$ctp8configdir

    $ctp7webconfig=Join-Path -Path $webroot -ChildPath "web.config"
    $ctp7webconfigbackup=Join-Path -Path $webroot -ChildPath "web.config.ctp7"
    $ctp8webconfig=Join-Path -Path $webroot -ChildPath "web.config.ctp8"
    $webconfig=Join-Path -Path $webroot -ChildPath "web.config"
    
    Rename-File -from:$ctp8webconfig -to:$webconfig
    Encrypt-Config -webroot:$webroot
}

function Upgrade-Wif-Config([string]$webroot,[string]$ctp8configdir)
{
    $ctp7wifconfig=Join-Path -Path $webroot -ChildPath "wif.config"
    $ctp8_wifconfig_template=Join-Path -Path $ctp8configdir -ChildPath "wif.config"
    $ctp8wifconfig=Join-Path -Path $webroot -ChildPath "wif.config.ctp8"
    Copy-Item -Path $ctp8_wifconfig_template -Destination $ctp8wifconfig -Force |out-null
    Write-Log "Copied the CTP8 wif.config template from '$ctp8_wifconfig_template' to '$ctp8wifconfig'."

    [System.Xml.XmlDocument] $ctp7xd = new-object System.Xml.XmlDocument
    $ctp7xd.Load($ctp7wifconfig)

    [System.Xml.XmlDocument] $ctp8xd = new-object System.Xml.XmlDocument
    $ctp8xd.Load($ctp8wifconfig)

    #region audienceUris
    $ctp7audienceUri=$ctp7xd.SelectSingleNode("/system.identityModel/identityConfiguration/securityTokenHandlers/securityTokenHandlerConfiguration/audienceUris/add")
    if($ctp7audienceUri -ne $null)
    {
        $ctp7audienceUriValue=$ctp7audienceUri.Attributes.GetNamedItem("value").Value
        $ctp8audienceUri=$ctp8xd.SelectSingleNode("/system.identityModel/identityConfiguration/securityTokenHandlers/securityTokenHandlerConfiguration/audienceUris/add")
        $ctp8audienceUri.Attributes.GetNamedItem("value").Value=$ctp7audienceUriValue
        Write-Log "setting the audienceUri value to '$ctp7audienceUriValue'."
    }

    $ctp8xd.Save($ctp8wifconfig)
    #endregion

    #region authority
    $ctp8IssuerNameRegistry=$ctp8xd.SelectSingleNode("/system.identityModel/identityConfiguration/securityTokenHandlers/securityTokenHandlerConfiguration/issuerNameRegistry")
    $ctp7AuthorityNameNodes=$ctp7xd.SelectNodes("/system.identityModel/identityConfiguration/securityTokenHandlers/securityTokenHandlerConfiguration/issuerNameRegistry/authority/@name")
    $ctp8AuthorityNameNodes=$ctp8xd.SelectNodes("/system.identityModel/identityConfiguration/securityTokenHandlers/securityTokenHandlerConfiguration/issuerNameRegistry/authority/@name")

    $ctp7AuthorityNames=@()
    $ctp8AuthorityNames=@()

    foreach($authority in $ctp7AuthorityNameNodes)
    {
        $ctp7AuthorityNames += $authority.'#text'
    }

    foreach($authority in $ctp8AuthorityNameNodes)
    {
        $ctp8AuthorityNames += $authority.'#text'
    }

    $ctp7UniqueAuthorities=$ctp7AuthorityNames|?{-not ($ctp8AuthorityNames -contains $_)}
    $intersection=$ctp7AuthorityNames|?{($ctp8AuthorityNames -contains $_)}
    
    # process the intersections
    foreach($name in $intersection)
    {
        $ctp7authority=$ctp7xd.SelectSingleNode("/system.identityModel/identityConfiguration/securityTokenHandlers/securityTokenHandlerConfiguration/issuerNameRegistry/authority[@name='$name']")
        $ctp8authoritykeys=$ctp8xd.SelectNodes("/system.identityModel/identityConfiguration/securityTokenHandlers/securityTokenHandlerConfiguration/issuerNameRegistry/authority[@name='$name']/keys")

        # remove the CTP8 authority keys
        $ctp8authoritykeys.RemoveAll()|out-null

        # get the thumbprint value(s) from the ctp7 wif.config and update it in the ctp8 wif.config
        $ctp7authoritykeys=$ctp7xd.SelectSingleNode("/system.identityModel/identityConfiguration/securityTokenHandlers/securityTokenHandlerConfiguration/issuerNameRegistry/authority[@name='$name']/keys/add")

        # add the authority keys from the CTP7 wif.config
        foreach($authoritykey in $ctp7authoritykeys)
        {
            $thumbprint=$authoritykey.Attributes.GetNamedItem("thumbprint").Value
            $newauthority = $ctp8xd.CreateElement("add")
            $newauthority.SetAttribute("thumbprint",$thumbprint)|out-null
            $ctp8authoritykeys.AppendChild($newauthority)|out-null
            Write-Log "Added an authority key to authority '$name' with thumbprint '$thumbprint'."
        }
    }

    # add the ctp7 only authorities to ctp8
    foreach($name in $ctp7UniqueAuthorities)
    {
        $ctp7Authority=$ctp7xd.SelectSingleNode("/system.identityModel/identityConfiguration/securityTokenHandlers/securityTokenHandlerConfiguration/issuerNameRegistry/authority[@name='$name']")
        $newauthority=$ctp8xd.CreateElement("authority")
        $newauthority.SetAttribute("name",$ctp7Authority.Attributes.GetNamedItem("name").Value)|out-null
        $newkeys=$ctp8xd.CreateElement("keys")
        $newValidIssuers=$ctp8xd.CreateElement("validIssuers")

        # add thumbprints
        foreach($thumbprint in $ctp7Authority.keys.add)
        {
            $newthumbprint = $ctp8xd.CreateElement("add")
            $newthumbprint.SetAttribute("thumbprint",$thumbprint.Attributes.GetNamedItem("thumbprint").value)|out-null
            $newkeys.AppendChild($newthumbprint)|out-null
        }

        # add valid issuers
        foreach($validIssuer in $ctp7Authority.validIssuers.add)
        {
            $newValidIssuer = $ctp8xd.CreateElement("add")
            $newValidIssuer.SetAttribute("name",$validIssuer.Attributes.GetNamedItem("name").value)|out-null
            $newValidIssuers.AppendChild($newValidIssuer)|out-null
        }

        $newauthority.AppendChild($newkeys)|out-null
        $newauthority.AppendChild($newValidIssuers)|out-null
        $ctp8IssuerNameRegistry.AppendChild($newAuthority)|out-null
    }

    $ctp8xd.Save($ctp8wifconfig)
    
    # set the thumbprints for the AxTokenIssuer authority
    $wc = Join-Path -Path $webroot -ChildPath "web.config"
    [System.Xml.XmlDocument] $wcxd = new-object System.Xml.XmlDocument
    $wcxd.Load($wc)

    $ctp8xd.Load($ctp8wifconfig)
    $trustedThumbprintsNode = $wcxd.SelectSingleNode("/configuration/appSettings/add[@key='Infrastructure.TrustedCertificates']")
    if($trustedThumbprintsNode -ne $null)
    {
        $trustedThumbprints =  $trustedThumbprintsNode.Attributes.GetNamedItem("value").Value
        [string[]]$thumbprints = $trustedThumbprints.Split(";")
        $axTokenIssuerKeys = $ctp8xd.SelectSingleNode("/system.identityModel/identityConfiguration/securityTokenHandlers/securityTokenHandlerConfiguration/issuerNameRegistry/authority[@name='AxTokenIssuer']/keys")
        $axTokenIssuers = $ctp8xd.SelectNodes("/system.identityModel/identityConfiguration/securityTokenHandlers/securityTokenHandlerConfiguration/issuerNameRegistry/authority[@name='AxTokenIssuer']/keys/add")

        if($axTokenIssuers -ne $null)
        {
            $axTokenIssuers.RemoveAll()|out-null
        }

        foreach($thumbprint in $thumbprints)
        {
            $newthumbprint = $ctp8xd.CreateElement("add")
            $newthumbprint.SetAttribute("thumbprint",$thumbprint)|out-null
            $axTokenIssuerKeys.AppendChild($newthumbprint)|out-null
        }

        $ctp8xd.Save($ctp8wifconfig)
    }
    #endregion

     Write-Log "Saved the CTP8 wif.config with updated values from CTP7 wif.config."

     # replace the wif.config file
     $wifconfig=Join-Path -Path $webroot -ChildPath "wif.config"
     Rename-File -from:$ctp8wifconfig -to:$wifconfig
}

function Upgrade-Wif-Services-Config([string]$webroot,[string]$ctp8configdir)
{
    $ctp7wifservicesconfig=Join-Path -Path $webroot -ChildPath "wif.services.config"
    $ctp8_wifservicesconfig_template=Join-Path -Path $ctp8configdir -ChildPath "wif.services.config"
    $ctp8wifservicesconfig=Join-Path -Path $webroot -ChildPath "wif.services.config.ctp8"
    Copy-Item -Path $ctp8_wifservicesconfig_template -Destination $ctp8wifservicesconfig -Force |out-null
    Write-Log "Copied the CTP8 wif.services.config template from '$ctp8_wifservicesconfig_template' to '$ctp8wifservicesconfig'."

    [System.Xml.XmlDocument] $ctp7xd = new-object System.Xml.XmlDocument
    $ctp7xd.Load($ctp7wifservicesconfig)

    [System.Xml.XmlDocument] $ctp8xd = new-object System.Xml.XmlDocument
    $ctp8xd.Load($ctp8wifservicesconfig)

    #region wsFederation
    $ctp8wsfederation=$ctp8xd.SelectSingleNode("/system.identityModel.services/federationConfiguration/wsFederation")
    $ctp7wsfederation=$ctp7xd.SelectSingleNode("/system.identityModel.services/federationConfiguration/wsFederation")

    # replace reply url
    $ctp7reply=$ctp7wsfederation.Attributes.GetNamedItem("reply").Value
    $ctp8wsfederation.Attributes.GetNamedItem("reply").Value=$ctp7reply
    Write-Log "Setting wsFederation reply='$ctp7reply'."

    # replace realm
    $ctp7realm=$ctp7wsfederation.Attributes.GetNamedItem("realm").Value
    $ctp8wsfederation.Attributes.GetNamedItem("realm").Value=$ctp7realm
    Write-Log "Setting wsFederation relam='$ctp7realm'."

    # replace issuer
    $ctp7issuer=$ctp7wsfederation.Attributes.GetNamedItem("issuer").Value
    $ctp8wsfederation.Attributes.GetNamedItem("issuer").Value=$ctp7issuer
    Write-Log "Setting wsFederation issuer='$ctp7issuer'."

    #endregion

    #region cookieHandler
    $ctp8cookieHandler=$ctp8xd.SelectSingleNode("/system.identityModel.services/federationConfiguration/cookieHandler")
    $ctp7cookieHandler=$ctp7xd.SelectSingleNode("/system.identityModel.services/federationConfiguration/cookieHandler")

    #replace path
    $ctp7path=$ctp7cookieHandler.Attributes.GetNamedItem("path").Value
    $ctp8cookieHandler.Attributes.GetNamedItem("path").Value=$ctp7path
    Write-Log "Setting cookie handler path='$path'."

    # replace domain
    $ctp7domain=$ctp7cookieHandler.Attributes.GetNamedItem("domain").Value
    $ctp8cookieHandler.Attributes.GetNamedItem("domain").Value=$ctp7domain
    Write-Log "Setting cookie handler domain='$ctp7domain'."
    #endregion

    #region certificateReference
    $ctp8certReference=$ctp8xd.SelectSingleNode("/system.identityModel.services/federationConfiguration/serviceCertificate/certificateReference")
    $ctp7certReference=$ctp7xd.SelectSingleNode("/system.identityModel.services/federationConfiguration/serviceCertificate/certificateReference")

    # replace findValue
    $ctp7findValue=$ctp7certReference.Attributes.GetNamedItem("findValue").Value
    $ctp8certReference.Attributes.GetNamedItem("findValue").Value=$ctp7findValue
    Write-Log "Setting certificateReference findValue='$ctp7findValue'."
    #endregion
    
    $ctp8xd.Save($ctp8wifservicesconfig)
    Write-Log "Saved the CTP8 wif.services.config with updated values from CTP7 wif.services.config."
    
    # replace the wif.services.config file
    $wifservicesconfig=Join-Path -Path $webroot -ChildPath "wif.services.config"
    Rename-File -from:$ctp8wifservicesconfig -to:$wifservicesconfig
}

function Upgrade-App-Settings([string]$webroot,[string]$parentdir)
{
    $ctp7webconfig=Join-Path -Path $webroot -ChildPath "web.config"
    $ctp8_webconfig_template=Join-Path -Path $ctp8configdir -ChildPath "web.config"
    $ctp8webconfig=Join-Path -Path $webroot -ChildPath "web.config.ctp8"
    Copy-Item -Path $ctp8_webconfig_template -Destination $ctp8webconfig -Force |out-null
    Write-Log "Copied the CTP8 web.config template from '$ctp8_webconfig_template' to '$ctp8webconfig'."

    # add/update appsettings
    [System.Xml.XmlDocument] $ctp7xd = new-object System.Xml.XmlDocument
    $ctp7xd.Load($ctp7webconfig)

    [System.Xml.XmlDocument] $ctp8xd = new-object System.Xml.XmlDocument
    $ctp8xd.Load($ctp8webconfig)

    $ctp8appsettings=$ctp8xd.SelectNodes("/configuration/appSettings/add")

    foreach($setting in $ctp8appsettings)
    {
        $ctp8keyname=$setting.Attributes.GetNamedItem("key").Value

        # special handling for the 'DataAccess.DataEncryptionCertificateThumbprintLegacy' and 'DataAccess.DataSigningCertificateThumbprintLegacy' keys
        if($ctp8keyname -eq $DataSigningCertThumbprintLegacyKey)
        {
            # get the legacy signing cert thumbprint from the CTP7 web.config
            $signingcertthumbprintnode=$ctp7xd.SelectSingleNode("/configuration/appSettings/add[@key='$DataSigningCertThumbprintKey']")
            $keyvalue=$signingcertthumbprintnode.Attributes.GetNamedItem("value").Value
        }
        elseif($ctp8keyname -eq $DataEncryptionCertThumbprintLegacyKey)
        {
            # get the legacy encryption cert thumbprint from the CTP7 web.config
            $encryptioncertthumbprintnode=$ctp7xd.SelectSingleNode("/configuration/appSettings/add[@key='$DataEncryptionCertThumbprintKey']")
            $keyvalue=$encryptioncertthumbprintnode.Attributes.GetNamedItem("value").Value
        }
        elseif($ctp8keyname -eq $DataEncryptionCertThumbprintKey -or
                $ctp8keyname -eq $DataSigningCertThumbprintKey
               )
        {
            # if the key is either a encryption or signing cert thumbprint key, continue
            continue
        }
        elseif($ctp8keyname -eq $InternalServiceCertThumbprints)
        {
            # combine the existing thumbrints from the CTP7 web.config and the thumbprint in the ctp8 web.config
            # the ctp8 cert thumbprint should be the third value after the values are combined
            $internalservicecertthumbprintsnode=$ctp7xd.SelectSingleNode("/configuration/appSettings/add[@key='$InternalServiceCertThumbprints']")
            $ctp7value=$internalservicecertthumbprintsnode.Attributes.GetNamedItem("value").Value
            $ctp8value=$setting.Attributes.GetNamedItem("value").Value
            $keyvalue="$ctp7value`;$ctp8value"
        }
        elseif($ctp8keyname -eq $DataAccessAxAdminSqlUser)
        {
            $keyvalue=$ctp7xd.SelectSingleNode("/configuration/appSettings/add[@key='DataAccess.SqlUser']").Attributes.GetNamedItem("value").Value
        }
        elseif($ctp8keyname -eq $DataAccessAxAdminSqlPwd)
        {
            $keyvalue=$ctp7xd.SelectSingleNode("/configuration/appSettings/add[@key='DataAccess.SqlPwd']").Attributes.GetNamedItem("value").Value
        }
        else
        {
            # if the key exists in the ctp7 web.config use its value
            $ctp7keyname=$ctp7xd.SelectSingleNode("/configuration/appSettings/add[@key='$ctp8keyname']")
            if($ctp7keyname -eq $null)
            {
                # we found a new CTP8 appsetting. Update the key value to indicate it
                # $keyvalue=$NEWSETTING
            }
            else
            {
                # use the value from the ctp7 appsetting in the ctp8 appsetting
                $keyvalue=$ctp7keyname.Attributes.GetNamedItem("value").Value
            }
        }

        $setting.Attributes.GetNamedItem("value").Value=$keyvalue
        Write-Log "Setting '$ctp8keyname=$keyvalue'."
    }
    
    $ctp8xd.Save($ctp8webconfig)
    Write-Log "Saved the CTP8 web.config with the updated appsettings."
}

function Upgrade-Service-Behaviors([string]$webroot,[string]$parentdir)
{
    $ctp7webconfig=Join-Path -Path $webroot -ChildPath "web.config"
    $ctp8webconfig=Join-Path -Path $webroot -ChildPath "web.config.ctp8"

    [System.Xml.XmlDocument] $ctp7xd = new-object System.Xml.XmlDocument
    $ctp7xd.Load($ctp7webconfig)

    [System.Xml.XmlDocument] $ctp8xd = new-object System.Xml.XmlDocument
    $ctp8xd.Load($ctp8webconfig)

    # retrieve the service certificate thumbprint
    $servicecertthumbprint=Get-ServiceBehavior-Thumbprint -xmldoc:$ctp7xd

    if([system.string]::IsNullOrEmpty($servicecertthumbprint))
    {
        Log-Error "Unable to find the certificate thumbprint that is required to configure the service behaviors." -throw
    }

    # set the service certificate thumbprint to the ctp7 value
    $ctp8servicecertificates=$ctp8xd.SelectNodes("/configuration/location/system.serviceModel/behaviors/serviceBehaviors/behavior/serviceCredentials/serviceCertificate")
    foreach($servicecertificate in $ctp8servicecertificates)
    {
        $servicecertificate.Attributes.GetNamedItem("findValue").Value=$servicecertthumbprint
    }

    Write-Log "Setting the service behavior certificate thumbprint to '$servicecertthumbprint'."
    $ctp8xd.Save($ctp8webconfig)
}

function Upgrade-Bindings([string]$webroot,[string]$parentdir)
{
    # open both files
    $ctp7webconfig=Join-Path -Path $webroot -ChildPath "web.config"
    $ctp8webconfig=Join-Path -Path $webroot -ChildPath "web.config.ctp8"

    [System.Xml.XmlDocument] $ctp7xd = new-object System.Xml.XmlDocument
    $ctp7xd.Load($ctp7webconfig)

    [System.Xml.XmlDocument] $ctp8xd = new-object System.Xml.XmlDocument
    $ctp8xd.Load($ctp8webconfig)

    #region customBinding
    $ctp8customBindings = $ctp8xd.SelectNodes("/configuration/location/system.serviceModel/bindings/customBinding")
    foreach($binding in $ctp8customBindings)
    {
        $name=$binding.name
        $ctp7CustomBinding = $ctp7xd.SelectNodes("/configuration/location/system.serviceModel/bindings/customBinding/binding[@name='$name']")
        if($ctp7CustomBinding -ne $null)
        {
            $ctp7CustomBinding.sendTimeout = $binding.sendTimeout
            $ctp7CustomBinding.receiveTimeout = $binding.receiveTimeout
        


        # update security
        $ctp8Security = $ctp8xd.SelectSingleNode("/configuration/location/system.serviceModel/bindings/customBinding/binding[@name='$name']/security")
        $ctp7Security = $ctp7xd.SelectSingleNode("/configuration/location/system.serviceModel/bindings/customBinding/binding[@name='$name']/security")
     
        $ctp8Security.authenticationMode = $ctp7Security.authenticationMode
      
     

        # update issuedTokenParameters
        $ctp8IssuedTokenParameters = $ctp8xd.SelectSingleNode("/configuration/location/system.serviceModel/bindings/customBinding/binding[@name='$name']/security/issuedTokenParameters")
        $ctp7IssuedTokenParameters = $ctp7xd.SelectSingleNode("/configuration/location/system.serviceModel/bindings/customBinding/binding[@name='$name']/security/issuedTokenParameters")
        $ctp8IssuedTokenParameters.keyType = $ctp7IssuedTokenParameters.keyType
        $ctp8IssuedTokenParameters.tokenType = $ctp7IssuedTokenParameters.tokenType

        # update textMessageEncoding
        $ctp8textMessageEncodingReaderQuotas = $ctp8xd.SelectSingleNode("/configuration/location/system.serviceModel/bindings/customBinding/binding[@name='$name']/textMessageEncoding/readerQuotas")
        $ctp7textMessageEncodingReaderQuotas = $ctp7xd.SelectSingleNode("/configuration/location/system.serviceModel/bindings/customBinding/binding[@name='$name']/textMessageEncoding/readerQuotas")
        $ctp8textMessageEncodingReaderQuotas.maxDepth = $ctp7textMessageEncodingReaderQuotas.maxDepth 
        $ctp8textMessageEncodingReaderQuotas.maxStringContentLength = $ctp7textMessageEncodingReaderQuotas.maxStringContentLength
        $ctp8textMessageEncodingReaderQuotas.maxArrayLength = $ctp7textMessageEncodingReaderQuotas.maxArrayLength
        $ctp8textMessageEncodingReaderQuotas.maxBytesPerRead = $ctp7textMessageEncodingReaderQuotas.maxBytesPerRead
        $ctp8textMessageEncodingReaderQuotas.maxNameTableCharCount = $ctp7textMessageEncodingReaderQuotas.maxNameTableCharCount
        }
    }
    #endregion

    #region webHttpBinding
    $ctp8webHttpBinding = $ctp8xd.SelectNodes("/configuration/location/system.serviceModel/bindings/webHttpBinding")
    foreach($binding in $ctp8webHttpBinding)
    {
        $name=$binding.name
        $ctp7webHttpBinding = $ctp7xd.SelectSingleNode("/configuration/location/system.serviceModel/bindings/webHttpBinding/binding[@name='$name']")
        if($ctp7webHttpBinding -ne $null)
        {
            $binding.allowCookies = $ctp7webHttpBinding.allowCookies
            $binding.maxReceivedMessageSize = $ctp7webHttpBinding.maxReceivedMessageSize
            if($ctp7webHttpBinding.Attributes["contentTypeMapper"] -ne $null)
            {
                $binding.contentTypeMapper = $ctp7webHttpBinding.contentTypeMapper
            }
        

        # update security
        $ctp8webHttpBindingSecurity = $ctp8xd.SelectSingleNode("/configuration/location/system.serviceModel/bindings/webHttpBinding/binding[@name='$name']/security")
        $ctp7webHttpBindingSecurity = $ctp7xd.SelectSingleNode("/configuration/location/system.serviceModel/bindings/webHttpBinding/binding[@name='$name']/security")
        $ctp8webHttpBindingSecurity.mode = $ctp7webHttpBindingSecurity.mode

        # update readerQuotas
        $ctp8webHttpBindingReaderQuotas = $ctp8xd.SelectSingleNode("/configuration/location/system.serviceModel/bindings/webHttpBinding/binding[@name='$name']/readerQuotas")
        $ctp7webHttpBindingReaderQuotas = $ctp7xd.SelectSingleNode("/configuration/location/system.serviceModel/bindings/webHttpBinding/binding[@name='$name']/readerQuotas")
        $ctp8webHttpBindingReaderQuotas.maxStringContentLength = $ctp7webHttpBindingReaderQuotas.maxStringContentLength
        }
    }
    #endregion

    $ctp8xd.Save($ctp8webconfig)
    Write-Log "Upgraded the bindings."
}

function Update-Machine-Config-Keys([string]$webroot,[string]$parenrdir)
{
    $ctp7webconfig=Join-Path -Path $webroot -ChildPath "web.config"
    $ctp8webconfig=Join-Path -Path $webroot -ChildPath "web.config.ctp8"

    # load the web.config files
    [System.Xml.XmlDocument] $ctp7xd = new-object System.Xml.XmlDocument
    $ctp7xd.Load($ctp7webconfig)

    [System.Xml.XmlDocument] $ctp8xd = new-object System.Xml.XmlDocument
    $ctp8xd.Load($ctp8webconfig)

    # fetch the ctp7 machineKey values
    $ctp7machineKey = $ctp7xd.SelectSingleNode("/configuration/location/system.web/machineKey")
    $decryption=$ctp7machineKey.Attributes.GetNamedItem("decryption").Value
    $decryptionKey = $ctp7machineKey.Attributes.GetNamedItem("decryptionKey").Value
    $validationKey = $ctp7machineKey.Attributes.GetNamedItem("validationKey").Value
    $validation = $ctp7machineKey.Attributes.GetNamedItem("validation").Value

    # update the ctp8 machineKey values
    $ctp8machineKey=$ctp8xd.SelectSingleNode("/configuration/location/system.web/machineKey")
    $ctp8machineKey.Attributes.GetNamedItem("decryption").Value=$decryption
    $ctp8machineKey.Attributes.GetNamedItem("decryptionKey").Value=$decryptionKey
    $ctp8machineKey.Attributes.GetNamedItem("validation").Value=$validation
    $ctp8machineKey.Attributes.GetNamedItem("validationKey").Value=$validationKey

    # log
    Write-Log "Setting the machine decryption value to '$decryption'."
    Write-Log "Setting the machine decryption key value to '$decryptionKey'."
    Write-Log "Setting the machine validation value to '$validation'."
    Write-Log "Setting the machine validation key value to '$validationKey'."

    # save the ctp8 web.config with the updated values
    $ctp8xd.Save($ctp8webconfig)
}

function Get-ServiceBehavior-Thumbprint($xmldoc)
{
    # well-known service behavior names
    $behaviornames=@("AxILSessionServiceBehaviour","AxInteractiveILSessionServiceBehaviour","InteractionServiceBehavior","ODataQueryServiceBehavior")

    # try to get the service behavior thumbprint using one of the known behavior names
    foreach($name in $behaviornames)
    {
        $thumbprint=$xmldoc.SelectSingleNode("/configuration/location/system.serviceModel/behaviors/serviceBehaviors/behavior[@name='$name']/serviceCredentials/serviceCertificate/@findValue").value
        if(![system.string]::IsNullOrEmpty($thumbprint))
        {
            return $thumbprint
        }
    }

    return [string]::Empty
}

function Rename-File([string]$from,[string]$to)
{
    Move-Item -Path $from -Destination $to -Force|out-null
    Write-Log "Renamed file '$from' to '$to'."
}

function Validate
{
    Import-Module "$PSScriptRoot\CommonRollbackUtilities.psm1" -DisableNameChecking
    
    $aosWebsiteName = Get-AosWebSiteName
    if(!(Is-Website-Stopped -name:$aosWebsiteName))
    {
        Log-Error "Cannot perform the upgrade as the AOS website '$aosWebsiteName' is started. Stop the website and retry." -throw
    }

    if(!(Is-Service-Stopped -name:$BatchService))
    {
        Log-Error "Cannot perform the upgrade as the NT service '$BatchService' is running. Stop the service and retry." -throw
    }

    if(!(Is-Service-Stopped -name:$PrintService))
    {
        Log-Error "Cannot perform the upgrade as the NT service '$PrintService' is running. Stop the service and retry." -throw
    }
}

function Is-Website-Stopped([string]$name)
{
    Import-Module WebAdministration
    Write-Log "Checking the state of the web site '$name'."|Out-Null
    $website=Get-Website -Name:$name -ErrorAction SilentlyContinue
    if($website -eq $null)
    {
        return $true
    }

    if($website.State -eq "Started")
    {
        return $false
    }

    return $true
}

function Is-Service-Stopped([string]$name)
{
    Write-Log "Checking the status of the service '$name'."|out-null
    $service=Get-Service -Name:$name -ErrorAction SilentlyContinue
    if($service -eq $null)
    {
        return $true
    }

    if($service.Status -eq "Running")
    {
        return $false
    }

    return $true
}

function Decrypt-Config([string]$webroot)
{
    $command = Join-Path -Path "$webroot\bin" -ChildPath $configEncryptor
    if(!(Test-Path -Path $command))
    {
        Log-Error "Cannot find the Microsoft.Dynamics.AX.Framework.ConfigEncryptor.exe at '$webroot\bin\'." -throw
    }

    $webconfig=Join-Path -Path $webroot -ChildPath "Web.config"
    $commandParameter = " -decrypt `"$webconfig`""
    $logdir=[System.IO.Path]::GetDirectoryName($global:logfile)
    $stdOut=Join-Path -Path $logdir -ChildPath "config_decrypt.log"
    $stdErr= Join-Path -Path $logdir -ChildPath "config_decrypt.error.log"
    Start-Process $command $commandParameter -PassThru -Wait -RedirectStandardOutput $stdOut -RedirectStandardError $stdErr

    $decryptError = Get-Content $stdErr
    if ($decryptError -ne $null) {
        Log-Error $decryptError -throw
    }

    Write-Log "Finished decrypting the CTP7 web.config."
}

function Encrypt-Config([string]$webroot)
{
    $command = Join-Path -Path "$PSScriptRoot\EncryptionTool" -ChildPath $configEncryptor
    if(!(Test-Path -Path $command))
    {
        Log-Error "Cannot find the CTP8 Microsoft.Dynamics.AX.Framework.ConfigEncryptor.exe at '$PSScriptRoot\EncryptionTool\'." -throw
    }

    $webconfig=Join-Path -Path $webroot -ChildPath "Web.config"
    $commandParameter = " -encrypt `"$webconfig`""
    $logdir=[System.IO.Path]::GetDirectoryName($global:logfile)
    $stdOut=Join-Path -Path $logdir -ChildPath "config_encrypt.log"
    $stdErr= Join-Path -Path $logdir -ChildPath "config_encrypt.error.log"
    Start-Process $command $commandParameter -PassThru -Wait -RedirectStandardOutput $stdOut -RedirectStandardError $stdErr

    $encryptError = Get-Content $stdErr
    if ($encryptError -ne $null) {
        Log-Error $encryptError -throw
    }

    Write-Log "Finished encrypting the CTP8 web.config."
}

Export-ModuleMember -Function Initialize-Log,Write-Log,Write-Error,Validate,Create-Backup,Upgrade-Web-Config,Upgrade-Wif-Config,Upgrade-Wif-Services-Config -Variable $logfile

# SIG # Begin signature block
# MIIr5AYJKoZIhvcNAQcCoIIr1TCCK9ECAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAFtoHbPK5XPz6U
# yKSkeOH9OrU39SSz6puyJiuuoTo186CCEW4wggh+MIIHZqADAgECAhM2AAAB33OB
# lxa+Mv0NAAIAAAHfMA0GCSqGSIb3DQEBCwUAMEExEzARBgoJkiaJk/IsZAEZFgNH
# QkwxEzARBgoJkiaJk/IsZAEZFgNBTUUxFTATBgNVBAMTDEFNRSBDUyBDQSAw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