-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCommon.ps1
More file actions
2519 lines (2269 loc) · 107 KB
/
Copy pathCommon.ps1
File metadata and controls
2519 lines (2269 loc) · 107 KB
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
# Copyright (c) Microsoft
# All rights reserved.
# Microsoft Limited Public License:
# This license governs use of the accompanying software. If you use the software, you
# accept this license. If you do not accept the license, do not use the software.
# 1. Definitions
# The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
# same meaning here as under U.S. copyright law.
# A "contribution" is the original software, or any additions or changes to the software.
# A "contributor" is any person that distributes its contribution under this license.
# "Licensed patents" are a contributor's patent claims that read directly on its contribution.
# 2. Grant of Rights
# (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
# (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
# 3. Conditions and Limitations
# (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
# (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
# (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
# (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
# (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
# (F) Platform Limitation - The licenses granted in sections 2(A) and 2(B) extend only to the software or derivative works that you create that run on a Microsoft Windows operating system product.
#File version: 1.0.2.0
function Get-OverrideParameters
{
$RunDeployParmFile = (Join-Path $AxBuildDir "OverrideParameters.txt")
if ((Test-Path $RunDeployParmFile) -ne $false)
{
$fileContent = Get-Content $RunDeployParmFile
foreach ($line in $fileContent)
{
$line = $line.split("=")
[System.Environment]::SetEnvironmentVariable($line[0],$line[1])
}
}
$script:CompileCILTimeout = [int](Set-Parameter "CompileCILTimeout" "60" )
$script:SyncTimeout = [int](Set-Parameter "SyncTimeout" "60" )
$script:ImportTimeout = [int](Set-Parameter "ImportTimeout" "60" )
$script:CombineTimeout = [int](Set-Parameter "CombineTimeout" "60" )
$script:AOSRestartTimeout = [int](Set-Parameter "AOSRestartTimeout" "60" )
$script:CompileAllTimeout = [int](Set-Parameter "CompileAllTimeout" "360" )
$script:SetupRegistryPath = (Set-Parameter "SetupRegistryPath" "HKLM:\SOFTWARE\Microsoft\Dynamics\6.0\Setup" )
$script:ServerRegistryPath = (Set-Parameter "ServerRegistryPath" "HKLM:\SYSTEM\CurrentControlSet\services\Dynamics Server\6.0" )
$script:ClientRegistryPath = (Set-Parameter "ClientRegistryPath" "HKCU:\SOFTWARE\Microsoft\Dynamics\6.0\Configuration" )
$script:labelsFolder = (Set-Parameter "LabelsFolder" "label files" )
}
function Get-ImportOverrideParameters
{
Write-InfoLog ("Start Get-ImportOverrideParameters : {0}" -f (Get-Date))
$RunDeployParmFile = (Join-Path $AxBuildDir "ImportOverrideParameters.txt")
if ((Test-Path $RunDeployParmFile) -ne $false)
{
$script:importOverrideParams = @{}
$fileContent = Get-Content $RunDeployParmFile
if ($fileContent -ne $null)
{
Write-InfoLog ("Override file content :")
Write-InfoLog $fileContent
foreach ($line in $fileContent)
{
$line = $line.split("=")
$importOverrideParams.Set_Item($line[0].Trim(),$line[1].Trim())
}
}
}
Write-InfoLog ("Import override params:")
Write-InfoLog $importOverrideParams
Write-InfoLog ("End Get-ImportOverrideParameters : {0}" -f (Get-Date))
}
function Set-Parameter($name, $defaultVal)
{
$value = GetEnvironmentVariable($name)
if($value -eq $null)
{
$value = $defaultVal
}
$value
}
function Write-InfoLog($message)
{
Write-Output ($message)
}
function Write-ErrorLog($message)
{
Write-InfoLog (" ")
Write-InfoLog ("ERROR: *********")
Write-InfoLog ($message)
Write-InfoLog ("****************")
Write-InfoLog (" ")
if($transcriptStarted -eq $true)
{
if($scriptName -eq 'DEPLOY')
{
if($currentLogFolder -ne $null)
{
$message | out-file -append (join-path $currentLogFolder 'DeployErrors.err')
}
}
else
{
if($dropLocation -ne $null)
{
$message | out-file -append (join-path $dropLocation 'BuildErrors.err')
}
}
}
}
function Write-TerminatingErrorLog($message, $errorMsg)
{
Write-ErrorLog $message
Write-InfoLog $errorMsg
if($buildModelStarted -eq $true)
{
$script:buildModelStarted = $false
try
{
if($NoCleanOnError -ne $true)
{
Write-InfoLog (" ")
Write-InfoLog ("*****************************************************************")
Write-InfoLog ("****************TRYING TO REVERT BUILD***************************")
Clean-Build
Write-InfoLog ("*****************************************************************")
Write-InfoLog ("*****************************************************************")
Write-InfoLog (" ")
}
}
catch
{
Write-ErrorLog ("Failed to revert build.")
Write-ErrorLog ($Error[0])
}
}
Write-InfoLog ("{0} Failed" -f $scriptName)
Exit
}
function Register-SQLSnapIn
{
Write-InfoLog ("Begin: Register-SQLSnapIn: {0}" -f (Get-Date))
if ( Get-PSSnapin -Registered | where {$_.name -eq 'SqlServerProviderSnapin100'} )
{
if( !(Get-PSSnapin | where {$_.name -eq 'SqlServerProviderSnapin100'}))
{
Add-PSSnapin SqlServerProviderSnapin100 | Out-Null
}
if( !(Get-PSSnapin | where {$_.name -eq 'SqlServerCmdletSnapin100'}))
{
Add-PSSnapin SqlServerCmdletSnapin100 | Out-Null
}
}
else
{
if( !(Get-Module | where {$_.name -eq 'sqlps'}))
{
Import-Module 'sqlps' –DisableNameChecking
}
}
Write-InfoLog ("End: Register-SQLSnapIn: {0}" -f (Get-Date))
}
function Check-PowerShellVersion
{
$pv = get-host
if($pv -ne $null -and $pv.Version -ne $null -and $pv.Version.Major -ne 2)
{
Write-TerminatingErrorLog ("Powershell version {0} not supported." -f $pv.Version.Major)
}
}
function GetEnvironmentVariable($variableName)
{
if ([System.Environment]::GetEnvironmentVariable($variableName) -ne $null)
{
([System.Environment]::GetEnvironmentVariable($variableName).Trim())
}
}
function Create-CurrentLogFolder
{
$date = "Logs" + (Get-Date)
$date = $date.Replace(' ', '')
$date = $date.Replace('/', '')
$date = $date.Replace(':', '')
$script:currentLogFolder = (join-path $logFolder $date)
New-Item $currentLogFolder -type directory
}
function Create-BuildFolders
{
if ((Test-Path (Join-Path $dropLocation $currentVersion)) -eq $false) {$n = New-Item (Join-Path $dropLocation $currentVersion) -ItemType directory}
$script:dropLocation = join-path $dropLocation $currentVersion
if ((Test-Path (Join-Path $dropLocation "Logs")) -eq $false) {$n = New-Item (Join-Path $dropLocation "Logs") -ItemType directory}
$script:currentLogFolder = join-path $dropLocation "Logs"
if ((Test-Path (Join-Path $currentLogFolder "DetailedLogs")) -eq $false) {$n = New-Item (Join-Path $currentLogFolder "DetailedLogs") -ItemType directory}
if ((Test-Path (Join-Path $dropLocation "Application")) -eq $false) {$n = New-Item (Join-Path $dropLocation "Application") -ItemType directory}
if ((Test-Path (Join-Path $dropLocation "Application\bin")) -eq $false) {$n = New-Item (Join-Path $dropLocation "Application\bin") -ItemType directory}
if ((Test-Path (Join-Path $dropLocation "Application\Appl")) -eq $false) {$n = New-Item (Join-Path $dropLocation "Application\Appl") -ItemType directory}
if ((Test-Path (Join-Path $dropLocation "VSProjBin")) -eq $false) {$n = New-Item (Join-Path $dropLocation "VSProjBin") -ItemType directory}
$script:vsProjBinFolder = join-path $dropLocation "VSProjBin"
}
############################################################################################
#COMMON AX FUNCTIONS
############################################################################################
function Synchronize-AX($tableId = 0)
{
Write-InfoLog ("Start synchronize : {0}" -f (Get-Date))
$SynchStartTime = Get-Date
if ($tableId -eq 0)
{
$arguments = '-lazyclassloading -lazytableloading -StartupCmd=Synchronize -internal=noModalBoxes'
}
else
{
# We make use of interpolation here
$arguments = "-lazyclassloading -lazytableloading -StartupCmd=Synchronize_$tableId -internal=noModalBoxes"
}
Write-InfoLog ("Calling Start-Process Synchronize: {0}" -f (Get-Date))
$axProcess = Start-Process $ax32 -WorkingDirectory $clientBinDir -PassThru -WindowStyle minimized -ArgumentList $arguments -OutVariable out
Write-InfoLog $out
if ($axProcess.WaitForExit(60000*$SyncTimeout) -eq $false)
{
Write-ErrorLog("Error: AX synchronize did not complete within {0} minutes" -f $SyncTimeout)
$axProcess.Kill()
foreach($event in Get-EventLog Application | Where-Object {$_.Source -match "Dynamics Server" -and $_.EntryType -eq "Error" -and $_.Timegenerated -gt $SynchStartTime})
{
Write-ErrorLog($event.Message.Substring($event.Message.IndexOf('[SQL Server]')+'[SQL Server]'.get_length()))
}
Write-TerminatingErrorLog("Synchronize doesn't finished on time. Stopping the build")
}
Write-InfoLog ("Synchronize finished : {0}" -f (Get-Date))
Write-InfoLog (" ")
}
function Stop-AOS
{
Write-InfoLog ("Begin: Stop-AOS method : {0}" -f (Get-Date))
$startDateTime = $(get-date)
Write-InfoLog ("Calling Get-WmiObject Win32_Service: {0}" -f (Get-Date))
$aos = Get-WmiObject Win32_Service -ComputerName $AxAOSServerName -Filter "name=""$AOSName""" -OutVariable out -Verbose
Write-InfoLog $out
if ($aos.State -ne [system.ServiceProcess.ServiceControllerStatus]::Stopped)
{
Write-InfoLog ("Stopping AOS")
$rv = $aos.StopService().ReturnValue
if ($rv -ne 0) {
Write-TerminatingErrorLog ("AOS cannot be stopped. Got error code {0}" -f $rv)
}
}
Write-InfoLog ("Calling Get-WmiObject Win32_Service: {0}" -f (Get-Date))
$aos = Get-WmiObject Win32_Service -ComputerName $AxAOSServerName -Filter "name=""$AOSName""" -OutVariable out -Verbose
Write-InfoLog $out
while ($aos.State -ne [system.ServiceProcess.ServiceControllerStatus]::Stopped)
{
if (($(get-date) - $startDateTime).get_Minutes() -gt $AOSRestartTimeout)
{
Write-TerminatingErrorLog('The AOS can not be stopped after {0} minutes.' -f $AOSRestartTimeout)
break
}
Start-Sleep 20
Write-InfoLog ("Calling Get-WmiObject Win32_Service: {0}" -f (Get-Date))
$aos = Get-WmiObject Win32_Service -ComputerName $AxAOSServerName -Filter "name=""$AOSName""" -OutVariable out -Verbose
Write-InfoLog $out
}
Write-InfoLog ("End: Stop-AOS method : {0}" -f (Get-Date))
Write-InfoLog (" ")
}
function Start-AOS
{
Write-InfoLog ("Begin: Start-AOS method : {0}" -f (Get-Date))
$startDateTime = $(get-date)
Write-InfoLog ("Calling Get-WmiObject Win32_Service: {0}" -f (Get-Date))
$aos = Get-WmiObject Win32_Service -ComputerName $AxAOSServerName -Filter "name=""$AOSName""" -OutVariable out
Write-InfoLog $out
Write-InfoLog ("Current AOS state : {0}" -f ($aos.State))
if ($aos.State -ne [system.ServiceProcess.ServiceControllerStatus]::Running)
{
Write-InfoLog ("Starting AOS")
$rv = $aos.StartService().ReturnValue
if ($rv -ne 0) {
Write-TerminatingErrorLog ("AOS service can't be started. Got error code {0}" -f $rv)
}
}
Write-InfoLog ("Calling Get-WmiObject Win32_Service: {0}" -f (Get-Date))
$aos = Get-WmiObject Win32_Service -ComputerName $AxAOSServerName -Filter "name=""$AOSName""" -OutVariable out
Write-InfoLog $out
while ($aos.State -ne [system.ServiceProcess.ServiceControllerStatus]::Running)
{
if ($aos.State -eq [system.ServiceProcess.ServiceControllerStatus]::Stopped)
{
# Start AOS one more time in case it stopped for some reason during the process of starting
Write-InfoLog ("Starting AOS")
$rv = $aos.StartService().ReturnValue
if ($rv -ne 0) {
Write-TerminatingErrorLog ("AOS service can't be started. Got error code {0}" -f $rv)
}
}
if (($(get-date) - $startDateTime).get_Minutes() -gt $AOSRestartTimeout)
{
Write-TerminatingErrorLog('The AOS can not be started after {0} minutes.' -f $AOSRestartTimeout)
break
}
Start-Sleep 20
Write-InfoLog ("Calling Get-WmiObject Win32_Service: {0}" -f (Get-Date))
$aos = Get-WmiObject Win32_Service -ComputerName $AxAOSServerName -Filter "name=""$AOSName""" -OutVariable out
Write-InfoLog $out
}
Write-InfoLog ("End: Start-AOS method : {0}" -f (Get-Date))
Write-InfoLog (" ")
}
function Read-AXClientConfiguration
{
$Path = $clientRegistryPath
$Path = Join-Path $Path (Get-ItemProperty (get-item ($Path)).PSPath).Current
$script:clientBinDir = (Get-ItemProperty (get-item ($Path)).PSPath).bindir.TrimEnd('\')
$script:clientLogDir = (Get-ItemProperty (get-item ($Path)).PSPath).logdir.TrimEnd('\')
$script:AxAOS = (Get-ItemProperty (get-item ($Path)).PSPath).aos2
$script:clientLogDir = [System.Environment]::ExpandEnvironmentVariables("$clientLogDir")
$script:clientBinDir = [System.Environment]::ExpandEnvironmentVariables("$clientBinDir")
$script:ax32 = join-path $clientBinDir "ax32.exe"
$parts = ($AxAOS.Split(';')[0]).Split('@')
if($parts.Length -eq 2)
{
$AxAOSServerName = $parts[1]
$AxAOSInstance = $parts[0]
}
elseif($parts.Length -eq 1) { $AxAOSServerName = $parts[0] }
$parts = $AxAOSServerName.Split(':')
if($parts.Length -eq 2) {
$AxAOSServerName = $parts[0]
$port = $parts[1] }
elseif($parts.Length -eq 1) { $AxAOSServerName = $parts[0] }
$script:AxAOSServerName = $AxAOSServerName
$script:AxAOSInstance = $AxAOSInstance
$script:port = $port
}
function Read-AxServerConfiguration
{
if($env:computername -eq $axaosservername)
{
$serverPath = $serverRegistryPath
foreach ($item in Get-ChildItem $serverPath)
{
$subpath = Join-Path $serverPath $item.PSChildName
$InstanceName = (Get-ItemProperty (get-item ($subPath)).PSPath).InstanceName
if ( ($AxAOSInstance -eq $null) -or ($InstanceName -eq $AxAOSInstance) -or ($portNumber -eq $port))
{
$AOSName = $script:AOSname = "AOS60`${0}" -f $item.PSChildName #The ` character makes powershell know that the next character is to be handled as a part of the string
$script:aosNumber = "{0}" -f $item.PSChildName
$CurrentServerConfig = (Get-ItemProperty (get-item ($subPath)).PSPath).current
$Path = Join-Path $subPath $CurrentServerConfig
$portNumber = (Get-ItemProperty (get-item ($Path)).PSPath).port
if( $port -eq $null -or ($portNumber -eq $port))
{
$script:sqlServer = (Get-ItemProperty (get-item ($Path)).PSPath).dbserver
$script:sqlDatabase = (Get-ItemProperty (get-item ($Path)).PSPath).database
$script:sqlModelDatabase = $sqlDatabase
if( (Get-ItemProperty (get-item ($Path)).PSPath).split_modeldb -ne $null -and (Get-ItemProperty (get-item ($Path)).PSPath).split_modeldb -eq '1')
{
$script:sqlModelDatabase = "{0}_model" -f $sqlDatabase
}
$script:serverBinDir = (Get-ItemProperty (get-item ($Path)).PSPath).bindir.TrimEnd('\')
$script:serverLogDir = (Get-ItemProperty (get-item ($Path)).PSPath).logdir.TrimEnd('\')
$script:serverApplDir = (Get-ItemProperty (get-item ($Path)).PSPath).directory + "\Appl\" +
(Get-ItemProperty (get-item ($Path)).PSPath).application
$script:AxAOSServerName = $AxAOSServerName
$script:axBuild = Join-Path $serverBinDir "AXBuild.exe"
break #Break once we've found the matching AOS server
}
}
}
}
}
############################################################################################
#END COMMON AX FUNCTIONS
############################################################################################
############################################################################################
#COMPILE-AX
############################################################################################
function Compile-Build
{
try
{
#Step: Compile layer
if ($AxCompileAll -eq "True")
{
$script:compileErrors = $false
$aolParm = ''
$compileInLayerParm = ''
if($compileInLayer -ne $null)
{
$AolCode = Get-AolCode $compileInLayer
if ($aolCode -ne '') {$aolParm = '-aolCode={0}' -f $aolCode}
$compileInLayerParm = '-aol={0}' -f $compileInLayer
}
Stop-AOS
$arguments = 'xppcompileall /s={0}' -f $script:aosNumber
#$arguments = '{0} {1} -lazyclassloading -lazytableloading -StartupCmd=compileall -novsprojcompileall -internal=noModalBoxes' -f $compileInLayerParm,$aolParm
Write-InfoLog ("Calling CompileAll API : {0}" -f (Get-Date))
#$axProcess = Start-Process $ax32 -WorkingDirectory $clientBinDir -PassThru -WindowStyle minimized -ArgumentList $arguments -OutVariable out
$axBuildProcess = Start-Process $axBuild -WorkingDirectory $serverBinDir -PassThru -WindowStyle minimized -ArgumentList $arguments -OutVariable out
Write-InfoLog $out
Write-InfoLog (" ")
Write-InfoLog (" ")
if ($axBuildProcess.WaitForExit(60000*$CompileAllTimeout) -eq $false)
{
$axBuildProcess.Kill()
Throw ("Error: AX compile did not complete within {0} minutes" -f $CompileAllTimeout)
}
Write-InfoLog ("End of CompileAll API: {0}" -f (Get-Date))
Copy-Item -Path (Join-Path $script:serverLogDir AxCompileAll.html) -Destination (join-path $clientLogDir AxCompileAll_Pass1.html) -Force -ErrorAction SilentlyContinue
Copy-Item -Path (Join-Path $script:serverLogDir AOTprco.log) -Destination (join-path $clientLogDir AOTprco.log) -Force -ErrorAction SilentlyContinue
Copy-Item -Path (Join-Path $script:serverLogDir AOTComp.log) -Destination (join-path $clientLogDir AOTComp.log) -Force -ErrorAction SilentlyContinue
#Step: Compile CIL
if ($CompileCIL -eq 'True')
{
if ($scriptName -eq 'Build')
{
# We need an active AOS for some stuff related to tasks like SetAXConfiguration
Start-AOS
Compile-VSComponents
# Need to restart AOS after compiling VS Components as they produce dlls which are loaded during AOS startup normally
Stop-AOS
# copy compiled dlls to Client & Server Bin dirs
Copy-VSProjectsBinaries
Start-AOS
Write-InfoLog (" ")
Write-InfoLog ("Compiling remaining objects after VS Components have been recompiled")
Write-InfoLog (" ")
$arguments = '{0} {1} -lazyclassloading -lazytableloading -StartupCmd=compilepartial -novsprojcompileall -internal=noModalBoxes' -f $compileInLayerParm,$aolParm
Write-host ("Calling CompilePartial API : {0}" -f (Get-Date))
$axProcess = Start-Process $ax32 -WorkingDirectory $clientBinDir -PassThru -WindowStyle minimized -ArgumentList $arguments -OutVariable out
Write-host $out
Write-InfoLog (" ")
Write-InfoLog (" ")
if ($axProcess.WaitForExit(60000*$CompileAllTimeout) -eq $false)
{
$axProcess.Kill()
Throw ("Error: AX compile partial did not complete within {0} minutes" -f $CompileAllTimeout)
}
}
else
{
# Need to start AOS after AXBuild run in case we are not in the Build script (i.e., in the Deploy script)
Start-AOS
}
Compile-CIL
Write-InfoLog (" ")
Write-InfoLog (" ")
}
#Step
Stop-AOS
Write-InfoLog (" ")
Write-InfoLog (" ")
#Step
Start-AOS
Write-InfoLog (" ")
Write-InfoLog (" ")
#Step
Synchronize-AX
Write-InfoLog (" ")
Write-InfoLog (" ")
}
}
finally
{
if($AxCompileAll -eq $true)
{
#Step
Check-CompilerErrors
Write-InfoLog (" ")
Write-InfoLog (" ")
Write-InfoLog ("Collecting AxCompileAll.html: {0}" -f (Get-Date))
Copy-Item -Path (Join-Path $clientLogDir AxCompileAll.html) -Destination $currentLogFolder -Force -ErrorAction SilentlyContinue
Copy-Item -Path (Join-Path $clientLogDir AOTprco.log) -Destination $currentLogFolder -Force -ErrorAction SilentlyContinue
Copy-Item -Path (Join-Path $clientLogDir AOTcomp.log) -Destination $currentLogFolder -Force -ErrorAction SilentlyContinue
if ($CompileCIL -eq 'True')
{
Check-CILErrors
if((Test-path (join-path $serverBinDir XppIL)) -eq $True)
{
Copy-Item -Path (Join-Path (join-path $serverBinDir XppIL) Dynamics.Ax.Application.dll.log) -Destination $currentLogFolder -Force -ErrorAction SilentlyContinue
}
}
}
}
}
function Compile-AX
{
Write-InfoLog (" ")
Write-InfoLog ("*****************************************************************")
Write-InfoLog ("****************COMPILE AX***************************************")
Write-InfoLog ("Begin: AX compile : {0}" -f (Get-Date))
Write-InfoLog (" ")
Write-InfoLog (" ")
#Step 1: Stop AOS
Stop-AOS
Write-InfoLog (" ")
Write-InfoLog (" ")
#Step 2: Update compiler Info
<#Update-CompilerInfo
Write-InfoLog (" ")
Write-InfoLog (" ")
#>
#Step 3: Delete auc files
Remove-Item -Path (Join-Path $env:LOCALAPPDATA "ax_*.auc") -ErrorAction SilentlyContinue
if((Test-path ($serverBinDir)) -eq $True)
{
$xpplPath = join-path $serverBinDir XppIL
if (((Test-path ($xpplPath)) -eq $True) -and ((Test-path (join-path $xpplPath Dynamics.Ax.Application.dll.log)) -eq $True))
{
Remove-Item -Path (join-path $xpplPath Dynamics.Ax.Application.dll.log) -ErrorAction SilentlyContinue
}
}
#Step 4: Restart AOS
Start-AOS
Write-InfoLog (" ")
Write-InfoLog (" ")
#Step 5: Set model store
Write-InfoLog ("Calling Set-AXModelStore: {0}" -f (Get-Date))
Set-AXModelStore -NoInstallMode -Server $sqlServer -Database $sqlModelDatabase -Verbose
Write-InfoLog (" ")
Write-InfoLog (" ")
Write-InfoLog ("Starting compile : {0}" -f (Get-Date))
Write-InfoLog (" ")
Write-InfoLog (" ")
#Step 6:
#Compile-Build
Synchronize-AX
Write-InfoLog (" ")
Write-InfoLog (" ")
Compile-Build
Write-InfoLog ("Compile finished : {0}" -f (Get-Date))
Write-InfoLog ("End: AX compile : {0}" -f (Get-Date))
Write-InfoLog ("*****************************************************************")
Write-InfoLog ("*****************************************************************")
Write-InfoLog (" ")
}
function Compile-CIL
{
Write-InfoLog ("Starting CIL compile : {0}" -f (Get-Date))
$CilXmlFile = join-path $currentLogFolder 'GenerateIL.XML'
$CilLogFile = join-path $currentLogFolder 'GenerateIL.log'
$newFile = @()
$newFile += '<?xml version="1.0" encoding="utf-8"?>'
$newFile += '<AxaptaAutoRun version="4.0" logFile="{0}">' -f $CilLogFile
$newFile += '<Run type="class" name="SysCompileIL" method="generateIL" parameters="true" />'
$newfile += '</AxaptaAutoRun>'
$newfile | Out-File $CilXmlFile -Encoding Default
$arguments = '-lazyclassloading -lazytableloading "-StartupCmd=autorun_{0}"' -f $CilXmlFile
$axProcess = Start-Process $ax32 -WorkingDirectory $clientBinDir -PassThru -WindowStyle minimized -ArgumentList $arguments
if ($axProcess.WaitForExit(60000*$CompileCILTimeout) -eq $false)
{
$axProcess.Kill()
Throw ("Error: AX CIL compile did not complete within {0} minutes" -f $CompileCILTimeout)
}
try
{
[xml]$LogFile = Get-Content($CilLogFile)
$Infolog = $LogFile.AxaptaAutoRun.Infolog.Split([char]10)
foreach($line in $Infolog)
{
if ($line.Length -gt 0)
{
$i = $line.LastIndexOf([char]9)
if ($i -gt 0) {$line = $line.Substring($i+1)}
if ($line.Contains('Service group started:') -eq $false)
{
if ($line -eq 'The full CIL generation from X++ is done.')
{
Write-InfoLog '. ' + $line
}
else
{
Write-ErrorLog(('Compile-CIL Error ' + $line))
}
}
}
}
}
catch
{
Write-ErrorLog "Exception in Compile-CIL."
Write-ErrorLog $Error[0].Exception
}
Write-InfoLog ("End CIL compile : {0}" -f (Get-Date))
}
function Update-CompilerInfo
{
Write-InfoLog ("Starting update compiler info : {0}" -f (Get-Date))
try
{
#Compiler settings
$query = "select COMPILERWARNINGLEVEL,DEBUGINFO,id from {0}..USERINFO where NETWORKALIAS = '{1}'" -f $sqlDatabase,$env:USERNAME
$table = Invoke-Sqlcmd -Query "$query" -ServerInstance "$SQLserver" -Verbose
if($table -ne $null)
{
foreach($row in $table)
{
$COMPILERWARNINGLEVEL = $row.get_Item('COMPILERWARNINGLEVEL')
$DEBUGINFO = $row.get_Item('DEBUGINFO')
$AxId = $row.get_Item('ID')
}
if (($COMPILERWARNINGLEVEL -ne 4) -or ($DEBUGINFO -ne 524))
{
$query = "update {0}..USERINFO set COMPILERWARNINGLEVEL=4, DEBUGINFO=524 where NETWORKALIAS = '{1}'" -f $sqlDatabase,$env:USERNAME
Invoke-Sqlcmd -Query "$query" -ServerInstance "$SQLserver" -Verbose
}
}
if ($AxId -ne $null)
{
#Best Practise settings
$query = "select LAYERSETTING,WARNINGLEVEL from {0}..SYSBPPARAMETERS where USERID = '{1}'" -f $sqlDatabase,$AxId
$table = Invoke-Sqlcmd -Query "$query" -ServerInstance "$SQLserver" -Verbose
if($table -ne $null)
{
foreach($row in $table)
{
$LayerSetting = $row.get_Item('LAYERSETTING')
$WARNINGLEVEL = $row.get_Item('WARNINGLEVEL')
}
if (($LayerSetting -ne 1) -or ($WARNINGLEVEL -ne 0))
{
$query = "update {0}..SYSBPPARAMETERS set LAYERSETTING=1, WARNINGLEVEL=0 where USERID = '{1}'" -f $sqlDatabase,$AxId
Invoke-Sqlcmd -Query "$query" -ServerInstance "$SQLserver" -Verbose
}
}
}
}
catch{
Write-TerminatingErrorLog "Exception in Update-CompilerInfo" $Error[0]
}
Write-InfoLog ("Done update compiler info : {0}" -f (Get-Date))
}
function Check-CILErrors
{
Write-InfoLog ("Begin Check-CILErrors: {0}" -f (Get-Date))
$xpplPath = join-path $serverBinDir XppIL
if (((Test-path ($xpplPath)) -eq $True) -and ((Test-path (join-path $xpplPath Dynamics.Ax.Application.dll.log)) -eq $True))
{
foreach ($line in (Get-Content (join-path $xpplPath Dynamics.Ax.Application.dll.log)))
{
if($line -ne $null -and $line.Trim() -ne '')
{
if($lastLine -ne $null)
{
$secondLastLine = $lastLine
$lastLine = $line
}
else
{
$lastLine = $line
}
}
}
if($secondLastLine -ne $null)
{
if($secondLastLine.Contains('Errors:') -and $secondLastLine.Split(':')[0].Trim() -eq 'Errors' -and $secondLastLine.Split(':')[1].Trim() -ne 0)
{
Write-ErrorLog "IL Compile errors. See Dynamics.Ax.Application.dll.log file."
}
}
if($lastLine -ne $null)
{
if($lastLine.Contains('Warnings:') -and $lastLine.Split(':')[0].Trim() -eq 'Warnings' -and $lastLine.Split(':')[1].Trim() -ne 0)
{ Write-Warning "Warnings while compiling IL."}
}
}
Write-InfoLog ("End Check-CILErrors: {0}" -f (Get-Date))
}
function Check-CompilerErrors
{
Write-InfoLog ("Begin Check-CompilerErrors: {0}" -f (Get-Date))
$compileErrors = $false
$compileLogFile = (join-path $clientLogDir "AxCompileAll.html")
if ((test-Path $compileLogFile) -eq $true)
{
foreach ($line in (Get-Content $compileLogFile))
{
if (($XMLstarted -eq $true) -and ($line.Contains('</XML>')))
{
$XMLstarted = $false
$xmlContent += $line.Replace('</XML>','')
}
if ($XMLstarted -eq $true)
{
# Add a space inbetween in case we are in the middle of the xml
if ($xmlContent) {$xmlContent += ' '}
$xmlContent += $line.Trim()
}
if ($line -eq '<XML ID="compilerinfo">') {$XMLstarted = $true}
}
$xmlcontent | out-file -filepath (join-path $clientLogDir 'CompileErrors.xml')
[xml]$AxXml = $xmlcontent
foreach($record in $axXml.AxaptaCompilerOutput.Record)
{
if ($record -ne $null -and (($record.field[7]).get_InnerText()) -eq "0")
{
$compileErrors = $true
$line = "Compiler ERROR: {0}\{1} : {2}" -f ($record.field[0]).get_InnerText(),($record.field[6]).get_InnerText(),($record.field[10]).get_InnerText()
Write-ErrorLog($line)
}
}
}
if ($compileErrors -eq $true)
{
Write-ErrorLog "Errors while compiling code."
}
Write-InfoLog ("End Check-CompilerErrors: {0}" -f (Get-Date))
}
function Compile-VSComponents
{
Write-InfoLog ("BEGIN: Compile-VSComponents: {0}" -f (Get-Date))
if($modelLayerMap -ne $null)
{
foreach($m in ($modelLayerMap.GetEnumerator()))
{
if($m -ne $null)
{
foreach($file in $m.Value)
{
$fileInfo = Get-Item -Path $file
if($fileInfo -ne $null)
{
if($fileInfo.Name -eq 'Model.xml')
{
Compile-VisualStudioProjects ($fileInfo)
}
}
}
}
}
}
Write-InfoLog ("END: Compile-VSComponents: {0}" -f (Get-Date))
}
function Compile-VisualStudioProjects([System.IO.FileSystemInfo]$model)
{
Write-InfoLog ("Begin: Compile-VisualStudioProjects: {0}" -f (Get-Date))
$manifest = new-object "System.Xml.XmlDocument"
$manifest.Load($model.FullName)
[String]$modelName=$manifest.SelectSingleNode("//Name").get_InnerText()
$publisher=$manifest.SelectSingleNode("//Publisher").get_InnerText()
$axLayer= $manifest.SelectSingleNode("//Layer").get_InnerText()
$aolCode = Get-AolCode $axlayer
$aolParm = ''
if ($aolCode -ne '') {$aolParm = '/p:axAolCode={0}' -f $aolCode}
$projPath = (join-path $AxBuildDir 'CompileVSProjects.proj')
$logFile = join-path $currentLogFolder ('VSCompile.{0}.log' -f $modelName)
$errlogFile = join-path $currentLogFolder ('VSCompileError.{0}.err' -f $modelName)
$wrnlogFile = join-path $currentLogFolder ('VSCompileWarning.{0}.wrn' -f $modelName)
$arguments = '"{0}" /p:srcFolder="{1}" /p:axLayer={2} {3} /p:ModelName="{4}" /p:Configuration=Release /l:FileLogger,Microsoft.Build.Engine;logfile="{5}" /p:ModelPublisher="{6}" /flp1:errorsonly;logfile="{7}" /flp2:WarningsOnly;logfile="{8}" /p:RDLParameterLanguage="{9}" /p:OutDir="{10}"' -f $projPath, $Model.Directory.FullName,$axLayer,$aolParm,$modelName,$logFile, $publisher,$errlogFile, $wrnlogFile,$rdlLanguage, $vsProjBinFolder
Write-InfoLog 'Msbuild arguments'
Write-InfoLog $arguments
$msBuildProcess = Start-Process "msbuild.exe" -WorkingDirectory $msBuildPath -PassThru -WindowStyle minimized -ArgumentList $arguments -Verbose
if ($msBuildProcess.WaitForExit(60000*$CompileCILTimeout) -eq $false)
{
$msBuildProcess.Kill()
Throw ("Error: Visual studio project didn't compile in {0} min." -f $CompileCILTimeout)
}
$retError = $true
if((test-path $logfile) -eq $true)
{
$fileContent = Get-Content $logFile -ErrorAction SilentlyContinue
$lineNum = 0
foreach ($line in $fileContent)
{
$err = $line.Contains('0 Error(s)')
if($err -eq $true)
{
$retError = $false
}
}
}
if((test-path $errlogFile) -eq $true)
{
$fileContent = Get-Content $errlogFile -ErrorAction SilentlyContinue
if($errlogFile -eq $null -or $errlogFile.Trim() -eq '')
{
$retError = $false
}
}
if($retError -eq $true)
{
Write-TerminatingErrorLog('Failed to compile VS project for model {0}' -f $modelName)
}
Write-InfoLog('Compilation of VS projects succeded at {0}' -f (Get-Date))
}
function Copy-VSProjectsBinaries
{
# copy compiled dlls to Client & Server Bin dirs
# Kill All active Ax32.exe processes if any
Get-Process -Name 'Ax32' -ErrorAction SilentlyContinue | Stop-Process -Force
Copy-Item "$vsProjBinFolder\*" $clientBinDir -Force -Recurse -ErrorAction SilentlyContinue
Write-Infolog ("Compiled VS projected have been copied to $clientBinDir")
Copy-Item "$vsProjBinFolder\*" $serverBinDir -Force -Recurse -ErrorAction SilentlyContinue
Write-Infolog ("Compiled VS projected have been copied to $serverBinDir")
}
###############################################################################################
#END COMPILE-AX
###############################################################################################
###############################################################################################
#COMBINE AND EXPORT-AX
###############################################################################################
#Read the VCSDEF.xml file with the AX TFS setup.
function Get-ModelsToBuild
{
Write-InfoLog ("Start getting models to build: {0}" -f (Get-Date))
$Definition = new-object "System.Xml.XmlDocument"
$Definition.Load($LocalProject)
$Definition.SelectSingleNode("//VCSParameters").SelectSingleNode("//Models").ChildNodes
}
function Get-AolCode([string]$Layer)
{
$aolCode = ''
foreach ($fileName in Get-ChildItem $AxBuildDir -Filter 'aolcodes.*' )
{
$fileContent = Get-Content $fileName.fullName
foreach ($line in $fileContent)
{
$line = $line.Trim().Split(':')
if ($line[0].length -ge 2)
{
if ($Layer.SubString(0,2).ToUpper() -eq $line[0].SubString(0,2).ToUpper())
{
$aolCode = $line[1]
}
}
}
}
$aolCode
}
function Get-Model([System.IO.FileSystemInfo]$model)
{
Write-InfoLog ("Begin Get-Model: {0}" -f (Get-Date))
Write-InfoLog ("Model: {0}" -f $model.FullName)
$manifest = new-object "System.Xml.XmlDocument"
$manifest.Load($model.FullName)
[String]$ModelLayer = $manifest.SelectSingleNode("//Layer").get_InnerText()
[String]$script:ModelName = $manifest.SelectSingleNode("//Name").get_InnerText()
[String]$ModelVssersion = $manifest.SelectSingleNode("//Version").get_InnerText()
$script:AolCode = Get-AolCode $ModelLayer
$script:AxLayer = $ModelLayer
$script:ModelVersion = $ModelVssersion
Write-InfoLog ("End Get-Model: {0}" -f (Get-Date))
}
function Combine-Xpos([System.IO.FileSystemInfo]$modelPath)
{
Write-InfoLog ("Begin: Combine-Xpos: {0}" -f (Get-Date))
Start-Sleep 2
$combinedXpoFile = (Join-Path $currentLogFolder ("Combined.{0}.xpo" -f $modelName))
$arguments = ' -XpoDir "{0}" -Verbose -CombinedXpoFile "{1}" -utf8' -f $modelPath,$combinedXpoFile
$cmdName = Join-Path $AxBuildDir 'combinexpos.exe'
$logfile = Join-Path $CurrentLogFolder ('Combined.{0}.log' -f $modelName)
Write-InfoLog ("Calling Start-Process: {0}" -f (Get-Date))
$result = Start-Process $cmdName -WorkingDirectory $axbuildDir -PassThru -ArgumentList $arguments -RedirectStandardOutput $logFile
Write-InfoLog $result
if ($result.WaitForExit(60000*$CombineTimeout) -eq $false)
{
$axProcess.Kill()
Throw ("Combine XPO for {0} didn't complete after {1} minutes." -f $modelName, $CombineTimeout)
}
CreateSpecificXPOs($combinedXpoFile)
Write-InfoLog ("End: Combine-Xpos: {0}" -f (Get-Date))
}
function Check-CombineXpoError
{
$logfile = Join-Path $CurrentLogFolder ('Combined.{0}.log' -f $modelName)
$fileContent = Get-Content $logFile -ErrorAction SilentlyContinue
$lineNum = 0
foreach ($line in $fileContent)
{
$lineNum++
if (($lineNum -gt 1) -and ($line -eq 'Ok')) {$importOk = $true}
}
$importOk
}
function Extract-References([string]$xpoFileName)
{
$fileContents = Get-Content $xpoFileName -ErrorAction SilentlyContinue
$referencesFileName = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($xpoFileName), ('{0}_refs.xpo' -f [System.IO.Path]::GetFileNameWithoutExtension($xpoFileName)))
$writer = [System.IO.StreamWriter] $referencesFileName
$writer.WriteLine('Exportfile for AOT version 1.0 or later')
$writer.WriteLine('Formatversion: 1')
$writer.WriteLine()
foreach ($line in $fileContents)
{
if ($line -match 'Element: REF')
{
$writer.WriteLine()
$copyLine = $true
}
if ($copyLine -eq $true)
{
$writer.WriteLine($line)
}
if ($line -match 'ENDREFERENCE' -and $copyLine -eq $true)
{
$writer.WriteLine()
$copyLine = $false
}
}
$writer.WriteLine()
$writer.WriteLine('***Element: END')
$writer.Close()
}
function GetWritersList($writers)