$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
# MIIn0QYJKoZIhvcNAQcCoIInwjCCJ74CAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAFtoHbPK5XPz6U
# yKSkeOH9OrU39SSz6puyJiuuoTo186CCDYUwggYDMIID66ADAgECAhMzAAACzfNk
# v/jUTF1RAAAAAALNMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaW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