aboutsummaryrefslogtreecommitdiff
path: root/src/WixToolset.Core.WindowsInstaller/Bind/AttachPatchTransformsCommand.cs
blob: 76bcd532987676a321996d441912d86e2618e667 (plain)
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
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.

namespace WixToolset.Core.WindowsInstaller.Bind
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Text.RegularExpressions;
    using WixToolset.Core.Native.Msi;
    using WixToolset.Data;
    using WixToolset.Data.Symbols;
    using WixToolset.Data.WindowsInstaller;
    using WixToolset.Data.WindowsInstaller.Rows;
    using WixToolset.Extensibility.Services;

    /// <summary>
    /// Include transforms in a patch.
    /// </summary>
    internal class AttachPatchTransformsCommand
    {
        private static readonly string[] PatchUninstallBreakingTables = new[]
        {
            "AppId",
            "BindImage",
            "Class",
            "Complus",
            "CreateFolder",
            "DuplicateFile",
            "Environment",
            "Extension",
            "Font",
            "IniFile",
            "IsolatedComponent",
            "LockPermissions",
            "MIME",
            "MoveFile",
            "MsiLockPermissionsEx",
            "MsiServiceConfig",
            "MsiServiceConfigFailureActions",
            "ODBCAttribute",
            "ODBCDataSource",
            "ODBCDriver",
            "ODBCSourceAttribute",
            "ODBCTranslator",
            "ProgId",
            "PublishComponent",
            "RemoveIniFile",
            "SelfReg",
            "ServiceControl",
            "ServiceInstall",
            "TypeLib",
            "Verb",
        };

        private readonly TableDefinitionCollection tableDefinitions;

        public AttachPatchTransformsCommand(IMessaging messaging, IBackendHelper backendHelper, Intermediate intermediate, IEnumerable<PatchTransform> transforms)
        {
            this.tableDefinitions = new TableDefinitionCollection(WindowsInstallerTableDefinitions.All);
            this.Messaging = messaging;
            this.BackendHelper = backendHelper;
            this.Intermediate = intermediate;
            this.Transforms = transforms;
        }

        private IMessaging Messaging { get; }

        private IBackendHelper BackendHelper { get; }

        private Intermediate Intermediate { get; }

        private IEnumerable<PatchTransform> Transforms { get; }

        public IEnumerable<SubStorage> SubStorages { get; private set; }

        public IEnumerable<SubStorage> Execute()
        {
            var subStorages = new List<SubStorage>();

            if (this.Transforms == null || !this.Transforms.Any())
            {
                this.Messaging.Write(ErrorMessages.PatchWithoutTransforms());
                return subStorages;
            }

            var summaryInfo = this.ExtractPatchSummaryInfo();

            var section = this.Intermediate.Sections.First();

            var symbols = this.Intermediate.Sections.SelectMany(s => s.Symbols).ToList();

            // Get the patch id from the WixPatchId symbol.
            var patchSymbol = symbols.OfType<WixPatchSymbol>().FirstOrDefault();

            if (String.IsNullOrEmpty(patchSymbol.Id?.Id))
            {
                this.Messaging.Write(ErrorMessages.ExpectedPatchIdInWixMsp());
                return subStorages;
            }

            if (String.IsNullOrEmpty(patchSymbol.ClientPatchId))
            {
                this.Messaging.Write(ErrorMessages.ExpectedClientPatchIdInWixMsp());
                return subStorages;
            }

            // enumerate patch.Media to map diskId to Media row
            var patchMediaByDiskId = symbols.OfType<MediaSymbol>().ToDictionary(t => t.DiskId);

            if (patchMediaByDiskId.Count == 0)
            {
                this.Messaging.Write(ErrorMessages.ExpectedMediaRowsInWixMsp());
                return subStorages;
            }

            // populate MSP summary information
            var patchMetadata = this.PopulateSummaryInformation(summaryInfo, symbols, patchSymbol);

            // enumerate transforms
            var productCodes = new SortedSet<string>();
            var transformNames = new List<string>();
            var validTransform = new List<Tuple<string, WindowsInstallerData>>();

            var baselineSymbolsById = symbols.OfType<WixPatchBaselineSymbol>().ToDictionary(t => t.Id.Id);

            foreach (var mainTransform in this.Transforms)
            {
                var baselineSymbol = baselineSymbolsById[mainTransform.Baseline];

                var patchRefSymbols = symbols.OfType<WixPatchRefSymbol>().ToList();
                if (patchRefSymbols.Count > 0)
                {
                    if (!this.ReduceTransform(mainTransform.Transform, patchRefSymbols))
                    {
                        // transform has none of the content authored into this patch
                        continue;
                    }
                }

                // Validate the transform doesn't break any patch specific rules.
                this.Validate(mainTransform);

                // ensure consistent File.Sequence within each Media
                var mediaSymbol = patchMediaByDiskId[baselineSymbol.DiskId];

                // Ensure that files are sequenced after the last file in any transform.
                var transformMediaTable = mainTransform.Transform.Tables["Media"];
                if (null != transformMediaTable && 0 < transformMediaTable.Rows.Count)
                {
                    foreach (MediaRow transformMediaRow in transformMediaTable.Rows)
                    {
                        if (!mediaSymbol.LastSequence.HasValue || mediaSymbol.LastSequence < transformMediaRow.LastSequence)
                        {
                            // The Binder will pre-increment the sequence.
                            mediaSymbol.LastSequence = transformMediaRow.LastSequence;
                        }
                    }
                }

                // Use the Media/@DiskId if greater than the last sequence for backward compatibility.
                if (!mediaSymbol.LastSequence.HasValue || mediaSymbol.LastSequence < mediaSymbol.DiskId)
                {
                    mediaSymbol.LastSequence = mediaSymbol.DiskId;
                }

                // Ignore media table in the transform.
                mainTransform.Transform.Tables.Remove("Media");
                mainTransform.Transform.Tables.Remove("MsiDigitalSignature");

                var pairedTransform = this.BuildPairedTransform(summaryInfo, patchMetadata, patchSymbol, mainTransform.Transform, mediaSymbol, baselineSymbol, out var productCode);

                productCode = productCode.ToUpperInvariant();
                productCodes.Add(productCode);
                validTransform.Add(Tuple.Create(productCode, mainTransform.Transform));

                // attach these transforms to the patch object
                // TODO: is this an acceptable way to auto-generate transform stream names?
                var transformName = mainTransform.Baseline + "." + validTransform.Count.ToString(CultureInfo.InvariantCulture);
                subStorages.Add(new SubStorage(transformName, mainTransform.Transform));
                subStorages.Add(new SubStorage("#" + transformName, pairedTransform));

                transformNames.Add(":" + transformName);
                transformNames.Add(":#" + transformName);
            }

            if (validTransform.Count == 0)
            {
                this.Messaging.Write(ErrorMessages.PatchWithoutValidTransforms());
                return subStorages;
            }

            // Validate that a patch authored as removable is actually removable
            if (patchMetadata.TryGetValue("AllowRemoval", out var allowRemoval) && allowRemoval.Value == "1")
            {
                var uninstallable = true;

                foreach (var entry in validTransform)
                {
                    uninstallable &= this.CheckUninstallableTransform(entry.Item1, entry.Item2);
                }

                if (!uninstallable)
                {
                    this.Messaging.Write(ErrorMessages.PatchNotRemovable());
                    return subStorages;
                }
            }

            // Finish filling tables with transform-dependent data.
            productCodes = FinalizePatchProductCodes(symbols, productCodes);

            // Semicolon delimited list of the product codes that can accept the patch.
            summaryInfo.Add(SummaryInformationType.PatchProductCodes, new SummaryInformationSymbol(patchSymbol.SourceLineNumbers)
            {
                PropertyId = SummaryInformationType.PatchProductCodes,
                Value = String.Join(";", productCodes)
            });

            // Semicolon delimited list of transform substorage names in the order they are applied.
            summaryInfo.Add(SummaryInformationType.TransformNames, new SummaryInformationSymbol(patchSymbol.SourceLineNumbers)
            {
                PropertyId = SummaryInformationType.TransformNames,
                Value = String.Join(";", transformNames)
            });

            // Put the summary information that was extracted back in now that it is updated.
            foreach (var readSummaryInfo in summaryInfo.Values.OrderBy(s => s.PropertyId))
            {
                section.AddSymbol(readSummaryInfo);
            }

            this.SubStorages = subStorages;

            return subStorages;
        }

        private Dictionary<SummaryInformationType, SummaryInformationSymbol> ExtractPatchSummaryInfo()
        {
            var result = new Dictionary<SummaryInformationType, SummaryInformationSymbol>();

            foreach (var section in this.Intermediate.Sections)
            {
                // Remove all summary information from the symbols and remember those that
                // are not calculated or reserved.
                foreach (var patchSummaryInfo in section.Symbols.OfType<SummaryInformationSymbol>().ToList())
                {
                    section.RemoveSymbol(patchSummaryInfo);

                    if (patchSummaryInfo.PropertyId != SummaryInformationType.PatchProductCodes &&
                        patchSummaryInfo.PropertyId != SummaryInformationType.PatchCode &&
                        patchSummaryInfo.PropertyId != SummaryInformationType.PatchInstallerRequirement &&
                        patchSummaryInfo.PropertyId != SummaryInformationType.Reserved11 &&
                        patchSummaryInfo.PropertyId != SummaryInformationType.Reserved14 &&
                        patchSummaryInfo.PropertyId != SummaryInformationType.Reserved16)
                    {
                        result.Add(patchSummaryInfo.PropertyId, patchSummaryInfo);
                    }
                }
            }

            return result;
        }

        private Dictionary<string, MsiPatchMetadataSymbol> PopulateSummaryInformation(Dictionary<SummaryInformationType, SummaryInformationSymbol> summaryInfo, List<IntermediateSymbol> symbols, WixPatchSymbol patchSymbol)
        {
            // PID_CODEPAGE
            if (!summaryInfo.ContainsKey(SummaryInformationType.Codepage))
            {
                // Set the code page by default to the same code page for the
                // string pool in the database.
                AddSummaryInformation(SummaryInformationType.Codepage, patchSymbol.Codepage?.ToString(CultureInfo.InvariantCulture) ?? "0", patchSymbol.SourceLineNumbers);
            }

            // GUID patch code for the patch.
            AddSummaryInformation(SummaryInformationType.PatchCode, patchSymbol.Id.Id, patchSymbol.SourceLineNumbers);

            // Indicates the minimum Windows Installer version that is required to install the patch.
            AddSummaryInformation(SummaryInformationType.PatchInstallerRequirement, ((int)SummaryInformation.InstallerRequirement.Version31).ToString(CultureInfo.InvariantCulture), patchSymbol.SourceLineNumbers);

            if (!summaryInfo.ContainsKey(SummaryInformationType.Security))
            {
                AddSummaryInformation(SummaryInformationType.Security, "4", patchSymbol.SourceLineNumbers); // Read-only enforced;
            }

            // Use authored comments or default to display name.
            MsiPatchMetadataSymbol commentsSymbol = null;

            var metadataSymbols = symbols.OfType<MsiPatchMetadataSymbol>().Where(t => String.IsNullOrEmpty(t.Company)).ToDictionary(t => t.Property);

            if (!summaryInfo.ContainsKey(SummaryInformationType.Title) &&
                metadataSymbols.TryGetValue("DisplayName", out var displayName))
            {
                AddSummaryInformation(SummaryInformationType.Title, displayName.Value, displayName.SourceLineNumbers);

                // Default comments to use display name as-is.
                commentsSymbol = displayName;
            }

            // TODO: This code below seems unnecessary given the codepage is set at the top of this method.
            //if (!summaryInfo.ContainsKey(SummaryInformationType.Codepage) &&
            //    metadataValues.TryGetValue("CodePage", out var codepage))
            //{
            //    AddSummaryInformation(SummaryInformationType.Codepage, codepage);
            //}

            if (!summaryInfo.ContainsKey(SummaryInformationType.PatchPackageName) &&
                metadataSymbols.TryGetValue("Description", out var description))
            {
                AddSummaryInformation(SummaryInformationType.PatchPackageName, description.Value, description.SourceLineNumbers);
            }

            if (!summaryInfo.ContainsKey(SummaryInformationType.Author) &&
                metadataSymbols.TryGetValue("ManufacturerName", out var manufacturer))
            {
                AddSummaryInformation(SummaryInformationType.Author, manufacturer.Value, manufacturer.SourceLineNumbers);
            }

            // Special metadata marshalled through the build.
            //var wixMetadataValues = symbols.OfType<WixPatchMetadataSymbol>().ToDictionary(t => t.Id.Id, t => t.Value);

            //if (wixMetadataValues.TryGetValue("Comments", out var wixComments))
            if (metadataSymbols.TryGetValue("Comments", out var wixComments))
            {
                commentsSymbol = wixComments;
            }

            // Write the package comments to summary info.
            if (!summaryInfo.ContainsKey(SummaryInformationType.Comments) &&
                commentsSymbol != null)
            {
                AddSummaryInformation(SummaryInformationType.Comments, commentsSymbol.Value, commentsSymbol.SourceLineNumbers);
            }

            return metadataSymbols;

            void AddSummaryInformation(SummaryInformationType type, string value, SourceLineNumber sourceLineNumber)
            {
                summaryInfo.Add(type, new SummaryInformationSymbol(sourceLineNumber)
                {
                    PropertyId = type,
                    Value = value
                });
            }
        }

        /// <summary>
        /// Ensure transform is uninstallable.
        /// </summary>
        /// <param name="productCode">Product code in transform.</param>
        /// <param name="transform">Transform generated by torch.</param>
        /// <returns>True if the transform is uninstallable</returns>
        private bool CheckUninstallableTransform(string productCode, WindowsInstallerData transform)
        {
            var success = true;

            foreach (var tableName in PatchUninstallBreakingTables)
            {
                if (transform.TryGetTable(tableName, out var table))
                {
                    foreach (var row in table.Rows)
                    {
                        if (row.Operation == RowOperation.Add)
                        {
                            success = false;

                            var primaryKey = row.GetPrimaryKey('/') ?? String.Empty;

                            this.Messaging.Write(ErrorMessages.NewRowAddedInTable(row.SourceLineNumbers, productCode, table.Name, primaryKey));
                        }
                    }
                }
            }

            return success;
        }

        /// <summary>
        /// Reduce the transform according to the patch references.
        /// </summary>
        /// <param name="transform">transform generated by torch.</param>
        /// <param name="patchRefSymbols">Table contains patch family filter.</param>
        /// <returns>true if the transform is not empty</returns>
        private bool ReduceTransform(WindowsInstallerData transform, IEnumerable<WixPatchRefSymbol> patchRefSymbols)
        {
            // identify sections to keep
            var oldSections = new Dictionary<string, Row>();
            var newSections = new Dictionary<string, Row>();
            var tableKeyRows = new Dictionary<string, Dictionary<string, Row>>();
            var sequenceList = new List<Table>();
            var componentFeatureAddsIndex = new Dictionary<string, List<string>>();
            var customActionTable = new Dictionary<string, Row>();
            var directoryTableAdds = new Dictionary<string, Row>();
            var featureTableAdds = new Dictionary<string, Row>();
            var keptComponents = new Dictionary<string, Row>();
            var keptDirectories = new Dictionary<string, Row>();
            var keptFeatures = new Dictionary<string, Row>();
            var keptLockPermissions = new HashSet<string>();
            var keptMsiLockPermissionExs = new HashSet<string>();

            var componentCreateFolderIndex = new Dictionary<string, List<string>>();
            var directoryLockPermissionsIndex = new Dictionary<string, List<Row>>();
            var directoryMsiLockPermissionsExIndex = new Dictionary<string, List<Row>>();

            foreach (var patchRefSymbol in patchRefSymbols)
            {
                var tableName = patchRefSymbol.Table;
                var key = patchRefSymbol.PrimaryKeys;

                // Short circuit filtering if all changes should be included.
                if ("*" == tableName && "*" == key)
                {
                    RemoveProductCodeFromTransform(transform);
                    return true;
                }

                if (!transform.Tables.TryGetTable(tableName, out var table))
                {
                    // Table not found.
                    continue;
                }

                // Index the table.
                if (!tableKeyRows.TryGetValue(tableName, out var keyRows))
                {
                    keyRows = new Dictionary<string, Row>();
                    tableKeyRows.Add(tableName, keyRows);

                    foreach (var newRow in table.Rows)
                    {
                        var primaryKey = newRow.GetPrimaryKey();
                        keyRows.Add(primaryKey, newRow);
                    }
                }

                if (!keyRows.TryGetValue(key, out var row))
                {
                    // Row not found.
                    continue;
                }

                // Differ.sectionDelimiter
                var sections = row.SectionId.Split('/');
                oldSections[sections[0]] = row;
                newSections[sections[1]] = row;
            }

            // throw away sections not referenced
            var keptRows = 0;
            Table directoryTable = null;
            Table featureTable = null;
            Table lockPermissionsTable = null;
            Table msiLockPermissionsTable = null;

            foreach (var table in transform.Tables)
            {
                if ("_SummaryInformation" == table.Name)
                {
                    continue;
                }

                if (table.Name == "AdminExecuteSequence"
                    || table.Name == "AdminUISequence"
                    || table.Name == "AdvtExecuteSequence"
                    || table.Name == "InstallUISequence"
                    || table.Name == "InstallExecuteSequence")
                {
                    sequenceList.Add(table);
                    continue;
                }

                for (var i = 0; i < table.Rows.Count; i++)
                {
                    var row = table.Rows[i];

                    if (table.Name == "CreateFolder")
                    {
                        var createFolderComponentId = row.FieldAsString(1);

                        if (!componentCreateFolderIndex.TryGetValue(createFolderComponentId, out var directoryList))
                        {
                            directoryList = new List<string>();
                            componentCreateFolderIndex.Add(createFolderComponentId, directoryList);
                        }

                        directoryList.Add(row.FieldAsString(0));
                    }

                    if (table.Name == "CustomAction")
                    {
                        customActionTable.Add(row.FieldAsString(0), row);
                    }

                    if (table.Name == "Directory")
                    {
                        directoryTable = table;
                        if (RowOperation.Add == row.Operation)
                        {
                            directoryTableAdds.Add(row.FieldAsString(0), row);
                        }
                    }

                    if (table.Name == "Feature")
                    {
                        featureTable = table;
                        if (RowOperation.Add == row.Operation)
                        {
                            featureTableAdds.Add(row.FieldAsString(0), row);
                        }
                    }

                    if (table.Name == "FeatureComponents")
                    {
                        if (RowOperation.Add == row.Operation)
                        {
                            var featureId = row.FieldAsString(0);
                            var componentId = row.FieldAsString(1);

                            if (!componentFeatureAddsIndex.TryGetValue(componentId, out var featureList))
                            {
                                featureList = new List<string>();
                                componentFeatureAddsIndex.Add(componentId, featureList);
                            }

                            featureList.Add(featureId);
                        }
                    }

                    if (table.Name == "LockPermissions")
                    {
                        lockPermissionsTable = table;
                        if ("CreateFolder" == row.FieldAsString(1))
                        {
                            var directoryId = row.FieldAsString(0);

                            if (!directoryLockPermissionsIndex.TryGetValue(directoryId, out var rowList))
                            {
                                rowList = new List<Row>();
                                directoryLockPermissionsIndex.Add(directoryId, rowList);
                            }

                            rowList.Add(row);
                        }
                    }

                    if (table.Name == "MsiLockPermissionsEx")
                    {
                        msiLockPermissionsTable = table;
                        if ("CreateFolder" == row.FieldAsString(1))
                        {
                            var directoryId = row.FieldAsString(0);

                            if (!directoryMsiLockPermissionsExIndex.TryGetValue(directoryId, out var rowList))
                            {
                                rowList = new List<Row>();
                                directoryMsiLockPermissionsExIndex.Add(directoryId, rowList);
                            }

                            rowList.Add(row);
                        }
                    }

                    if (null == row.SectionId)
                    {
                        table.Rows.RemoveAt(i);
                        i--;
                    }
                    else
                    {
                        var sections = row.SectionId.Split('/');
                        // ignore the row without section id.
                        if (0 == sections[0].Length && 0 == sections[1].Length)
                        {
                            table.Rows.RemoveAt(i);
                            i--;
                        }
                        else if (IsInPatchFamily(sections[0], sections[1], oldSections, newSections))
                        {
                            if ("Component" == table.Name)
                            {
                                keptComponents.Add(row.FieldAsString(0), row);
                            }

                            if ("Directory" == table.Name)
                            {
                                keptDirectories.Add(row.FieldAsString(0), row);
                            }

                            if ("Feature" == table.Name)
                            {
                                keptFeatures.Add(row.FieldAsString(0), row);
                            }

                            keptRows++;
                        }
                        else
                        {
                            table.Rows.RemoveAt(i);
                            i--;
                        }
                    }
                }
            }

            keptRows += ReduceTransformSequenceTable(sequenceList, oldSections, newSections, customActionTable);

            if (null != directoryTable)
            {
                foreach (var componentRow in keptComponents.Values)
                {
                    var componentId = componentRow.FieldAsString(0);

                    if (RowOperation.Add == componentRow.Operation)
                    {
                        // Make sure each added component has its required directory and feature heirarchy.
                        var directoryId = componentRow.FieldAsString(2);
                        while (null != directoryId && directoryTableAdds.TryGetValue(directoryId, out var directoryRow))
                        {
                            if (!keptDirectories.ContainsKey(directoryId))
                            {
                                directoryTable.Rows.Add(directoryRow);
                                keptDirectories.Add(directoryId, directoryRow);
                                keptRows++;
                            }

                            directoryId = directoryRow.FieldAsString(1);
                        }

                        if (componentFeatureAddsIndex.TryGetValue(componentId, out var componentFeatureIds))
                        {
                            foreach (var featureId in componentFeatureIds)
                            {
                                var currentFeatureId = featureId;
                                while (null != currentFeatureId && featureTableAdds.TryGetValue(currentFeatureId, out var featureRow))
                                {
                                    if (!keptFeatures.ContainsKey(currentFeatureId))
                                    {
                                        featureTable.Rows.Add(featureRow);
                                        keptFeatures.Add(currentFeatureId, featureRow);
                                        keptRows++;
                                    }

                                    currentFeatureId = featureRow.FieldAsString(1);
                                }
                            }
                        }
                    }

                    // Hook in changes LockPermissions and MsiLockPermissions for folders for each component that has been kept.
                    foreach (var keptComponentId in keptComponents.Keys)
                    {
                        if (componentCreateFolderIndex.TryGetValue(keptComponentId, out var directoryList))
                        {
                            foreach (var directoryId in directoryList)
                            {
                                if (directoryLockPermissionsIndex.TryGetValue(directoryId, out var lockPermissionsRowList))
                                {
                                    foreach (var lockPermissionsRow in lockPermissionsRowList)
                                    {
                                        var key = lockPermissionsRow.GetPrimaryKey('/');
                                        if (keptLockPermissions.Add(key))
                                        {
                                            lockPermissionsTable.Rows.Add(lockPermissionsRow);
                                            keptRows++;
                                        }
                                    }
                                }

                                if (directoryMsiLockPermissionsExIndex.TryGetValue(directoryId, out var msiLockPermissionsExRowList))
                                {
                                    foreach (var msiLockPermissionsExRow in msiLockPermissionsExRowList)
                                    {
                                        var key = msiLockPermissionsExRow.GetPrimaryKey('/');
                                        if (keptMsiLockPermissionExs.Add(key))
                                        {
                                            msiLockPermissionsTable.Rows.Add(msiLockPermissionsExRow);
                                            keptRows++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            keptRows += ReduceTransformSequenceTable(sequenceList, oldSections, newSections, customActionTable);

            // Delete tables that are empty.
            var tablesToDelete = transform.Tables.Where(t => t.Rows.Count == 0).Select(t => t.Name).ToList();

            foreach (var tableName in tablesToDelete)
            {
                transform.Tables.Remove(tableName);
            }

            return keptRows > 0;
        }

        private void Validate(PatchTransform patchTransform)
        {
            var transformPath = patchTransform.Baseline; // TODO: this is used in error messages, how best to set it?
            var transform = patchTransform.Transform;

            // Changing the ProdocutCode in a patch transform is not recommended.
            if (transform.TryGetTable("Property", out var propertyTable))
            {
                foreach (var row in propertyTable.Rows)
                {
                    // Only interested in modified rows; fast check.
                    if (RowOperation.Modify == row.Operation &&
                        "ProductCode".Equals(row.FieldAsString(0), StringComparison.Ordinal))
                    {
                        this.Messaging.Write(WarningMessages.MajorUpgradePatchNotRecommended());
                    }
                }
            }

            // If there is nothing in the component table we can return early because the remaining checks are component based.
            if (!transform.TryGetTable("Component", out var componentTable))
            {
                return;
            }

            // Index Feature table row operations
            var featureOps = new Dictionary<string, RowOperation>();
            if (transform.TryGetTable("Feature", out var featureTable))
            {
                foreach (var row in featureTable.Rows)
                {
                    featureOps[row.FieldAsString(0)] = row.Operation;
                }
            }

            // Index Component table and check for keypath modifications
            var componentKeyPath = new Dictionary<string, string>();
            var deletedComponent = new Dictionary<string, Row>();
            foreach (var row in componentTable.Rows)
            {
                var id = row.FieldAsString(0);
                var keypath = row.FieldAsString(5) ?? String.Empty;

                componentKeyPath.Add(id, keypath);

                if (RowOperation.Delete == row.Operation)
                {
                    deletedComponent.Add(id, row);
                }
                else if (RowOperation.Modify == row.Operation)
                {
                    if (row.Fields[1].Modified)
                    {
                        // Changing the guid of a component is equal to deleting the old one and adding a new one.
                        deletedComponent.Add(id, row);
                    }

                    // If the keypath is modified its an error
                    if (row.Fields[5].Modified)
                    {
                        this.Messaging.Write(ErrorMessages.InvalidKeypathChange(row.SourceLineNumbers, id, transformPath));
                    }
                }
            }

            // Verify changes in the file table
            if (transform.TryGetTable("File", out var fileTable))
            {
                var componentWithChangedKeyPath = new Dictionary<string, string>();
                foreach (FileRow row in fileTable.Rows)
                {
                    if (RowOperation.None == row.Operation)
                    {
                        continue;
                    }

                    var fileId = row.File;
                    var componentId = row.Component;

                    // If this file is the keypath of a component
                    if (componentKeyPath.TryGetValue(componentId, out var keyPath) && keyPath.Equals(fileId, StringComparison.Ordinal))
                    {
                        if (row.Fields[2].Modified)
                        {
                            // You can't change the filename of a file that is the keypath of a component.
                            this.Messaging.Write(ErrorMessages.InvalidKeypathChange(row.SourceLineNumbers, componentId, transformPath));
                        }

                        if (!componentWithChangedKeyPath.ContainsKey(componentId))
                        {
                            componentWithChangedKeyPath.Add(componentId, fileId);
                        }
                    }

                    if (RowOperation.Delete == row.Operation)
                    {
                        // If the file is removed from a component that is not deleted.
                        if (!deletedComponent.ContainsKey(componentId))
                        {
                            var foundRemoveFileEntry = false;
                            var filename = this.BackendHelper.GetMsiFileName(row.FieldAsString(2), false, true);

                            if (transform.TryGetTable("RemoveFile", out var removeFileTable))
                            {
                                foreach (var removeFileRow in removeFileTable.Rows)
                                {
                                    if (RowOperation.Delete == removeFileRow.Operation)
                                    {
                                        continue;
                                    }

                                    if (componentId == removeFileRow.FieldAsString(1))
                                    {
                                        // Check if there is a RemoveFile entry for this file
                                        if (null != removeFileRow[2])
                                        {
                                            var removeFileName = this.BackendHelper.GetMsiFileName(removeFileRow.FieldAsString(2), false, true);

                                            // Convert the MSI format for a wildcard string to Regex format.
                                            removeFileName = removeFileName.Replace('.', '|').Replace('?', '.').Replace("*", ".*").Replace("|", "\\.");

                                            var regex = new Regex(removeFileName, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
                                            if (regex.IsMatch(filename))
                                            {
                                                foundRemoveFileEntry = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            if (!foundRemoveFileEntry)
                            {
                                this.Messaging.Write(WarningMessages.InvalidRemoveFile(row.SourceLineNumbers, fileId, componentId));
                            }
                        }
                    }
                }
            }

            var featureComponentsTable = transform.Tables["FeatureComponents"];

            if (0 < deletedComponent.Count)
            {
                // Index FeatureComponents table.
                var featureComponents = new Dictionary<string, List<string>>();

                if (null != featureComponentsTable)
                {
                    foreach (var row in featureComponentsTable.Rows)
                    {
                        var componentId = row.FieldAsString(1);

                        if (!featureComponents.TryGetValue(componentId, out var features))
                        {
                            features = new List<string>();
                            featureComponents.Add(componentId, features);
                        }

                        features.Add(row.FieldAsString(0));
                    }
                }

                // Check to make sure if a component was deleted, the feature was too.
                foreach (var entry in deletedComponent)
                {
                    if (featureComponents.TryGetValue(entry.Key, out var features))
                    {
                        foreach (var featureId in features)
                        {
                            if (!featureOps.TryGetValue(featureId, out var op) || op != RowOperation.Delete)
                            {
                                // The feature was not deleted.
                                this.Messaging.Write(ErrorMessages.InvalidRemoveComponent(((Row)entry.Value).SourceLineNumbers, entry.Key.ToString(), featureId, transformPath));
                            }
                        }
                    }
                }
            }

            // Warn if new components are added to existing features
            if (null != featureComponentsTable)
            {
                foreach (var row in featureComponentsTable.Rows)
                {
                    if (RowOperation.Add == row.Operation)
                    {
                        // Check if the feature is in the Feature table
                        var feature_ = row.FieldAsString(0);
                        var component_ = row.FieldAsString(1);

                        // Features may not be present if not referenced
                        if (!featureOps.ContainsKey(feature_) || RowOperation.Add != (RowOperation)featureOps[feature_])
                        {
                            this.Messaging.Write(WarningMessages.NewComponentAddedToExistingFeature(row.SourceLineNumbers, component_, feature_, transformPath));
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Remove the ProductCode property from the transform.
        /// </summary>
        /// <param name="transform">The transform.</param>
        /// <remarks>
        /// Changing the ProductCode is not supported in a patch.
        /// </remarks>
        private static void RemoveProductCodeFromTransform(WindowsInstallerData transform)
        {
            if (transform.Tables.TryGetTable("Property", out var propertyTable))
            {
                for (var i = 0; i < propertyTable.Rows.Count; ++i)
                {
                    var propertyRow = propertyTable.Rows[i];
                    var property = (string)propertyRow[0];

                    if ("ProductCode" == property)
                    {
                        propertyTable.Rows.RemoveAt(i);
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Check if the section is in a PatchFamily.
        /// </summary>
        /// <param name="oldSection">Section id in target wixout</param>
        /// <param name="newSection">Section id in upgrade wixout</param>
        /// <param name="oldSections">Dictionary contains section id should be kept in the baseline wixout.</param>
        /// <param name="newSections">Dictionary contains section id should be kept in the upgrade wixout.</param>
        /// <returns>true if section in patch family</returns>
        private static bool IsInPatchFamily(string oldSection, string newSection, Dictionary<string, Row> oldSections, Dictionary<string, Row> newSections)
        {
            var result = false;

            if ((String.IsNullOrEmpty(oldSection) && newSections.ContainsKey(newSection)) || (String.IsNullOrEmpty(newSection) && oldSections.ContainsKey(oldSection)))
            {
                result = true;
            }
            else if (!String.IsNullOrEmpty(oldSection) && !String.IsNullOrEmpty(newSection) && (oldSections.ContainsKey(oldSection) || newSections.ContainsKey(newSection)))
            {
                result = true;
            }

            return result;
        }

        /// <summary>
        /// Reduce the transform sequence tables.
        /// </summary>
        /// <param name="sequenceList">ArrayList of tables to be reduced</param>
        /// <param name="oldSections">Hashtable contains section id should be kept in the baseline wixout.</param>
        /// <param name="newSections">Hashtable contains section id should be kept in the target wixout.</param>
        /// <param name="customAction">Hashtable contains all the rows in the CustomAction table.</param>
        /// <returns>Number of rows left</returns>
        private static int ReduceTransformSequenceTable(List<Table> sequenceList, Dictionary<string, Row> oldSections, Dictionary<string, Row> newSections, Dictionary<string, Row> customAction)
        {
            var keptRows = 0;

            foreach (var currentTable in sequenceList)
            {
                for (var i = 0; i < currentTable.Rows.Count; i++)
                {
                    var row = currentTable.Rows[i];
                    var actionName = row.Fields[0].Data.ToString();
                    var sections = row.SectionId.Split('/');
                    var isSectionIdEmpty = (sections[0].Length == 0 && sections[1].Length == 0);

                    if (row.Operation == RowOperation.None)
                    {
                        // Ignore the rows without section id.
                        if (isSectionIdEmpty)
                        {
                            currentTable.Rows.RemoveAt(i);
                            i--;
                        }
                        else if (IsInPatchFamily(sections[0], sections[1], oldSections, newSections))
                        {
                            keptRows++;
                        }
                        else
                        {
                            currentTable.Rows.RemoveAt(i);
                            i--;
                        }
                    }
                    else if (row.Operation == RowOperation.Modify)
                    {
                        var sequenceChanged = row.Fields[2].Modified;
                        var conditionChanged = row.Fields[1].Modified;

                        if (sequenceChanged && !conditionChanged)
                        {
                            keptRows++;
                        }
                        else if (!sequenceChanged && conditionChanged)
                        {
                            if (isSectionIdEmpty)
                            {
                                currentTable.Rows.RemoveAt(i);
                                i--;
                            }
                            else if (IsInPatchFamily(sections[0], sections[1], oldSections, newSections))
                            {
                                keptRows++;
                            }
                            else
                            {
                                currentTable.Rows.RemoveAt(i);
                                i--;
                            }
                        }
                        else if (sequenceChanged && conditionChanged)
                        {
                            if (isSectionIdEmpty)
                            {
                                row.Fields[1].Modified = false;
                                keptRows++;
                            }
                            else if (IsInPatchFamily(sections[0], sections[1], oldSections, newSections))
                            {
                                keptRows++;
                            }
                            else
                            {
                                row.Fields[1].Modified = false;
                                keptRows++;
                            }
                        }
                    }
                    else if (row.Operation == RowOperation.Delete)
                    {
                        if (isSectionIdEmpty)
                        {
                            // it is a stardard action which is added by wix, we should keep this action.
                            row.Operation = RowOperation.None;
                            keptRows++;
                        }
                        else if (IsInPatchFamily(sections[0], sections[1], oldSections, newSections))
                        {
                            keptRows++;
                        }
                        else
                        {
                            if (customAction.ContainsKey(actionName))
                            {
                                currentTable.Rows.RemoveAt(i);
                                i--;
                            }
                            else
                            {
                                // it is a stardard action, we should keep this action.
                                row.Operation = RowOperation.None;
                                keptRows++;
                            }
                        }
                    }
                    else if (row.Operation == RowOperation.Add)
                    {
                        if (isSectionIdEmpty)
                        {
                            keptRows++;
                        }
                        else if (IsInPatchFamily(sections[0], sections[1], oldSections, newSections))
                        {
                            keptRows++;
                        }
                        else
                        {
                            if (customAction.ContainsKey(actionName))
                            {
                                currentTable.Rows.RemoveAt(i);
                                i--;
                            }
                            else
                            {
                                keptRows++;
                            }
                        }
                    }
                }
            }

            return keptRows;
        }

        /// <summary>
        /// Create the #transform for the given main transform.
        /// </summary>
        private WindowsInstallerData BuildPairedTransform(Dictionary<SummaryInformationType, SummaryInformationSymbol> summaryInfo, Dictionary<string, MsiPatchMetadataSymbol> patchMetadata, WixPatchSymbol patchIdSymbol, WindowsInstallerData mainTransform, MediaSymbol mediaSymbol, WixPatchBaselineSymbol baselineSymbol, out string productCode)
        {
            productCode = null;

            var pairedTransform = new WindowsInstallerData(null)
            {
                Type = OutputType.Transform,
                Codepage = mainTransform.Codepage
            };

            // lookup productVersion property to correct summaryInformation
            var newProductVersion = mainTransform.Tables["Property"]?.Rows.FirstOrDefault(r => r.FieldAsString(0) == "ProductVersion")?.FieldAsString(1);

            var mainSummaryTable = mainTransform.Tables["_SummaryInformation"];
            var mainSummaryRows = mainSummaryTable.Rows.ToDictionary(r => r.FieldAsInteger(0));

            var baselineValidationFlags = ((int)baselineSymbol.ValidationFlags).ToString(CultureInfo.InvariantCulture);

            if (!mainSummaryRows.ContainsKey((int)SummaryInformationType.TransformValidationFlags))
            {
                var mainSummaryRow = mainSummaryTable.CreateRow(baselineSymbol.SourceLineNumbers);
                mainSummaryRow[0] = (int)SummaryInformationType.TransformValidationFlags;
                mainSummaryRow[1] = baselineValidationFlags;
            }

            // copy summary information from core transform
            var pairedSummaryTable = pairedTransform.EnsureTable(this.tableDefinitions["_SummaryInformation"]);

            foreach (var mainSummaryRow in mainSummaryTable.Rows)
            {
                var type = (SummaryInformationType)mainSummaryRow.FieldAsInteger(0);
                var value = mainSummaryRow.FieldAsString(1);
                switch (type)
                {
                    case SummaryInformationType.TransformProductCodes:
                        var propertyData = value.Split(';');
                        var oldProductVersion = propertyData[0].Substring(38);
                        var upgradeCode = propertyData[2];
                        productCode = propertyData[0].Substring(0, 38);

                        if (newProductVersion == null)
                        {
                            newProductVersion = oldProductVersion;
                        }

                        // Force mainTranform to 'old;new;upgrade' and pairedTransform to 'new;new;upgrade'
                        mainSummaryRow[1] = String.Concat(productCode, oldProductVersion, ';', productCode, newProductVersion, ';', upgradeCode);
                        value = String.Concat(productCode, newProductVersion, ';', productCode, newProductVersion, ';', upgradeCode);
                        break;
                    case SummaryInformationType.TransformValidationFlags: // use validation flags authored into the patch XML.
                        value = baselineValidationFlags;
                        mainSummaryRow[1] = value;
                        break;
                }

                var pairedSummaryRow = pairedSummaryTable.CreateRow(mainSummaryRow.SourceLineNumbers);
                pairedSummaryRow[0] = mainSummaryRow[0];
                pairedSummaryRow[1] = value;
            }

            if (productCode == null)
            {
                this.Messaging.Write(ErrorMessages.CouldNotDetermineProductCodeFromTransformSummaryInfo());
                return null;
            }

            // Copy File table
            if (mainTransform.Tables.TryGetTable("File", out var mainFileTable) && 0 < mainFileTable.Rows.Count)
            {
                var pairedFileTable = pairedTransform.EnsureTable(mainFileTable.Definition);

                foreach (FileRow mainFileRow in mainFileTable.Rows)
                {
                    // Set File.Sequence to non null to satisfy transform bind.
                    mainFileRow.Sequence = 1;

                    // Delete's don't need rows in the paired transform.
                    if (mainFileRow.Operation == RowOperation.Delete)
                    {
                        continue;
                    }

                    var pairedFileRow = (FileRow)pairedFileTable.CreateRow(mainFileRow.SourceLineNumbers);
                    pairedFileRow.Operation = RowOperation.Modify;
                    mainFileRow.CopyTo(pairedFileRow);

                    // Override authored media for patch bind.
                    mainFileRow.DiskId = mediaSymbol.DiskId;

                    // Suppress any change to File.Sequence to avoid bloat.
                    mainFileRow.Fields[7].Modified = false;

                    // Force File row to appear in the transform.
                    switch (mainFileRow.Operation)
                    {
                        case RowOperation.Modify:
                        case RowOperation.Add:
                            pairedFileRow.Attributes |= WindowsInstallerConstants.MsidbFileAttributesPatchAdded;
                            pairedFileRow.Fields[6].Modified = true;
                            pairedFileRow.Operation = mainFileRow.Operation;
                            break;
                        default:
                            pairedFileRow.Fields[6].Modified = false;
                            break;
                    }
                }
            }

            // Add Media row to pairedTransform
            var pairedMediaTable = pairedTransform.EnsureTable(this.tableDefinitions["Media"]);
            var pairedMediaRow = (MediaRow)pairedMediaTable.CreateRow(mediaSymbol.SourceLineNumbers);
            pairedMediaRow.Operation = RowOperation.Add;
            pairedMediaRow.DiskId = mediaSymbol.DiskId;
            pairedMediaRow.LastSequence = mediaSymbol.LastSequence ?? 0;
            pairedMediaRow.DiskPrompt = mediaSymbol.DiskPrompt;
            pairedMediaRow.Cabinet = mediaSymbol.Cabinet;
            pairedMediaRow.VolumeLabel = mediaSymbol.VolumeLabel;
            pairedMediaRow.Source = mediaSymbol.Source;

            // Add PatchPackage for this Media
            var pairedPackageTable = pairedTransform.EnsureTable(this.tableDefinitions["PatchPackage"]);
            pairedPackageTable.Operation = TableOperation.Add;
            var pairedPackageRow = pairedPackageTable.CreateRow(mediaSymbol.SourceLineNumbers);
            pairedPackageRow.Operation = RowOperation.Add;
            pairedPackageRow[0] = patchIdSymbol.Id.Id;
            pairedPackageRow[1] = mediaSymbol.DiskId;

            // Add the property to the patch transform's Property table.
            var pairedPropertyTable = pairedTransform.EnsureTable(this.tableDefinitions["Property"]);
            pairedPropertyTable.Operation = TableOperation.Add;

            // Add property to both identify client patches and whether those patches are removable or not
            patchMetadata.TryGetValue("AllowRemoval", out var allowRemovalSymbol);

            var pairedPropertyRow = pairedPropertyTable.CreateRow(allowRemovalSymbol?.SourceLineNumbers);
            pairedPropertyRow.Operation = RowOperation.Add;
            pairedPropertyRow[0] = String.Concat(patchIdSymbol.ClientPatchId, ".AllowRemoval");
            pairedPropertyRow[1] = allowRemovalSymbol?.Value ?? "0";

            // Add this patch code GUID to the patch transform to identify
            // which patches are installed, including in multi-patch
            // installations.
            pairedPropertyRow = pairedPropertyTable.CreateRow(patchIdSymbol.SourceLineNumbers);
            pairedPropertyRow.Operation = RowOperation.Add;
            pairedPropertyRow[0] = String.Concat(patchIdSymbol.ClientPatchId, ".PatchCode");
            pairedPropertyRow[1] = patchIdSymbol.Id.Id;

            // Add PATCHNEWPACKAGECODE to apply to admin layouts.
            pairedPropertyRow = pairedPropertyTable.CreateRow(patchIdSymbol.SourceLineNumbers);
            pairedPropertyRow.Operation = RowOperation.Add;
            pairedPropertyRow[0] = "PATCHNEWPACKAGECODE";
            pairedPropertyRow[1] = patchIdSymbol.Id.Id;

            // Add PATCHNEWSUMMARYCOMMENTS and PATCHNEWSUMMARYSUBJECT to apply to admin layouts.
            if (summaryInfo.TryGetValue(SummaryInformationType.Subject, out var subjectSymbol))
            {
                pairedPropertyRow = pairedPropertyTable.CreateRow(subjectSymbol.SourceLineNumbers);
                pairedPropertyRow.Operation = RowOperation.Add;
                pairedPropertyRow[0] = "PATCHNEWSUMMARYSUBJECT";
                pairedPropertyRow[1] = subjectSymbol.Value;
            }

            if (summaryInfo.TryGetValue(SummaryInformationType.Comments, out var commentsSymbol))
            {
                pairedPropertyRow = pairedPropertyTable.CreateRow(commentsSymbol.SourceLineNumbers);
                pairedPropertyRow.Operation = RowOperation.Add;
                pairedPropertyRow[0] = "PATCHNEWSUMMARYCOMMENTS";
                pairedPropertyRow[1] = commentsSymbol.Value;
            }

            return pairedTransform;
        }

        private static SortedSet<string> FinalizePatchProductCodes(List<IntermediateSymbol> symbols, SortedSet<string> productCodes)
        {
            var patchTargetSymbols = symbols.OfType<WixPatchTargetSymbol>().ToList();

            if (patchTargetSymbols.Any())
            {
                var targets = new SortedSet<string>();
                var replace = true;
                foreach (var wixPatchTargetRow in patchTargetSymbols)
                {
                    var target = wixPatchTargetRow.ProductCode.ToUpperInvariant();
                    if (target == "*")
                    {
                        replace = false;
                    }
                    else
                    {
                        targets.Add(target);
                    }
                }

                // Replace the target ProductCodes with the authored list.
                if (replace)
                {
                    productCodes = targets;
                }
                else
                {
                    // Copy the authored target ProductCodes into the list.
                    foreach (var target in targets)
                    {
                        productCodes.Add(target);
                    }
                }
            }

            return productCodes;
        }
    }
}