PowerShell.BTDF.psm1

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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
#Requires -RunAsAdministrator
#Requires -PSEdition Desktop

if (-not [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.BizTalk.ExplorerOM"))
{
    throw [System.ApplicationException]::new("Failed to load Microsoft.BizTalk.ExplorerOM")
}
if (-not [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.BizTalk.Operations"))
{
    throw [System.ApplicationException]::new("Failed to load Microsoft.BizTalk.Operations")
}
if (-not [System.Reflection.Assembly]::LoadWithPartialName("SSOSettingsFileReader"))
{
    throw [System.ApplicationException]::new("Failed to load SSOSettingsFileReader")
}

#region Variables
$btdfTargets = @{
    "BounceBizTalk"      = @{
        "Message" = "Boucing BizTalk"
        "Target"  = "BounceBizTalk"
    }
    "Deploy"             = @{
        "Message" = "Deploying application"
        "Target"  = "Deploy"
    }
    "DeployBAM"          = @{
        "Message" = "Deploying BAM"
        "Target"  = "GetSoftwarePaths;InitializeAppName;DeployBAM"
    }
    "DeployBRE"          = @{
        "Message" = "Deploying BRE" 
        "Target"  = "DeployVocabAndRules"
    }
    "DeploySSO"          = @{
        "Message" = "Deploying SSO"
        "Target"  = "DeploySSO"
    }
    "ImportBindings"     = @{
        "Message" = "Importing bindings"
        "Target"  = "ImportBindings"
    }
    "Installer"          = @{
        "Message" = "Packaging"
        "Target"  = "Installer"
    }
    "PreProcessBindings" = @{
        "Message" = "Pre-Processing bindings"
        "Target"  = "PreprocessBindings"
    }
    "QuickDeploy"        = @{
        "Message" = "Quick deploying application"
        "Target"  = "UpdateOrchestration"
    }
    "Undeploy"           = @{
        "Message" = "Undeploying application"
        "Target"  = "Undeploy"
    }
    "UndeployBAM"        = @{
        "Message" = "Undeploying BAM"
        "Target"  = "GetSoftwarePaths;InitializeAppName;UndeployBAM"
    }
    "UndeployBRE"        = @{
        "Message" = "Undeploying BRE"
        "Target"  = "UndeployVocabAndRules"
    }
}
#endregion

#region BTDF
<#
.SYNOPSIS
    Helper function to clean BizTalk environment using BTDF
.DESCRIPTION
    Uses BizTalk ExplorerOM to build a list of BizTalk applications currently installed. Each application is undeployed using "Deploy-BTDFApplication" to cleanly undeploy applications as well as handling dependencies. An exemption list is also included to leave specified, base applications
.EXAMPLE
    PS C:\> Clean-BTDFEnvironment
    Removes all BTDF BizTalk applications using the Debug configuration, the default for local development
.EXAMPLE
    PS C:\> Clean-BTDFEnvironment -Configuration Release
    Removes all BTDF BizTalk applications using the Release configuration
.EXAMPLE
    PS C:\> Clean-BTDFEnvironment -Exemptions Common
    Removes all BTDF BizTalk applications using the Debug configuration except for the "Common" application
.PARAMETER Configuration
    Deploys the BizTalk artifacts from the specified bin location. Debug and Release are default build configuration in VS. Server is used to (un)deploy BizTalk artifacts from an MSI installation
.PARAMETER TerminateInstances
    Terminates BizTalk service instances as part of the undeployment process
.PARAMETER Exemptions
    A dynamic list of applications which can be exempt from the cleaning process
.NOTES
    General notes
#>

function Clean-BTDFEnvironment
{
    [CmdletBinding()]
    Param (
        [Parameter(HelpMessage = "Valid parameters are Debug, Release and Server. Defaults to Debug")]
        [ValidateSet("Debug", "Release", "Server")]
        [string]$Configuration = "Debug",

        [Parameter(HelpMessage = "Terminate instances related to deployed app")]
        [switch]$TerminateInstances
    )
    DynamicParam
    {
        $btsCatalog.Refresh()
        $btsApps = $btsCatalog.Applications | Select-Object -Property Name, $projectPathColumn | Where-Object { $_.ProjectPath }

        $paramDict = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()

        #region DeployBTMgmtDB
        if ($Configuration -eq "Server")
        {
            $attributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
            $parameter = [System.Management.Automation.ParameterAttribute]::new()
            $parameter.HelpMessage = "Register artifacts in BizTalk DB"
            $attributeCollection.Add($parameter)
            $deployBTMgmtDBParameter = [System.Management.Automation.RuntimeDefinedParameter]::new("DeployBTMgmtDB", [switch], $attributeCollection)
            $paramDict.Add("DeployBTMgmtDB", $deployBTMgmtDBParameter)
        }
        #endregion

        #region Exemptions
        $attributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
        $parameter = [System.Management.Automation.ParameterAttribute]::new()
        $attributeCollection.Add($parameter)
        $validateSet = [System.Management.Automation.ValidateSetAttribute]::new([string[]]($btsApps | Select-Object -ExpandProperty Name))
        $attributeCollection.Add($validateSet)
        $exemptionsParameter = [System.Management.Automation.RuntimeDefinedParameter]::new("Exemptions", [System.Collections.Generic.List[string]], $attributeCollection)
        $exemptionsParameter.Value = @()
        $paramDict.Add("Exemptions", $exemptionsParameter)
        $PSBoundParameters["Exemptions"] = [System.Collections.Generic.List[string]]::new()
        #endregion

        return $paramDict
    }
    Process
    {
        $cleanParams = @{ }
        if ($PSBoundParameters.ContainsKey("DeployBTMgmtDB"))
        {
            $cleanParams["DeployBTMgmtDB"] = $PSBoundParameters["DeployBTMgmtDB"]
        }
        if ($PSBoundParameters.ContainsKey("TerminateInstances"))
        {
            $cleanParams["TerminateInstances"] = $TerminateInstances
        }
        
        foreach ($a in $btsApps)
        {
            Write-Debug "App: $($a.Name)"
            $btsCatalog.Refresh()
            if (-not $btsCatalog.Applications[$a.Name])
            {
                Write-Warning "$($a.Name) already removed"
                
            } 
            elseif ($PSBoundParameters["Exemptions"].Contains($a.Name))
            {
                Write-Verbose "$($a.Name) exempt"
            } 
            else
            {
                Write-Information "Removing $($a.Name)"
                Deploy-BTDFApplication -ProjectPath $a.ProjectPath `
                    -DeploymentType Undeploy `
                    -Configuration $Configuration `
                    @cleanParams
            }
        }
    }
}

<#
.SYNOPSIS
    Deploys a BTDF based BizTalk application
 
.DESCRIPTION
    Deploys a BTDF based BizTalk application and allows configuration to support multi-server setups (Deploying resources to secondary nodes and registering application on primary node). This also uses BizTalk types to check if an upgraded application is a dependency and will strip and restore this application recursively and in order. Supports both local (Debug/Release) deployments as well as server deployments. The parameters are validated and may need adjusting should your environments be named differently
 
.PARAMETER ProjectPath
    The path which the BTDF application is stored in (Eqivalent to the installation path/targetdir). Usually one level above the deployment folder for an application
 
.PARAMETER DeploymentType
    Choose whether to "Deploy", "Undeploy" or "Quick Deploy (UpdateOrchestration)" the BizTalk application (Default is "Deploy")
 
.PARAMETER Configuration
    Deploys the BizTalk artifacts from the specified bin location. Debug and Release are default build configuration in VS. Server is used to (un)deploy BizTalk artifacts from an MSI installation
 
.PARAMETER Environment
    Select the environment to deploy. Must match what is configured in BTDF environmentsettings spreadsheet. Defaults to Local (Only applicable to Server deployments)
 
.PARAMETER DeployBTMgmtDB
    Registers application in BizTalk. Assemblies/components are GACed otherwise (Only applicable to Server deployments)
 
.PARAMETER SkipUnDeploy
    Skip undeploying application prior to deployment (Only applicable to Server deployments)
 
.PARAMETER SkipBizTalkRestart
    If supported by deployment project, skip restarting BizTalk Host instances post-deployment
 
.PARAMETER SkipIISRestart
    If supported by deployment project, skip IISReset post-deployment
 
.PARAMETER SkipApplicationStart
    If supported by deployment project, don't start application after deployment
 
.PARAMETER TerminateInstances
    If supported by deployment project, terminate running/suspended instances
 
.PARAMETER SkipRestore
    Skips restoring dependant applciations, if any
 
.EXAMPLE
    Deploy application components/assemblies
 
    C:\PS> Deploy-BTDFApplication -ProjectPath "C:\Program Files (x86)\Scratchpad"
 
.EXAMPLE
    Deploy application and register in BizTalk
 
    C:\PS> Deploy-BTDFApplication -ProjectPath "C:\Program Files (x86)\Scratchpad" -Configuration Server -DeployBTMgmtDB
 
.EXAMPLE
    Deploy application and register in BizTalk with live environment settings
 
    C:\PS> Deploy-BTDFApplication -ProjectPath "C:\Program Files (x86)\Scratchpad" -Configuration Server -Environment Prod -DeployBTMgmtDB
 
.EXAMPLE
    Undeploys application and removes from BizTalk
 
    C:\PS> Deploy-BTDFApplication -ProjectPath "C:\Program Files (x86)\Scratchpad" -DeploymentType Undeploy -Configuration Server -DeployBTMgmtDB
 
.NOTES
    General notes
#>

function Deploy-BTDFApplication
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    [OutputType([hashtable])]
    Param (
        [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, HelpMessage = "Path to the folder of the BizTalk app")]
        [System.IO.DirectoryInfo[]]$ProjectPath,

        [Parameter(HelpMessage = "Defaults to Deploy")]
        [ValidateSet("BounceBizTalk", "Deploy", "DeployBAM", "DeployBRE", "DeploySSO", "ImportBindings", "Installer", "PreProcessBindings", "QuickDeploy", "Undeploy", "UndeployBAM", "UndeployBRE")]
        [string]$DeploymentType = "Deploy",

        [Parameter(HelpMessage = "Valid parameters are Debug, Release and Server. Defaults to Debug")]
        [ValidateSet("Debug", "Release", "Server")]
        [string]$Configuration = "Debug",

        [Parameter(HelpMessage = "Valid parameters are Local, Dev , Int, UAT and Prod. Defaults to Local")]
        [ValidateSet("Local", "Dev", "Int", "UAT", "Train", "Prod")]
        [string]$Environment = "Local",

        [Parameter(HelpMessage = "Register artifacts in BizTalk DB")]
        [switch]$DeployBTMgmtDB,
  
        [Parameter(HelpMessage = "Only deploy instead of redeploy")]
        [switch]$SkipUnDeploy,

        [Parameter(HelpMessage = "Skip starting BizTalk hosts back up post deployment")]
        [switch]$SkipBizTalkRestart,

        [Parameter(HelpMessage = "Skip IISReset post deployment")]
        [switch]$SkipIISRestart,

        [Parameter(HelpMessage = "Skipping starting BizTalk app post deployment")]
        [switch]$SkipApplicationStart,

        [Parameter(HelpMessage = "Terminate instances related to deployed app")]
        [switch]$TerminateInstances,

        [Parameter(HelpMessage = "Skip restoring dependant applications")]
        [switch]$SkipRestore
    )
    Process
    {
        #region Parameter checks
        if ($Configuration -ne "Server")
        {
            if ($PSBoundParameters.ContainsKey("Environment"))
            {
                throw [System.ArgumentException]::new("Environment must be used with the `"Server`" configuration")
            }
            if ($PSBoundParameters.ContainsKey("DeployBTMgmtDB"))
            {
                throw [System.ArgumentException]::new("DeployBTMgmtDB must be used with the `"Server`" configuration")
            }
            if ($PSBoundParameters.ContainsKey("SkipUnDeploy"))
            {
                throw [System.ArgumentException]::new("SkipUnDeploy must be used with the `"Server`" configuration")
            }
        }
        #endregion

        foreach ($pp in $ProjectPath)
        {
            Write-Debug "ProjectPath = $pp"

            #region Get properties from BTDF project
            $btdfProject = Join-Path -Path $pp -ChildPath "Deployment\Deployment.btdfproj"
            $btdfProjectXml = [xml](Get-Content -Path $btdfProject)
            $manufacturer = $btdfProjectXml.GetElementsByTagName("Manufacturer")."#text"
            Write-Debug "Manufacturer = $manufacturer"
            $projectName = $btdfProjectXml.GetElementsByTagName("ProjectName")."#text"
            Write-Debug "ProjectName = $projectName"
            #endregion

            #region Get back referenced applications
            $btsCatalog.Refresh()
            $btsApp = $btsCatalog.Applications["$projectName"]
            Write-Verbose "Checking back references for: $projectName"
            try
            {
                if ((-not ($Configuration -eq "Server" -and -not $DeployBTMgmtDB)) `
                        -and $btsApp `
                        -and ($DeploymentType -in "Deploy", "UnDeploy"))
                {
                    if (-not $backRefs)
                    {
                        Write-Verbose "Creating new back refs stack"
                        $backRefs = [System.Collections.Generic.Stack[System.Object]]::new()
                    }
    
                    $btsApps = $btsCatalog.Applications["$projectName"].BackReferences | Select-Object -Property Name, $projectPathColumn

                    if ($btsApps.Count -gt 0)
                    {
                        Write-Verbose "Back refs found"
                    }
                    foreach ($a in $btsApps)
                    {
                        $btsCatalog.Refresh()
                        if ($btsCatalog.Applications[$a.Name])
                        {
                            Write-Verbose "Removing back reference: $($a.Name)"
                            Write-Debug "BizTalk App: $($a.Name) = $($a.ProjectPath)"

                            $undeployParams = $PSBoundParameters
                            $undeployParams["ProjectPath"] = $a.ProjectPath
                            $undeployParams["DeploymentType"] = "Undeploy"

                            try
                            {
                                if ($PSCmdlet.ShouldProcess($a.Name, "Removing BizTalk Application"))
                                {
                                    Deploy-BTDFApplication @undeployParams
                                }
                            }
                            finally
                            {
                                $backRefs.Push($a)
                            }
                            Write-Verbose "Removed back reference: $($a.Name)"
                        }
                        else
                        {
                            Write-Warning "$($a.Name) already removed"
                        }
                    }
                    if (($backRefs.Count -gt 0) -and ($btsApps.Count -gt 0))
                    {
                        Write-Debug ($backRefs.GetEnumerator() | Out-String)
                    }
                }
                else
                {
                    Write-Verbose "No back references"
                }
                $backRefsRemoved = $true
            }
            catch
            {
                Write-Error -Message "Undeploying back references failed" -ErrorAction Continue
                Write-Error -Message "$_" -ErrorAction Continue
            }
            #endregion

            #region Calculate deployment variables
            #Calculate required properties
            $deployment = (Get-ChildItem -Path $pp -Filter *Deployment)[0]
            Write-Debug "Deployment = $($deployment.FullName)"
            $resultsPath = Join-Path -Path $pp -ChildPath "DeployResults\DeployResults.txt"
            if ($PSCmdlet.ShouldProcess($resultsPath, "Create empty MSBuild log file"))
            {
                New-Item -Path $resultsPath -ItemType File -Force | Out-Null
            }
            Write-Debug "Results = $resultsPath"

            #Get/Create project registry keys
            $manufacturerReg = if ($softwareReg32 | Join-Path -ChildPath $manufacturer | Test-Path)
            {
                $softwareReg32 | Join-Path -ChildPath $manufacturer | Get-Item
            }
            else
            {
                New-Item -Path $softwareReg32.PSPath -Name $manufacturer
                Write-Verbose "Created manufacturer key: $manufacturer"
            }

            $projectReg = if ($manufacturerReg | Join-Path -ChildPath $projectName | Test-Path)
            {
                $manufacturerReg | Join-Path -ChildPath $projectName | Get-Item
            }
            else
            {
                New-Item -Path $manufacturerReg.PSPath -Name $projectName
                Write-Verbose "Created project key: $projectName"
            }
        
            #Get properties from Application BTDF registry
            try
            {
                $version = $projectReg.GetValue("InstalledVersion")
                if (-not $version)
                {
                    throw
                }
                Write-Debug "Version = $version"
            }
            catch
            {
                Write-Warning "Unable to find version"
            }
            #endregion

            #region Run EnvironmentSettingsExporter
            if (($DeploymentType -eq "Deploy" -or $DeploymentType -eq "PreProcessBindings") -and ($Configuration -eq "Server"))
            {
                $envSettingsDir = $deployment | Join-Path -ChildPath "EnvironmentSettings" | Get-Item
                Write-Debug "Environment Settings Dir = $($envSettingsDir.FullName)"

                $settingsExporter = Join-Path -Path $deployment.FullName -ChildPath "Framework\DeployTools\EnvironmentSettingsExporter.exe"
                Write-Debug "Settings Exporter = $settingsExporter"
                if ($PSCmdlet.ShouldProcess($settingsExporter, "Exporting BTDF settings"))
                {
                    Invoke-Process -FilePath $settingsExporter `
                        -ArgumentList "`"$(Join-Path -Path $envSettingsDir.FullName -ChildPath \SettingsFileGenerator.xml)`"",
                    "`"$($envSettingsDir.FullName)`"" | Out-Null
                }
                $envSettings = Join-Path -Path $envSettingsDir -ChildPath "Exported_$Environment`Settings.xml" | Get-Item
                Write-Debug "Environment Settings = $($envSettings.FullName)"
            }
            #endregion

            #region Run MSBuild and deploy
            if ($backRefsRemoved)
            {
                $projectReg | New-ItemProperty -Name "Configuration" -Value $Configuration -Force | Out-Null
                $projectReg | New-ItemProperty -Name "LastDeploySettingsFilePath" -Value $envSettings.FullName -Force | Out-Null
                $projectReg | New-ItemProperty -Name "Version" -Value $version -Force | Out-Null
                Write-Verbose "$($btdfTargets[$DeploymentType]["Message"]): $projectName"
                $msbuildArgs = "/t:$($btdfTargets[$DeploymentType]["Target"])",
                $(if ($version)
                    {
                        "/p:ProductVersion=$version"
                    }),
                $(if (($DeploymentType -eq "Deploy") -and ($Configuration -eq "Server"))
                    {
                        "/p:ENV_SETTINGS=`"$($envSettings)`""
                    }),
                $(if ($PSBoundParameters.ContainsKey("TerminateInstances"))
                    {
                        "/p:AutoTerminateInstances=$TerminateInstances"
                    }),
                $(if ($Configuration)
                    {
                        "/p:Configuration=$Configuration"
                    }),
                $(if ($Configuration -eq "Server")
                    {
                        "/p:DeployBizTalkMgmtDB=$DeployBTMgmtDB"
                    }),
                $(if ($PSBoundParameters.ContainsKey("SkipBizTalkRestart"))
                    {
                        "/p:SkipHostInstancesRestart=$SkipBizTalkRestart"
                    }),
                $(if ($PSBoundParameters.ContainsKey("SkipIISRestart"))
                    {
                        "/p:SkipIISReset=$SkipIISRestart"
                    }),
                $(if ($PSBoundParameters.ContainsKey("SkipUnDeploy"))
                    {
                        "/p:SkipUndeploy=$SkipUnDeploy"
                    }),
                $(if ($PSBoundParameters.ContainsKey("SkipApplicationStart"))
                    {
                        "/p:StartApplicationOnDeploy=$(-not $SkipApplicationStart)"
                        "/p:StartReferencedApplicationsOnDeploy=$(-not $SkipApplicationStart)"
                    }),
                "/l:FileLogger,Microsoft.Build.Engine;logfile=`"$resultsPath`""
                if ($PSCmdlet.ShouldProcess($btdfProject, "Deploy BTDF packaged application"))
                {
                    Invoke-MSBuild -Project $btdfProject `
                        -ArgumentList $msbuildArgs `
                        -Version 4.0 `
                        -Run32Bit `
                        -ErrorAction Stop
                }
            }
            #endregion

            #region Restore back referenced applications in reverse
            if ($SkipRestore -and ($backRefs.Count -gt 0))
            {
                Write-Verbose "Skipping restore"
            }

            if (($backRefs.Count -gt 0) -and ($DeploymentType -eq "Deploy") -and (-not $SkipRestore))
            {
                Write-Debug "Back References Count = $($backRefs.Count)"
                while (($backRefs.Count -gt 0) -and ($DeploymentType -eq "Deploy"))
                {
                    $app = $backRefs.Pop()
                    Write-Verbose "Restoring: $($app.Name)"
                    $deployParams = $PSBoundParameters
                    $deployParams["ProjectPath"] = $app.ProjectPath
                    $deployParams["DeploymentType"] = $DeploymentType
                    $deployParams["Configuration"] = $Configuration
                    if ($PSCmdlet.ShouldProcess($app.Name, "Restoring BizTalk Application"))
                    {
                        Deploy-BTDFApplication @deployParams
                    }
                }
            }
            #endregion
        }
    }
}

<#
.SYNOPSIS
    Installs a BTDF packaged BizTalk application to the specified directory and deploys
 
.DESCRIPTION
    Requires Admin rights locally and for BizTalk. Locally installs a BTDF packaged BizTalk application to the specified directory and deploys. Deployment can be configured to support multi-server setups (install and gac assemblies on secondary nodes and register to BizTalk on primary node). This also takes into account applications which references an application to be upgraded and will strip and redeploy these. Supports configuration of multiple environments which are validated (cmdlet will need to be modified to support additional environments)
 
.PARAMETER MsiFile
    Path to the MsiFile
 
.PARAMETER TargetDir
    Path for the directory to install the application. The application will be installed WITHIN the specified folder rather than autocreating a folder
 
.PARAMETER DeploymentType
    Choose whether to DEPLOY and UNDEPLOY the BizTalk application (Default is DEPLOY)
 
.PARAMETER Environment
    Select the environment to deploy. Must match what is configured in BTDF environmentsettings spreadsheet(Defaults to Local)(Alter validated set if needed)
 
.PARAMETER DeployBTMgmtDB
    Registers application in BizTalk (Without this only the assemblies/components are GACed)
 
.PARAMETER SkipUnDeploy
    Skip undeploying application prior to deployment (deploy only instead of redeploy)
 
.PARAMETER SkipBizTalkRestart
    If supported by deployment project, skip restarting BizTalk Host instances post-deployment
 
.PARAMETER SkipIISRestart
    If supported by deployment project, skip IISReset post-deployment
 
.PARAMETER SkipApplicationStart
    If supported by deployment project, don't start application after deployment
 
.PARAMETER TerminateInstances
    If supported by deployment project, terminate running/suspended instances
 
.PARAMETER SkipRestore
    Skips restoring dependant applciations, if any
 
.EXAMPLE
    Install application components/assemblies
 
    C:\PS> Install-BTDFApplication -MsiFile C:\Deployments\Scratchpad.msi -TargetDir "C:\Program Files (x86)\Scratchpad"
 
.EXAMPLE
    Install application and register in BizTalk
 
    C:\PS> Install-BTDFApplication -MsiFile C:\Deployments\Scratchpad.msi -TargetDir "C:\Program Files (x86)\Scratchpad" -DeployBTMgmtDB
 
.EXAMPLE
    Install application and register in BizTalk with live environment settings
 
    C:\PS> Install-BTDFApplication -MsiFile C:\Deployments\Scratchpad.msi -TargetDir "C:\Program Files (x86)\Scratchpad" -Environment Prod -DeployBTMgmtDB
 
.EXAMPLE
    Undeploys application and removes from BizTalk
 
    C:\PS> Install-BTDFApplication -MsiFile C:\Deployments\Scratchpad.msi -TargetDir "C:\Program Files (x86)\Scratchpad" -DeploymentType UnDeploy -DeployBTMgmtDB
#>

function Install-BTDFApplication
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        [Parameter(Position = 0, Mandatory = $true, HelpMessage = "Path to existing BTDF MSI")]
        [ValidateScript( { Test-Path -Path $_.Fullname -PathType Leaf -Include *.msi })]
        [System.IO.FileInfo]$MsiFile,

        [Parameter(Position = 1, Mandatory = $true, HelpMessage = "Path wherein the resource files will be installed")]
        [System.IO.DirectoryInfo]$TargetDir,

        [Parameter(HelpMessage = "Valid parameters as Deploy, Undeploy, UpdateOrchestration. Defaults to Deploy")]
        [ValidateSet("Deploy", "UnDeploy", "UpdateOrchestration")]
        [string]$DeploymentType = "Deploy",

        [Parameter(HelpMessage = "Valid parameters are Local, Dev, Int, UAT, Train and Prod. Defaults to Local")]
        [ValidateSet("Local", "Dev", "Int", "UAT", "Train", "Prod")]
        [string]$Environment = "Local",

        [Parameter(HelpMessage = "Register artifacts in BizTalk DB")]
        [switch]$DeployBTMgmtDB,
  
        [Parameter(HelpMessage = "Only deploy instead of redeploy")]
        [switch]$SkipUnDeploy,

        [Parameter(HelpMessage = "Skip starting BizTalk hosts back up post deployment")]
        [switch]$SkipBizTalkRestart,

        [Parameter(HelpMessage = "Skip IISReset post deployment")]
        [switch]$SkipIISRestart,

        [Parameter(HelpMessage = "Skipping starting BizTalk app post deployment")]
        [switch]$SkipApplicationStart,

        [Parameter(HelpMessage = "Terminate instances related to deployed app")]
        [switch]$TerminateInstances,

        [Parameter(HelpMessage = "Skip restoring dependant applications")]
        [switch]$SkipRestore
    )
    Process
    {
        $TargetDir = Install-MsiFile -MsiFile $MsiFile -TargetDir $TargetDir

        #region Build splat params
        $splatParams = @{ }
        if ($PSBoundParameters.ContainsKey("DeployBTMgmtDB"))
        {
            $splatParams.Add("DeployBTMgmtDB", $DeployBTMgmtDB)
        }
        if ($PSBoundParameters.ContainsKey("SkipUndeploy"))
        {
            $splatParams.Add("SkipUndeploy", $SkipUndeploy)
        }
        if ($PSBoundParameters.ContainsKey("SkipBizTalkRestart"))
        {
            $splatParams.Add("SkipBizTalkRestart", $SkipBizTalkRestart)
        }
        if ($PSBoundParameters.ContainsKey("SkipIISRestart"))
        {
            $splatParams.Add("SkipIISRestart", $SkipIISRestart)
        }
        if ($PSBoundParameters.ContainsKey("SkipApplicationStart"))
        {
            $splatParams.Add("SkipApplicationStart", $SkipApplicationStart)
        }
        if ($PSBoundParameters.ContainsKey("TerminateInstances"))
        {
            $splatParams.Add("TerminateInstances", $TerminateInstances)
        }
        if ($PSBoundParameters.ContainsKey("SkipRestore"))
        {
            $splatParams.Add("SkipRestore", $SkipRestore)
        }
        #endregion
            
        Deploy-BTDFApplication -ProjectPath  $TargetDir `
            -Configuration "Server" `
            -DeploymentType $DeploymentType `
            -Environment $Environment `
            @splatParams
    }
}
#endregion

#region SSO

<#
.SYNOPSIS
    Read BTDF SSO settings for deployed BizTalk applications
 
.DESCRIPTION
    Makes use of BTDF SSOSettingsFileReader helper assembly to read all SSO settings for a deployed application
 
.PARAMETER Application
    Name of the BTDF deployed application to read SSO settings
 
.EXAMPLE
    PS C:\> Read-SSO -Application Scratchpad
    Returns a hashtable of SSO settings for the Scratchpad application
 
.OUTPUTS
    Hashtable
#>

function Read-SSO
{
    [CmdletBinding()]
    [OutputType([hashtable])]
    Param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [string]$Application
    )
    Process
    {
        return [SSOSettingsFileReader]::Read($Application)
    }
}

<#
.SYNOPSIS
    Read BTDF SSO settings for deployed BizTalk applications
 
.DESCRIPTION
    Makes use of BTDF SSOSettingsFileReader helper assembly to read all SSO settings for a deployed application
 
.PARAMETER Application
    Name of the BTDF deployed application to read SSO settings
 
.PARAMETER Value
    Name of the SSO setting to get the value of
 
.EXAMPLE
    PS C:\> Read-SSO -Application Scratchpad -Value NumberSetting
    Returns a int typed value from SSO for the Scatchpad appliction for the setting "NumberSetting"
 
.OUTPUTS
    int
#>

function Read-SSOInt32
{
    [CmdletBinding()]
    [OutputType([int])]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
        [string]$Application,
        [Parameter(Mandatory = $true, Position = 1)]
        [string]$Value
    )
    Process
    {
        return [SSOSettingsFileReader]::ReadInt32($Application, $Value)
    }
}

<#
.SYNOPSIS
    Read BTDF SSO settings for deployed BizTalk applications
 
.DESCRIPTION
    Makes use of BTDF SSOSettingsFileReader helper assembly to read all SSO settings for a deployed application
 
.PARAMETER Application
    Name of the BTDF deployed application to read SSO settings
 
.PARAMETER Value
    Name of the SSO setting to get the value of
 
.EXAMPLE
    PS C:\> Read-SSO -Application Scratchpad -Value StringSetting
    Returns a string typed value from SSO for the Scatchpad appliction for the setting "StringSetting"
 
.OUTPUTS
    string
#>

function Read-SSOString
{
    [CmdletBinding()]
    [OutputType([string])]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
        [string]$Application,
        [Parameter(Mandatory = $true, Position = 1)]
        [string]$Value
    )
    Process
    {
        return [SSOSettingsFileReader]::ReadString($Application, $Value)
    }
}

<#
.SYNOPSIS
    Write settings to BTDF SSO for deployed BizTalk applications
 
.DESCRIPTION
    Makes use of BTDF SSOSettingsFileReader helper assembly to read all SSO settings for a deployed application
 
.PARAMETER Application
    Name of the BTDF deployed application to read SSO settings
 
.PARAMETER Setting
    Name of the setting to write to. Will create the setting if it doesn't already exist
 
.PARAMETER Value
    Name of the SSO setting to get the value of
 
.EXAMPLE
    PS C:\> Write-SSOSetting -Application Scratchpad -Setting StringSetting -Value StringValue
    Returns a string typed value from SSO for the Scatchpad appliction for the setting "StringSetting"
 
.OUTPUTS
    string
#>

function Write-SSOSetting
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
        [string]$Application,
        [Parameter(Mandatory = $true, Position = 1)]
        [string]$Setting,
        [Parameter(Mandatory = $true, Position = 2)]
        [string]$Value
    )
    Process
    {
        [SSOSettingsFileManager.SSOSettingsManager]::WriteSetting($Application, $Setting, $Value)
    }
}
#endregion

#region Private
function Connect-BTSCatalog
{
    [CmdletBinding()]
    [OutputType([Microsoft.BizTalk.ExplorerOM.BtsCatalogExplorer])]
    Param (
        [Parameter()]
        [string]$Server = $env:COMPUTERNAME,
        [Parameter()]
        [string]$SQLInstance,
        [Parameter()]
        [string]$ManagementDB
    )
    Process
    {        
        #Calculate BizTalk connection string
        $wmi = Get-WmiObject -Class MSBTS_GroupSetting -Namespace root\MicrosoftBizTalkServer -ComputerName $server -ErrorAction Stop
        if (-not $SQLInstance)
        {
            $SQLInstance = $wmi.MgmtDbServerName
        }
        if (-not $ManagementDB)
        {
            $ManagementDB = $wmi.MgmtDbName
        }

        $btsCatalog = [Microsoft.BizTalk.ExplorerOM.BtsCatalogExplorer]::new()
        $btsCatalog.ConnectionString = "SERVER=$SQLInstance;DATABASE=$ManagementDB;Integrated Security=SSPI"

        return $btsCatalog
    }
}

Function Install-MsiFile
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true)]
        [ValidateScript( { Test-Path -Path $_ -PathType Leaf -Include *.msi })]
        [string]$MsiFile,

        [Parameter()]
        [ValidateNotNullorEmpty()]
        [string]$TargetDir,

        [Parameter()]
        [ValidateNotNullorEmpty()]
        [System.Collections.Generic.List[string]]$ArgumentList
    )
    Process
    {
        $ArgumentList += "/i",
        "`"$msiFile`"",
        $(if ($targetDir)
            {
                "INSTALLDIR=`"$targetDir`""
            }),
        "ADDLOCAL=ALL",
        "/qn",
        "/norestart"

        Write-Verbose "Installing MSI File..."
        $process = Invoke-Process -FilePath "$env:windir\System32\msiexec.exe" -ArgumentList $ArgumentList

        switch ($process.ExitCode)
        {
            0
            {
                Write-Verbose "MSI been successfully installed"
            }
            Default
            {
                Write-Error "Installing $MsiFile failed!, Exit Code: $($process.ExitCode)"
            }
        }
        return $TargetDir
    }
}

