forked from wixtoolset/wix3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binder.cs
7917 lines (7000 loc) · 378 KB
/
Binder.cs
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) .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 Microsoft.Tools.WindowsInstallerXml
{
using Microsoft.Tools.WindowsInstallerXml.Cab;
using Microsoft.Tools.WindowsInstallerXml.CLR.Interop;
using Microsoft.Tools.WindowsInstallerXml.MergeMod;
using Microsoft.Tools.WindowsInstallerXml.Msi;
using Microsoft.Tools.WindowsInstallerXml.Msi.Interop;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.XPath;
// TODO: (4.0) Refactor so that these don't need to be copied.
// Copied verbatim from ext\UtilExtension\wixext\UtilCompiler.cs
[Flags]
internal enum WixFileSearchAttributes
{
Default = 0x001,
MinVersionInclusive = 0x002,
MaxVersionInclusive = 0x004,
MinSizeInclusive = 0x008,
MaxSizeInclusive = 0x010,
MinDateInclusive = 0x020,
MaxDateInclusive = 0x040,
WantVersion = 0x080,
WantExists = 0x100,
IsDirectory = 0x200,
}
[Flags]
internal enum WixRegistrySearchAttributes
{
Raw = 0x01,
Compatible = 0x02,
ExpandEnvironmentVariables = 0x04,
WantValue = 0x08,
WantExists = 0x10,
Win64 = 0x20,
}
internal enum WixComponentSearchAttributes
{
KeyPath = 0x1,
State = 0x2,
WantDirectory = 0x4,
}
[Flags]
internal enum WixProductSearchAttributes
{
Version = 0x01,
Language = 0x02,
State = 0x04,
Assignment = 0x08,
UpgradeCode = 0x10,
}
/// <summary>
/// Binder core of the Windows Installer Xml toolset.
/// </summary>
public sealed class Binder : WixBinder, IDisposable
{
// as outlined in RFC 4122, this is our namespace for generating name-based (version 3) UUIDs
private static readonly Guid WixComponentGuidNamespace = new Guid("{3064E5C6-FB63-4FE9-AC49-E446A792EFA5}");
// String to be used for setting Row values to NULL that are non-nullable
private static readonly string NullString = ((char)21).ToString();
internal static readonly string PARAM_SPSD_NAME = "SuppressPatchSequenceData";
// The following constants must stay in sync with src\burn\engine\core.h
private const string BURN_BUNDLE_NAME = "WixBundleName";
private const string BURN_BUNDLE_ORIGINAL_SOURCE = "WixBundleOriginalSource";
private const string BURN_BUNDLE_ORIGINAL_SOURCE_FOLDER = "WixBundleOriginalSourceFolder";
private const string BURN_BUNDLE_LAST_USED_SOURCE = "WixBundleLastUsedSource";
private string emptyFile;
private bool backwardsCompatibleGuidGen;
private int cabbingThreadCount;
private string cabCachePath;
private Cab.CompressionLevel defaultCompressionLevel;
private bool exactAssemblyVersions;
private bool setMsiAssemblyNameFileVersion;
private string pdbFile;
private bool reuseCabinets;
private bool suppressAssemblies;
private bool suppressAclReset;
private bool suppressFileHashAndInfo;
private StringCollection suppressICEs;
private bool suppressLayout;
private bool suppressPatchSequenceData;
private bool suppressWixPdb;
private bool suppressValidation;
private bool allowEmptyTransforms;
private StringCollection nonEmptyProductCodes;
private StringCollection nonEmptyTransformNames;
private StringCollection emptyTransformNames;
private StringCollection ices;
private StringCollection invalidArgs;
private bool suppressAddingValidationRows;
private Validator validator;
private string contentsFile;
private string outputsFile;
private string builtOutputsFile;
private string wixprojectFile;
// Following object handles are needed by the NewCabNamesCallBack callback
private ArrayList fileTransfers; // File Transfers for BindDatabase Only and not the one for BindBundle
private Output output;
internal FileSplitCabNamesCallback newCabNamesCallBack;
private Dictionary<string, string> lastCabinetAddedToMediaTable; // Key is First Cabinet Name, Value is Last Cabinet Added in the Split Sequence
/// <summary>
/// Creates an MSI binder.
/// </summary>
public Binder()
{
this.defaultCompressionLevel = Cab.CompressionLevel.Mszip;
this.suppressICEs = new StringCollection();
this.ices = new StringCollection();
this.invalidArgs = new StringCollection();
this.validator = new Validator();
// Need fileTransfers handle for NewCabNamesCallBack callback
this.fileTransfers = new ArrayList();
this.newCabNamesCallBack = NewCabNamesCallBack;
this.lastCabinetAddedToMediaTable = new Dictionary<string, string>();
this.nonEmptyProductCodes = new StringCollection();
this.nonEmptyTransformNames = new StringCollection();
this.emptyTransformNames = new StringCollection();
}
/// <summary>
/// Gets or sets whether the GUID generation should use a backwards
/// compatible version (i.e. MD5).
/// </summary>
public bool BackwardsCompatibleGuidGen
{
get { return this.backwardsCompatibleGuidGen; }
set { this.backwardsCompatibleGuidGen = value; }
}
/// <summary>
/// Gets or sets the number of threads to use for cabinet creation.
/// </summary>
/// <value>The number of threads to use for cabinet creation.</value>
public int CabbingThreadCount
{
get { return this.cabbingThreadCount; }
set { this.cabbingThreadCount = value; }
}
/// <summary>
/// Gets or sets the default compression level to use for cabinets
/// that don't have their compression level explicitly set.
/// </summary>
public Cab.CompressionLevel DefaultCompressionLevel
{
get { return this.defaultCompressionLevel; }
set { this.defaultCompressionLevel = value; }
}
/// <summary>
/// Gets or sets the exact assembly versions flag (see docs).
/// </summary>
public bool ExactAssemblyVersions
{
get { return this.exactAssemblyVersions; }
set { this.exactAssemblyVersions = value; }
}
/// <summary>
/// Gets and sets the location to save the WixPdb.
/// </summary>
/// <value>The location in which to save the WixPdb. Null if the the WixPdb should not be output.</value>
public string PdbFile
{
get { return this.pdbFile; }
set { this.pdbFile = value; }
}
/// <summary>
/// Gets and sets the option to set the file version in the MsiAssemblyName table.
/// </summary>
/// <value>The option to set the file version in the MsiAssemblyName table.</value>
public bool SetMsiAssemblyNameFileVersion
{
get { return this.setMsiAssemblyNameFileVersion; }
set { this.setMsiAssemblyNameFileVersion = value; }
}
/// <summary>
/// Gets and sets the option to suppress resetting ACLs by the binder.
/// </summary>
/// <value>The option to suppress resetting ACLs by the binder.</value>
public bool SuppressAclReset
{
get { return this.suppressAclReset; }
set { this.suppressAclReset = value; }
}
/// <summary>
/// Gets and sets the option to suppress adding _Validation rows.
/// </summary>
/// <value>The option to suppress adding _Validation rows.</value>
public bool SuppressAddingValidationRows
{
get { return this.suppressAddingValidationRows; }
set { this.suppressAddingValidationRows = value; }
}
/// <summary>
/// Gets and sets the option to suppress grabbing assembly name information from assemblies.
/// </summary>
/// <value>The option to suppress grabbing assembly name information from assemblies.</value>
public bool SuppressAssemblies
{
get { return this.suppressAssemblies; }
set { this.suppressAssemblies = value; }
}
/// <summary>
/// Gets and sets the option to suppress grabbing the file hash, version and language at link time.
/// </summary>
/// <value>The option to suppress grabbing the file hash, version and language.</value>
public bool SuppressFileHashAndInfo
{
get { return this.suppressFileHashAndInfo; }
set { this.suppressFileHashAndInfo = value; }
}
/// <summary>
/// Gets and sets the option to suppress creating an image for MSI/MSM.
/// </summary>
/// <value>The option to suppress creating an image for MSI/MSM.</value>
public bool SuppressLayout
{
get { return this.suppressLayout; }
set { this.suppressLayout = value; }
}
/// <summary>
/// Gets and sets the option to allow patching despite having one or more empty transforms.
/// </summary>
/// <value>The option to allow patching despite having one or more empty transforms.</value>
public bool AllowEmptyTransforms
{
get { return this.allowEmptyTransforms; }
set { this.allowEmptyTransforms = value; }
}
/// <summary>
/// Gets and sets the option to suppress MSI/MSM validation.
/// </summary>
/// <value>The option to suppress MSI/MSM validation.</value>
/// <remarks>This must be set before calling Bind.</remarks>
public bool SuppressValidation
{
get
{
return this.suppressValidation;
}
set
{
// make a new validator if validation has been turned off and is now being turned back on
if (!value && null == this.validator)
{
this.validator = new Validator();
}
this.suppressValidation = value;
}
}
/// <summary>
/// Gets help for all the command line arguments for this binder.
/// </summary>
/// <returns>A string to be added to light's help string.</returns>
public override string GetCommandLineArgumentsHelpString()
{
return WixStrings.BinderArguments;
}
/// <summary>
/// Parse the commandline arguments.
/// </summary>
/// <param name="args">Commandline arguments.</param>
/// <param name="consoleMessageHandler">The console message handler.</param>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "These strings are not round tripped, and have no security impact")]
public override StringCollection ParseCommandLine(string[] args, ConsoleMessageHandler consoleMessageHandler)
{
for (int i = 0; i < args.Length; ++i)
{
string arg = args[i];
if (null == arg || 0 == arg.Length) // skip blank arguments
{
continue;
}
if ('-' == arg[0] || '/' == arg[0])
{
string parameter = arg.Substring(1);
if (parameter.Equals("bcgg", StringComparison.Ordinal))
{
consoleMessageHandler.Display(this, WixWarnings.DeprecatedCommandLineSwitch(parameter));
this.backwardsCompatibleGuidGen = true;
}
else if (parameter.Equals("cc", StringComparison.Ordinal))
{
this.cabCachePath = CommandLine.GetDirectory(parameter, consoleMessageHandler, args, ++i);
if (String.IsNullOrEmpty(this.cabCachePath))
{
return this.invalidArgs;
}
}
else if (parameter.Equals("ct", StringComparison.Ordinal))
{
if (!CommandLine.IsValidArg(args, ++i))
{
consoleMessageHandler.Display(this, WixErrors.IllegalCabbingThreadCount(String.Empty));
return this.invalidArgs;
}
try
{
this.cabbingThreadCount = Convert.ToInt32(args[i], CultureInfo.InvariantCulture.NumberFormat);
if (0 >= this.cabbingThreadCount)
{
consoleMessageHandler.Display(this, WixErrors.IllegalCabbingThreadCount(args[i]));
}
consoleMessageHandler.Display(this, WixVerboses.SetCabbingThreadCount(this.cabbingThreadCount.ToString()));
}
catch (FormatException)
{
consoleMessageHandler.Display(this, WixErrors.IllegalCabbingThreadCount(args[i]));
}
catch (OverflowException)
{
consoleMessageHandler.Display(this, WixErrors.IllegalCabbingThreadCount(args[i]));
}
}
else if (parameter.Equals("cub", StringComparison.Ordinal))
{
string cubeFile = CommandLine.GetFile(parameter, consoleMessageHandler, args, ++i);
if (String.IsNullOrEmpty(cubeFile))
{
return this.invalidArgs;
}
this.validator.AddCubeFile(cubeFile);
}
else if (parameter.StartsWith("dcl:", StringComparison.Ordinal))
{
string defaultCompressionLevel = arg.Substring(5);
if (String.IsNullOrEmpty(defaultCompressionLevel))
{
return this.invalidArgs;
}
this.defaultCompressionLevel = WixCreateCab.CompressionLevelFromString(defaultCompressionLevel);
}
else if (parameter.Equals("eav", StringComparison.Ordinal))
{
this.exactAssemblyVersions = true;
}
else if (parameter.Equals("fv", StringComparison.Ordinal))
{
this.setMsiAssemblyNameFileVersion = true;
}
else if (parameter.StartsWith("ice:", StringComparison.Ordinal))
{
this.ices.Add(parameter.Substring(4));
}
else if (parameter.Equals("contentsfile", StringComparison.Ordinal))
{
this.contentsFile = CommandLine.GetFile(parameter, consoleMessageHandler, args, ++i);
if (String.IsNullOrEmpty(this.contentsFile))
{
return this.invalidArgs;
}
}
else if (parameter.Equals("outputsfile", StringComparison.Ordinal))
{
this.outputsFile = CommandLine.GetFile(parameter, consoleMessageHandler, args, ++i);
if (String.IsNullOrEmpty(this.outputsFile))
{
return this.invalidArgs;
}
}
else if (parameter.Equals("builtoutputsfile", StringComparison.Ordinal))
{
this.builtOutputsFile = CommandLine.GetFile(parameter, consoleMessageHandler, args, ++i);
if (String.IsNullOrEmpty(this.builtOutputsFile))
{
return this.invalidArgs;
}
}
else if (parameter.Equals("wixprojectfile", StringComparison.Ordinal))
{
this.wixprojectFile = CommandLine.GetFile(parameter, consoleMessageHandler, args, ++i);
if (String.IsNullOrEmpty(this.wixprojectFile))
{
return this.invalidArgs;
}
}
else if (parameter.Equals("O1", StringComparison.Ordinal))
{
consoleMessageHandler.Display(this, WixWarnings.DeprecatedCommandLineSwitch("O1"));
}
else if (parameter.Equals("O2", StringComparison.Ordinal))
{
consoleMessageHandler.Display(this, WixWarnings.DeprecatedCommandLineSwitch("O2"));
}
else if (parameter.Equals("pdbout", StringComparison.Ordinal))
{
this.pdbFile = CommandLine.GetFile(parameter, consoleMessageHandler, args, ++i);
if (String.IsNullOrEmpty(this.pdbFile))
{
return this.invalidArgs;
}
}
else if (parameter.Equals("reusecab", StringComparison.Ordinal))
{
this.reuseCabinets = true;
}
else if (parameter.Equals("sa", StringComparison.Ordinal))
{
consoleMessageHandler.Display(this, WixWarnings.DeprecatedCommandLineSwitch(parameter));
this.suppressAssemblies = true;
}
else if (parameter.Equals("sacl", StringComparison.Ordinal))
{
this.suppressAclReset = true;
}
else if (parameter.Equals("sbuildinfo", StringComparison.Ordinal))
{
consoleMessageHandler.Display(this, WixWarnings.DeprecatedCommandLineSwitch(parameter));
}
else if (parameter.Equals("sf", StringComparison.Ordinal))
{
consoleMessageHandler.Display(this, WixWarnings.DeprecatedCommandLineSwitch(parameter));
this.suppressAssemblies = true;
this.suppressFileHashAndInfo = true;
}
else if (parameter.Equals("sh", StringComparison.Ordinal))
{
consoleMessageHandler.Display(this, WixWarnings.DeprecatedCommandLineSwitch(parameter));
this.suppressFileHashAndInfo = true;
}
else if (parameter.StartsWith("sice:", StringComparison.Ordinal))
{
this.suppressICEs.Add(parameter.Substring(5));
}
else if (parameter.Equals("sl", StringComparison.Ordinal))
{
this.suppressLayout = true;
}
else if (parameter.Equals("spdb", StringComparison.Ordinal))
{
this.suppressWixPdb = true;
}
else if (parameter.Equals("spsd", StringComparison.Ordinal))
{
this.suppressPatchSequenceData = true;
}
else if (parameter.Equals("sval", StringComparison.Ordinal))
{
this.suppressValidation = true;
}
else
{
this.invalidArgs.Add(arg);
}
}
else
{
this.invalidArgs.Add(arg);
}
}
this.pdbFile = this.suppressWixPdb ? null : this.pdbFile;
return this.invalidArgs;
}
/// <summary>
/// Do any setting up needed after all command line parsing.
/// </summary>
public override void PostParseCommandLine()
{
if (!this.suppressWixPdb && null == this.pdbFile && null != this.OutputFile)
{
this.pdbFile = Path.ChangeExtension(this.OutputFile, ".wixpdb");
}
}
/// <summary>
/// Adds an event handler.
/// </summary>
/// <param name="newHandler">The event handler to add.</param>
public override void AddMessageEventHandler(MessageEventHandler newHandler)
{
base.AddMessageEventHandler(newHandler);
validator.Extension.Message += newHandler;
}
/// <summary>
/// Binds an output.
/// </summary>
/// <param name="output">The output to bind.</param>
/// <param name="file">The Windows Installer file to create.</param>
/// <remarks>The Binder.DeleteTempFiles method should be called after calling this method.</remarks>
/// <returns>true if binding completed successfully; false otherwise</returns>
public override bool Bind(Output output, string file)
{
// Need output object handle for NewCabNamesCallBack callback
this.output = output;
// ensure the cabinet cache path exists if we are going to use it
if (null != this.cabCachePath && !Directory.Exists(this.cabCachePath))
{
Directory.CreateDirectory(this.cabCachePath);
}
// tell the binder about the validator if validation isn't suppressed
if (!this.suppressValidation && (OutputType.Module == output.Type || OutputType.Product == output.Type))
{
if (String.IsNullOrEmpty(this.validator.TempFilesLocation))
{
this.validator.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP");
}
// set the default cube file
Assembly lightAssembly = Assembly.GetExecutingAssembly();
string lightDirectory = Path.GetDirectoryName(lightAssembly.Location);
if (OutputType.Module == output.Type)
{
this.validator.AddCubeFile(Path.Combine(lightDirectory, "mergemod.cub"));
}
else // product
{
this.validator.AddCubeFile(Path.Combine(lightDirectory, "darice.cub"));
}
// by default, disable ICEs that have equivalent-or-better checks in WiX
this.suppressICEs.Add("ICE08");
this.suppressICEs.Add("ICE33");
this.suppressICEs.Add("ICE47");
this.suppressICEs.Add("ICE66");
// set the ICEs
string[] iceArray = new string[this.ices.Count];
this.ices.CopyTo(iceArray, 0);
this.validator.ICEs = iceArray;
// set the suppressed ICEs
string[] suppressICEArray = new string[this.suppressICEs.Count];
this.suppressICEs.CopyTo(suppressICEArray, 0);
this.validator.SuppressedICEs = suppressICEArray;
}
else
{
this.validator = null;
}
this.core = new BinderCore(this.MessageHandler);
this.FileManager.MessageHandler = this.core;
// Add properties we need to pass to other classes.
if (this.suppressPatchSequenceData)
{
// Avoid unnecessary boxing if false.
this.core.SetProperty(Binder.PARAM_SPSD_NAME, true);
}
this.core.SetProperty(BinderCore.OutputPath, file);
if (!String.IsNullOrEmpty(this.outputsFile))
{
this.core.SetProperty(BinderCore.IntermediateFolder, Path.GetDirectoryName(this.outputsFile));
}
else if (!String.IsNullOrEmpty(this.contentsFile))
{
this.core.SetProperty(BinderCore.IntermediateFolder, Path.GetDirectoryName(this.contentsFile));
}
else if (!String.IsNullOrEmpty(this.builtOutputsFile))
{
this.core.SetProperty(BinderCore.IntermediateFolder, Path.GetDirectoryName(this.builtOutputsFile));
}
foreach (BinderExtension extension in this.extensions)
{
extension.Core = this.core;
}
if (null == output)
{
throw new ArgumentNullException("output");
}
this.core.EncounteredError = false;
switch (output.Type)
{
case OutputType.Bundle:
return this.BindBundle(output, file);
case OutputType.Transform:
return this.BindTransform(output, file);
default:
return this.BindDatabase(output, file);
}
}
/// <summary>
/// Does any housekeeping after Bind.
/// </summary>
/// <param name="tidy">Whether or not any actual tidying should be done.</param>
public override void Cleanup(bool tidy)
{
// If Bind hasn't been called yet, core will be null. There will be
// nothing to cleanup.
if (this.core == null)
{
return;
}
if (tidy)
{
if (!this.DeleteTempFiles())
{
this.core.OnMessage(WixWarnings.FailedToDeleteTempDir(this.TempFilesLocation));
}
}
else
{
this.core.OnMessage(WixVerboses.BinderTempDirLocatedAt(this.TempFilesLocation));
}
if (null != this.validator && !String.IsNullOrEmpty(this.validator.TempFilesLocation))
{
if (tidy)
{
if (!this.validator.DeleteTempFiles())
{
this.core.OnMessage(WixWarnings.FailedToDeleteTempDir(this.validator.TempFilesLocation));
}
}
else
{
this.core.OnMessage(WixVerboses.ValidatorTempDirLocatedAt(this.validator.TempFilesLocation));
}
}
}
/// <summary>
/// Cleans up the temp files used by the Binder.
/// </summary>
/// <returns>True if all files were deleted, false otherwise.</returns>
public override bool DeleteTempFiles()
{
bool deleted = base.DeleteTempFiles();
if (deleted)
{
this.emptyFile = null;
}
return deleted;
}
/// <summary>
/// Process a list of loaded extensions.
/// </summary>
/// <param name="loadedExtensionList">The list of loaded extensions.</param>
public override void ProcessExtensions(WixExtension[] loadedExtensionList)
{
bool binderFileManagerLoaded = false;
bool validatorExtensionLoaded = false;
foreach (WixExtension wixExtension in loadedExtensionList)
{
if (null != wixExtension.BinderFileManager)
{
if (binderFileManagerLoaded)
{
core.OnMessage(WixErrors.CannotLoadBinderFileManager(wixExtension.BinderFileManager.GetType().ToString(), this.FileManager.ToString()));
}
this.FileManager = wixExtension.BinderFileManager;
binderFileManagerLoaded = true;
}
ValidatorExtension validatorExtension = wixExtension.ValidatorExtension;
if (null != validatorExtension)
{
if (validatorExtensionLoaded)
{
core.OnMessage(WixErrors.CannotLoadLinkerExtension(validatorExtension.GetType().ToString(), this.validator.Extension.ToString()));
}
this.validator.Extension = validatorExtension;
validatorExtensionLoaded = true;
}
}
this.FileManager.CabCachePath = this.cabCachePath;
this.FileManager.ReuseCabinets = this.reuseCabinets;
}
/// <summary>
/// Creates the MSI/MSM/PCP database.
/// </summary>
/// <param name="output">Output to create database for.</param>
/// <param name="databaseFile">The database file to create.</param>
/// <param name="keepAddedColumns">Whether to keep columns added in a transform.</param>
/// <param name="useSubdirectory">Whether to use a subdirectory based on the <paramref name="databaseFile"/> file name for intermediate files.</param>
internal void GenerateDatabase(Output output, string databaseFile, bool keepAddedColumns, bool useSubdirectory)
{
// add the _Validation rows
if (!this.suppressAddingValidationRows)
{
Table validationTable = output.EnsureTable(this.core.TableDefinitions["_Validation"]);
foreach (Table table in output.Tables)
{
if (!table.Definition.IsUnreal)
{
// add the validation rows for this table
table.Definition.AddValidationRows(validationTable);
}
}
}
// set the base directory
string baseDirectory = this.TempFilesLocation;
if (useSubdirectory)
{
string filename = Path.GetFileNameWithoutExtension(databaseFile);
baseDirectory = Path.Combine(baseDirectory, filename);
// make sure the directory exists
Directory.CreateDirectory(baseDirectory);
}
try
{
OpenDatabase type = OpenDatabase.CreateDirect;
// set special flag for patch files
if (OutputType.Patch == output.Type)
{
type |= OpenDatabase.OpenPatchFile;
}
// try to create the database
using (Database db = new Database(databaseFile, type))
{
// localize the codepage if a value was specified by the localizer
if (null != this.Localizer && -1 != this.Localizer.Codepage)
{
output.Codepage = this.Localizer.Codepage;
}
// if we're not using the default codepage, import a new one into our
// database before we add any tables (or the tables would be added
// with the wrong codepage)
if (0 != output.Codepage)
{
this.SetDatabaseCodepage(db, output);
}
// insert substorages (like transforms inside a patch)
if (0 < output.SubStorages.Count)
{
using (View storagesView = new View(db, "SELECT `Name`, `Data` FROM `_Storages`"))
{
foreach (SubStorage subStorage in output.SubStorages)
{
string transformFile = Path.Combine(this.TempFilesLocation, String.Concat(subStorage.Name, ".mst"));
// bind the transform
if (this.BindTransform(subStorage.Data, transformFile))
{
// add the storage
using (Record record = new Record(2))
{
record.SetString(1, subStorage.Name);
record.SetStream(2, transformFile);
storagesView.Modify(ModifyView.Assign, record);
}
}
}
}
// some empty transforms may have been excluded
// we need to remove these from the final patch summary information
if (OutputType.Patch == output.Type && this.AllowEmptyTransforms)
{
Table patchSummaryInfo = output.EnsureTable(this.core.TableDefinitions["_SummaryInformation"]);
for (int i = patchSummaryInfo.Rows.Count - 1; i >= 0; i--)
{
Row row = patchSummaryInfo.Rows[i];
if ((int)SummaryInformation.Patch.ProductCodes == (int)row[0])
{
if (nonEmptyProductCodes.Count > 0)
{
string[] productCodes = new string[nonEmptyProductCodes.Count];
nonEmptyProductCodes.CopyTo(productCodes, 0);
row[1] = String.Join(";", productCodes);
}
else
{
row[1] = Binder.NullString;
}
}
else if ((int)SummaryInformation.Patch.TransformNames == (int)row[0])
{
if (nonEmptyTransformNames.Count > 0)
{
string[] transformNames = new string[nonEmptyTransformNames.Count];
nonEmptyTransformNames.CopyTo(transformNames, 0);
row[1] = String.Join(";", transformNames);
}
else
{
row[1] = Binder.NullString;
}
}
}
}
}
foreach (Table table in output.Tables)
{
Table importTable = table;
bool hasBinaryColumn = false;
// skip all unreal tables other than _Streams
if (table.Definition.IsUnreal && "_Streams" != table.Name)
{
continue;
}
// Do not put the _Validation table in patches, it is not needed
if (OutputType.Patch == output.Type && "_Validation" == table.Name)
{
continue;
}
// The only way to import binary data is to copy it to a local subdirectory first.
// To avoid this extra copying and perf hit, import an empty table with the same
// definition and later import the binary data from source using records.
foreach (ColumnDefinition columnDefinition in table.Definition.Columns)
{
if (ColumnType.Object == columnDefinition.Type)
{
importTable = new Table(table.Section, table.Definition);
hasBinaryColumn = true;
break;
}
}
// create the table via IDT import
if ("_Streams" != importTable.Name)
{
try
{
db.ImportTable(output.Codepage, this.core, importTable, baseDirectory, keepAddedColumns);
}
catch (WixInvalidIdtException)
{
// If ValidateRows finds anything it doesn't like, it throws
importTable.ValidateRows();
// Otherwise we rethrow the InvalidIdt
throw;
}
}
// insert the rows via SQL query if this table contains object fields
if (hasBinaryColumn)
{
StringBuilder query = new StringBuilder("SELECT ");
// build the query for the view
bool firstColumn = true;
foreach (ColumnDefinition columnDefinition in table.Definition.Columns)
{
if (!firstColumn)
{
query.Append(",");
}
query.AppendFormat(" `{0}`", columnDefinition.Name);
firstColumn = false;
}
query.AppendFormat(" FROM `{0}`", table.Name);
using (View tableView = db.OpenExecuteView(query.ToString()))
{
// import each row containing a stream
foreach (Row row in table.Rows)
{
using (Record record = new Record(table.Definition.Columns.Count))
{
StringBuilder streamName = new StringBuilder();
bool needStream = false;
// the _Streams table doesn't prepend the table name (or a period)
if ("_Streams" != table.Name)
{
streamName.Append(table.Name);
}
for (int i = 0; i < table.Definition.Columns.Count; i++)
{
ColumnDefinition columnDefinition = table.Definition.Columns[i];
switch (columnDefinition.Type)
{
case ColumnType.Localized:
case ColumnType.Preserved:
case ColumnType.String:
if (columnDefinition.IsPrimaryKey)
{
if (0 < streamName.Length)
{
streamName.Append(".");
}
streamName.Append((string)row[i]);
}
record.SetString(i + 1, (string)row[i]);
break;
case ColumnType.Number:
record.SetInteger(i + 1, Convert.ToInt32(row[i], CultureInfo.InvariantCulture));
break;
case ColumnType.Object:
if (null != row[i])
{
needStream = true;
try
{
record.SetStream(i + 1, (string)row[i]);
}
catch (Win32Exception e)
{
if (0xA1 == e.NativeErrorCode) // ERROR_BAD_PATHNAME
{
throw new WixException(WixErrors.FileNotFound(row.SourceLineNumbers, (string)row[i]));
}
else
{
throw new WixException(WixErrors.Win32Exception(e.NativeErrorCode, e.Message));
}
}
}
break;
}
}
// stream names are created by concatenating the name of the table with the values
// of the primary key (delimited by periods)
// check for a stream name that is more than 62 characters long (the maximum allowed length)
if (needStream && MsiInterop.MsiMaxStreamNameLength < streamName.Length)
{
this.core.OnMessage(WixErrors.StreamNameTooLong(row.SourceLineNumbers, table.Name, streamName.ToString(), streamName.Length));
}
else // add the row to the database