Bacpac/Export-NavContainerDatabasesAsBacpac.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
<#
 .Synopsis
  Export databases in a Nav container as .bacpac files
 .Description
  If the Nav Container is multi-tenant, this command will create an app.bacpac and a tenant.bacpac.
  If the Nav Container is single-tenant, this command will create one bacpac file called database.bacpac.
 .Parameter containerName
  Name of the container for which you want to export and convert objects
 .Parameter sqlCredential
  Credentials for the SQL admin user if using NavUserPassword authentication. User will be prompted if not provided
 .Parameter bacpacFolder
  The folder to which the bacpac files are exported (needs to be shared with the container)
 .Example
  Export-NavContainerDatabasesAsBacpac -containerName test
 .Example
  Export-NavContainerDatabasesAsBacpac -containerName test -bacpacfolder "c:\programdata\navcontainerhelper\extensions\test"
 .Example
  Export-NavContainerDatabasesAsBacpac -containerName test -bacpacfolder "c:\demo" -sqlCredential <sqlCredential>
#>

function Export-NavContainerDatabasesAsBacpac {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName, 
        [Parameter(Mandatory=$false)]
        [System.Management.Automation.PSCredential]$sqlCredential = $null,
        [Parameter(Mandatory=$false)]
        [string]$bacpacFolder = ""
    )
    
    $genericTag = Get-NavContainerGenericTag -containerOrImageName $containerName
    if ([System.Version]$genericTag -lt [System.Version]"0.0.4.5") {
        throw "Export-DatabasesAsBacpac is not supported in images with generic tag prior to 0.0.4.5"
    }

    $sqlCredential = Get-DefaultSqlCredential -containerName $containerName -sqlCredential $sqlCredential

    $containerFolder = Join-Path $ExtensionsFolder $containerName
    if ("$bacpacFolder" -eq "") {
        $bacpacFolder = $containerFolder
    }
    $containerBacpacFolder = Get-NavContainerPath -containerName $containerName -path $bacpacFolder -throw

    $session = Get-NavContainerSession -containerName $containerName -silent
    Invoke-Command -Session $session -ScriptBlock { Param($sqlCredential, $bacpacFolder)
    
        function Install-DACFx
        {
            $DacFxMsi = Join-Path $env:TEMP "DacFramework.msi"
            $sqlpakcageExe = "C:\Program Files\Microsoft SQL Server\140\DAC\bin\sqlpackage.exe"
            if (!(Test-Path $sqlpakcageExe -PathType Leaf)) {
                Write-Host "Downloading DacFx 17.3 GA"
                (New-Object System.Net.WebClient).DownloadFile("https://download.microsoft.com/download/3/7/F/37F3C5CE-E96B-41AC-B361-27735365AA16/EN/x64/DacFramework.msi",$DacFxMsi)
                Write-Host "Installing DacFx 17.3 GA"
                Start-process -FilePath $DacFxMsi -argumentList "/qn" -Wait
                Remove-Item -Path $DacFxMsi
            }
            $sqlpakcageExe 
        }
        
        function Remove-NetworkServiceUser
        (
            [Parameter(Mandatory=$true)]
            [string]$DatabaseName,
            [Parameter(Mandatory=$true)]
            [string]$DatabaseServer,
            [Parameter(Mandatory=$false)]
            [System.Management.Automation.PSCredential]$sqlCredential = $null
        )
        {
            $params = @{ 'ErrorAction' = 'Ignore'; 'ServerInstance' = $databaseServer }
            if ($sqlCredential) {
                $params += @{ 'Username' = $sqlCredential.UserName; 'Password' = ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($sqlCredential.Password))) }
            }
        
            Write-Host "Remove Network Service User from $DatabaseName"
            Invoke-Sqlcmd @params -Query "USE [$DatabaseName]
            IF EXISTS (SELECT 'X' FROM sysusers WHERE name = 'NT AUTHORITY\NETWORK SERVICE' and isntuser = 1)
              BEGIN DROP USER [NT AUTHORITY\NETWORK SERVICE] END"

        }
        
        function Remove-NavDatabaseSystemTableData
        (
            [Parameter(Mandatory=$true)]
            [string]$DatabaseName,
            [Parameter(Mandatory=$true)]
            [string]$DatabaseServer,
            [Parameter(Mandatory=$false)]
            [System.Management.Automation.PSCredential]$sqlCredential = $null
        )
        {
            $params = @{ 'ErrorAction' = 'Ignore'; 'ServerInstance' = $databaseServer }
            if ($sqlCredential) {
                $params += @{ 'Username' = $sqlCredential.UserName; 'Password' = ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($sqlCredential.Password))) }
            }
        
            Write-Host "Remove data from System Tables database $DatabaseName"
            Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[Server Instance]" 
            Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[$("$")ndo$("$")cachesync]"
            Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[$("$")ndo$("$")tenants]"
            Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[Object Tracking]" 
        
            Invoke-Sqlcmd @params -Query "USE [$DatabaseName]
              IF EXISTS ( SELECT 'X' FROM [sys].[tables] WHERE name = 'Active Session' AND type = 'U' )
                BEGIN Delete from dbo.[Active Session] END"
 
            
            Invoke-Sqlcmd @params -Query "USE [$DatabaseName]
              IF EXISTS ( SELECT 'X' FROM [sys].[tables] WHERE name = 'Session Event' AND type = 'U' )
                BEGIN Delete from dbo.[Session Event] END"
 
        
            Remove-NetworkServiceUser -DatabaseServer $DatabaseServer -DatabaseName $DatabaseName -sqlCredential $sqlCredential
        }
        
        function Remove-NavTenantDatabaseUserData
        (        
            [Parameter(Mandatory=$true)]
            [string]$DatabaseName,
            [Parameter(Mandatory=$true)]
            [string]$DatabaseServer,
            [Parameter(Mandatory=$false)]
            [System.Management.Automation.PSCredential]$sqlCredential = $null,
            [Parameter(Mandatory=$false)]
            [switch]$KeepUserData
        )
        {
            $params = @{ 'ErrorAction' = 'Ignore'; 'ServerInstance' = $databaseServer }
            if ($sqlCredential) {
                $params += @{ 'Username' = $sqlCredential.UserName; 'Password' = ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($sqlCredential.Password))) }
            }
        
            Write-Host "Remove data from User table and related tables in $DatabaseName database."
            if (!($KeepUserData)) {
                Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[Access Control]" 
                Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[User Property]" 
                Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[User Personalization]" 
                Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[User Metadata]" 
                Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[User Default Style Sheet]" 
                Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[User]" 
            }
            Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[Active Session]" 
            Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DELETE FROM dbo.[Session Event]" 
        
            Write-Host "Drop triggers from $DatabaseName"
            Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DROP TRIGGER [dbo].[RemoveOnLogoutActiveSession]" 
            Invoke-Sqlcmd @params -Query "USE [$DatabaseName] DROP TRIGGER [dbo].[DeleteActiveSession]" 
        
            Remove-NetworkServiceUser -DatabaseServer $DatabaseServer -DatabaseName $DatabaseName -sqlCredential $sqlCredential
        }

        function Do-Export
        (        
            [Parameter(Mandatory=$true)]
            [string]$DatabaseName,
            [Parameter(Mandatory=$true)]
            [string]$DatabaseServer,
            [Parameter(Mandatory=$false)]
            [System.Management.Automation.PSCredential]$sqlCredential = $null,
            [Parameter(Mandatory=$true)]
            [string]$targetFile
        )
        {
            $arguments = @(
                ('/Action:Export'), 
                ('/TargetFile:"'+$targetFile+'"'), 
                ('/SourceDatabaseName:"'+$databaseName+'"'),
                ('/SourceServerName:"'+$databaseServer+'"'),
                ('/OverwriteFiles:True')
            )

            if ($sqlCredential) {
                $arguments += @(
                    ('/SourceUser:"'+$sqlCredential.UserName+'"'),
                    ('/SourcePassword:"'+([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($sqlCredential.Password)))+'"')
                )
            }

            $pinfo = New-Object System.Diagnostics.ProcessStartInfo
            $pinfo.FileName = $sqlPackageExe
            $pinfo.RedirectStandardError = $true
            $pinfo.RedirectStandardOutput = $true
            $pinfo.UseShellExecute = $false
            $pinfo.Arguments = $arguments
            $p = New-Object System.Diagnostics.Process
            $p.StartInfo = $pinfo
            $p.Start() | Out-Null

            while (!$p.HasExited){
                $line = $p.StandardOutput.ReadLine()
                Write-Host $line
            }
            $line = $p.StandardOutput.ReadToEnd()
            Write-Host $line
            $err = $p.StandardError.ReadToEnd()
            if ($err) {
                Write-Error $err
            }
        }

        $customConfigFile = Join-Path (Get-Item "C:\Program Files\Microsoft Dynamics NAV\*\Service").FullName "CustomSettings.config"
        [xml]$customConfig = [System.IO.File]::ReadAllText($customConfigFile)
        $multitenant = ($customConfig.SelectSingleNode("//appSettings/add[@key='Multitenant']").Value -eq "true")
        $databaseServer = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseServer']").Value
        $databaseInstance = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseInstance']").Value
        $databaseName = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseName']").Value

        if ("$databaseInstance" -ne "") {
            $databaseServer = "$databaseServer\$databaseInstance"
        }

        $sqlPackageExe = Install-DACFx
       
        if ($multitenant) {
            $tempAppDatabaseName = "temp$DatabaseName"
            $appBacpacFileName = Join-Path $bacpacFolder "app.bacpac"
            Copy-NavDatabase -SourceDatabaseName $DatabaseName -DestinationDatabaseName $tempAppDatabaseName
            Remove-NavDatabaseSystemTableData -DatabaseServer $databaseServer -DatabaseName $tempAppDatabaseName -sqlCredential $sqlCredential
            Do-Export -DatabaseServer $databaseServer -DatabaseName $tempAppDatabaseName -sqlCredential $sqlCredential -targetFile $appBacpacFileName
            
            $tempTenantDatabaseName = "tempTenant"
            $tenantBacpacFileName = Join-Path $bacpacFolder "tenant.bacpac"
            Copy-NavDatabase -SourceDatabaseName "tenant" -DestinationDatabaseName $tempTenantDatabaseName
            Remove-NavTenantDatabaseUserData -DatabaseServer $databaseServer -DatabaseName $tempTenantDatabaseName -sqlCredential $sqlCredential
            Do-Export -DatabaseServer $databaseServer -DatabaseName $tempTenantDatabaseName -sqlCredential $sqlCredential -targetFile $tenantBacpacFileName
        } else {
            $tempDatabaseName = "temp$DatabaseName"
            $bacpacFileName = Join-Path $bacpacFolder "database.bacpac"
            Copy-NavDatabase -SourceDatabaseName $DatabaseName -DestinationDatabaseName $tempDatabaseName
            Remove-NavDatabaseSystemTableData -DatabaseServer $databaseServer -DatabaseName $tempDatabaseName -sqlCredential $sqlCredential
            Remove-NavTenantDatabaseUserData -DatabaseServer $databaseServer -DatabaseName $tempDatabaseName -sqlCredential $sqlCredential
            Do-Export -DatabaseServer $databaseServer -DatabaseName $tempDatabaseName -sqlCredential $sqlCredential -targetFile $bacpacFileName
        }
    } -ArgumentList $sqlCredential, $containerBacpacFolder
}
Export-ModuleMember Export-NavContainerDatabasesAsBacpac