function Invoke-MSBuild
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
        [ValidateScript( { Test-Path -Path $_ -PathType Leaf -Include *.*proj })]
        [string]$Project,
        
        [Parameter(Position = 1)]
        [System.Collections.Generic.List[string]]$ArgumentList,

        [Parameter()]
        [switch]$Run32Bit

        # [Parameter()]
        # [ValidateNotNullOrEmpty()]
        # [ValidateScript({[version]::Parse($_)})]
        # [string]$Version
    )
    DynamicParam
    {
        $msbuildReg = if ($Run32Bit -and ($env:PROCESSOR_ARCHITECTURE -eq "AMD64"))
        {
            Get-Item -Path "HKLM:\SOFTWARE\Wow6432Node\Microsoft\MSBuild\ToolsVersions"
        }
        else
        {
            Get-Item -Path "HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions"
        }

        $versions = $msbuildReg | Get-ChildItem | Get-ItemProperty | Sort-Object -Property @{Expression = { [version]::Parse($_.PSChildName) } } -Descending

        $paramDict = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary

        #region Version
        $attributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
        $parameter = New-Object System.Management.Automation.ParameterAttribute
        $attributeCollection.Add($parameter)
        $validateSet = New-Object System.Management.Automation.ValidateSetAttribute($versions | Select-Object -ExpandProperty PSChildName)
        $attributeCollection.Add($validateSet)
        $versionParameter = New-Object System.Management.Automation.RuntimeDefinedParameter("Version", [string], $attributeCollection)
        $paramDict.Add("Version", $versionParameter)
        #endregion

        return $paramDict
    }
    Process
    {
        $versionsHash = @{ }
        $versions | ForEach-Object {
            $versionsHash[$($_.PSChildName)] = $_.MSBuildToolsPath
        }

        $version = if (-not $PSBoundParameters.ContainsKey("Version"))
        {
            $versions[0].PSChildName
        }
        else
        {
            $PSBoundParameters.Version
        }
        Write-Debug "Version = $version"

        $msbuildFolder = $versionsHash[$version]
        Write-Debug "MSBuildFolder = $msbuildFolder"
        $msbuild = Join-Path -Path $msbuildFolder -ChildPath "msbuild.exe"
        $ArgumentList = "`"$Project`"",
        $ArgumentList,
        "/p:UseSharedCompilation=false",
        "/noLogo",
        "/maxcpucount:1",
        "/nodeReuse:false"
        Invoke-Process -FilePath $msbuild -ArgumentList $ArgumentList | Out-Null
    }
} 

function Invoke-Process
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [ValidateScript( { Test-Path -Path $_ -PathType Leaf -Include *.* })]
        [System.IO.FileInfo]$FilePath,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string[]]$ArgumentList
    )
    Process
    {
        $stdOutTempFile = "$env:TEMP\$((New-Guid).Guid)"
        $stdErrTempFile = "$env:TEMP\$((New-Guid).Guid)"

        Write-Verbose "Invoking $($FilePath.Name)"
        $processParams = @{
            "FilePath"    = $FilePath.FullName
            "Wait"        = $true
            "PassThru"    = $true
            "NoNewWindow" = $true
        }
        Write-Debug "FilePath = $($FilePath.FullName)"
        if ($ArgumentList)
        {
            $processParams.Add("ArgumentList", $ArgumentList)
            Write-Debug "ArgumentList = $ArgumentList"
        }

        #Redirect output if executed remotely
        if ((Get-Host).Name -eq "ServerRemoteHost")
        {
            $processParams["RedirectStandardOutput"] = $stdOutTempFile
            $processParams["RedirectStandardError"] = $stdErrTempFile
            Write-Debug "TempStdOutput = $stdOutTempFile"
            Write-Debug "TempStdError = $stdErrTempFile"
        }

        try
        {
            $process = Start-Process @processParams

            switch ($process.ExitCode)
            {
                0
                {
                    Write-Verbose "Process has been successfully run"
                    return $process
                }
                Default
                {
                    throw "Process failed!, Exit Code: $($process.ExitCode)"
                }
            }
        }
        catch
        {
            throw $_
        }
        finally
        {
            if ((Get-Host).Name -eq "ServerRemoteHost")
            {
                $processOutput = (Get-Content -Path $stdOutTempFile -Raw)
                $processError = Get-Content -Path $stdErrTempFile -Raw
                if ($processOutput)
                {
                    Write-Information $processOutput
                }
                if ($processError)
                {
                    Write-Error $processError
                }
            }

            Remove-Item -Path $stdOutTempFile, $stdErrTempFile `
                -Force `
                -Verbose:$false `
                -ErrorAction Ignore `
        
        }
    }
}
#endregion

#region Variables
$btsCatalog = Connect-BTSCatalog

$projectPathColumn = @{Name = "ProjectPath"; Expression = { Read-SSOString -Application $_.Name -Value "ProjectPath" } }

$softwareReg32 = if ($env:PROCESSOR_ARCHITECTURE -eq "AMD64")
{
    Get-Item -Path HKLM:\SOFTWARE\Wow6432Node
}
else
{
    Get-Item -Path HKLM:\SOFTWARE
}
#endregion