forked from dotnet/msbuild
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolutionProjectGenerator.cs
2434 lines (2127 loc) · 133 KB
/
SolutionProjectGenerator.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
#if FEATURE_ASPNET_COMPILER
using System.Collections;
#endif
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.Build.BackEnd.SdkResolution;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Project = Microsoft.Build.Evaluation.Project;
using ProjectCollection = Microsoft.Build.Evaluation.ProjectCollection;
using ProjectItem = Microsoft.Build.Evaluation.ProjectItem;
using IProperty = Microsoft.Build.Evaluation.IProperty;
using Constants = Microsoft.Build.Internal.Constants;
using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService;
#if FEATURE_ASPNET_COMPILER
using FrameworkName = System.Runtime.Versioning.FrameworkName;
#endif
using Microsoft.Build.Execution;
using Microsoft.NET.StringTools;
#nullable disable
namespace Microsoft.Build.Construction
{
/// <summary>
/// This class is used to generate an MSBuild wrapper project for a solution file.
/// </summary>
internal class SolutionProjectGenerator
{
/// <summary>
/// Name of the property used to store the path to the solution being built.
/// </summary>
internal const string SolutionPathPropertyName = "SolutionPath";
#if FEATURE_ASPNET_COMPILER
/// <summary>
/// The path node to add in when the output directory for a website is overridden.
/// </summary>
private const string WebProjectOverrideFolder = "_PublishedWebsites";
#endif // FEATURE_ASPNET_COMPILER
/// <summary>
/// Property set by VS when building projects. It's an XML containing the project configurations for ALL projects in the solution for the currently selected solution configuration.
/// </summary>
internal const string CurrentSolutionConfigurationContents = nameof(CurrentSolutionConfigurationContents);
/// <summary>
/// The set of properties all projects in the solution should be built with
/// </summary>
private const string SolutionProperties = "BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)";
/// <summary>
/// The set of properties which identify the configuration and platform to build a project with
/// </summary>
private const string SolutionConfigurationAndPlatformProperties = "Configuration=$(Configuration); Platform=$(Platform)";
/// <summary>
/// The Special Target name which when <see cref="_batchProjectTargets"/> is enabled, all P2P references will just execute this target.
/// </summary>
internal const string SolutionProjectReferenceAllTargets = "SlnProjectResolveProjectReference";
/// <summary>
/// A known list of target names to create. This is for backwards compatibility.
/// </summary>
internal static readonly ImmutableHashSet<string> _defaultTargetNames = ImmutableHashSet.Create(StringComparer.OrdinalIgnoreCase,
"Build",
"Clean",
"Rebuild",
"Publish",
"ValidateSolutionConfiguration",
"ValidateToolsVersions",
"ValidateProjects",
"GetSolutionConfigurationContents");
#if FEATURE_ASPNET_COMPILER
/// <summary>
/// Version 2.0
/// </summary>
private readonly Version _version20 = new Version(2, 0);
/// <summary>
/// Version 4.0
/// </summary>
private readonly Version _version40 = new Version(4, 0);
#endif // FEATURE_ASPNET_COMPILER
/// <summary>
/// The list of global properties we set on each metaproject and which get passed to each project when building.
/// </summary>
private readonly Tuple<string, string>[] _metaprojectGlobalProperties =
{
new Tuple<string, string>("Configuration", null), // This is the solution configuration in a metaproject, and project configuration on an actual project
new Tuple<string, string>("Platform", null), // This is the solution platform in a metaproject, and project platform on an actual project
new Tuple<string, string>("BuildingSolutionFile", "true"),
new Tuple<string, string>("CurrentSolutionConfigurationContents", null),
new Tuple<string, string>("SolutionDir", null),
new Tuple<string, string>("SolutionExt", null),
new Tuple<string, string>("SolutionFileName", null),
new Tuple<string, string>("SolutionName", null),
new Tuple<string, string>(SolutionPathPropertyName, null)
};
/// <summary>
/// The SolutionFile containing information about the solution we're generating a wrapper for.
/// </summary>
private readonly SolutionFile _solutionFile;
/// <summary>
/// The global properties passed under which the project should be opened.
/// </summary>
private readonly IDictionary<string, string> _globalProperties;
/// <summary>
/// The ToolsVersion passed on the commandline, if any. May be null.
/// </summary>
private readonly string _toolsVersionOverride;
/// <summary>
/// The context of this build (used for logging purposes).
/// </summary>
private readonly BuildEventContext _projectBuildEventContext;
/// <summary>
/// The LoggingService used to log messages.
/// </summary>
private readonly ILoggingService _loggingService;
/// <summary>
/// The list of targets specified to use.
/// </summary>
private readonly IReadOnlyCollection<string> _targetNames = new Collection<string>();
/// <summary>
/// The solution configuration selected for this build.
/// </summary>
private string _selectedSolutionConfiguration;
/// <summary>
/// The <see cref="ISdkResolverService"/> to use.
/// </summary>
private readonly ISdkResolverService _sdkResolverService;
/// <summary>
/// The current build submission ID.
/// </summary>
private readonly int _submissionId;
/// <summary>
/// Create a solution metaproj with one MSBuild task with all project references.
/// </summary>
private readonly bool _batchProjectTargets;
/// <summary>
/// Constructor.
/// </summary>
private SolutionProjectGenerator(
SolutionFile solution,
IDictionary<string, string> globalProperties,
string toolsVersionOverride,
BuildEventContext projectBuildEventContext,
ILoggingService loggingService,
IReadOnlyCollection<string> targetNames,
ISdkResolverService sdkResolverService,
int submissionId)
{
_solutionFile = solution;
_globalProperties = globalProperties ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
_toolsVersionOverride = toolsVersionOverride;
_projectBuildEventContext = projectBuildEventContext;
_loggingService = loggingService;
_sdkResolverService = sdkResolverService ?? SdkResolverService.Instance;
_submissionId = submissionId;
_batchProjectTargets = Traits.Instance.SolutionBatchTargets;
if (targetNames != null)
{
_targetNames = targetNames.Select(i => i.Split([':'], 2, StringSplitOptions.RemoveEmptyEntries).Last()).ToList();
}
}
/// <summary>
/// This method generates an MSBuild project file from the list of projects and project dependencies
/// that have been collected from the solution file.
/// </summary>
/// <param name="solution">The parser which contains the solution file.</param>
/// <param name="globalProperties">The global properties.</param>
/// <param name="toolsVersionOverride">Tools Version override (may be null). This should be any tools version explicitly passed to the command-line or from an MSBuild ToolsVersion parameter.</param>
/// <param name="projectBuildEventContext">The logging context for this project.</param>
/// <param name="loggingService">The logging service.</param>
/// <param name="targetNames">A collection of target names the user requested to be built.</param>
/// <param name="sdkResolverService">An <see cref="ISdkResolverService"/> to use.</param>
/// <param name="submissionId">The current build submission ID.</param>
/// <returns>An array of ProjectInstances. The first instance is the traversal project, the remaining are the metaprojects for each project referenced in the solution.</returns>
internal static ProjectInstance[] Generate(
SolutionFile solution,
IDictionary<string, string> globalProperties,
string toolsVersionOverride,
BuildEventContext projectBuildEventContext,
ILoggingService loggingService,
IReadOnlyCollection<string> targetNames = default(IReadOnlyCollection<string>),
ISdkResolverService sdkResolverService = null,
int submissionId = BuildEventContext.InvalidSubmissionId)
{
SolutionProjectGenerator projectGenerator = new SolutionProjectGenerator(
solution,
globalProperties,
toolsVersionOverride,
projectBuildEventContext,
loggingService,
targetNames,
sdkResolverService,
submissionId);
return projectGenerator.Generate();
}
/// <summary>
/// Adds a new property group with contents of the given solution configuration to the project
/// Internal for unit-testing.
/// </summary>
internal static void AddPropertyGroupForSolutionConfiguration(ProjectRootElement msbuildProject, SolutionFile solutionFile, SolutionConfigurationInSolution solutionConfiguration)
{
ProjectPropertyGroupElement solutionConfigurationProperties = msbuildProject.CreatePropertyGroupElement();
msbuildProject.AppendChild(solutionConfigurationProperties);
solutionConfigurationProperties.Condition = GetConditionStringForConfiguration(solutionConfiguration);
string escapedSolutionConfigurationContents = GetSolutionConfiguration(solutionFile, solutionConfiguration);
solutionConfigurationProperties.AddProperty("CurrentSolutionConfigurationContents", escapedSolutionConfigurationContents);
msbuildProject.AddItem(
"SolutionConfiguration",
solutionConfiguration.FullName,
new Dictionary<string, string>
{
{ "Configuration", solutionConfiguration.ConfigurationName },
{ "Platform", solutionConfiguration.PlatformName },
{ "Content", escapedSolutionConfigurationContents },
});
}
internal static string GetSolutionConfiguration(SolutionFile solutionFile, SolutionConfigurationInSolution solutionConfiguration)
{
var solutionConfigurationContents = new StringBuilder(1024);
var settings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true
};
using (XmlWriter xw = XmlWriter.Create(solutionConfigurationContents, settings))
{
// TODO: Consider augmenting SolutionConfiguration with this code
xw.WriteStartElement("SolutionConfiguration");
// add a project configuration entry for each project in the solution
foreach (ProjectInSolution project in solutionFile.ProjectsInOrder)
{
if (project.ProjectConfigurations.TryGetValue(solutionConfiguration.FullName, out ProjectConfigurationInSolution projectConfiguration))
{
xw.WriteStartElement("ProjectConfiguration");
xw.WriteAttributeString("Project", project.ProjectGuid);
xw.WriteAttributeString("AbsolutePath", project.AbsolutePath);
xw.WriteAttributeString("BuildProjectInSolution", projectConfiguration.IncludeInBuild.ToString());
xw.WriteString(projectConfiguration.FullName);
foreach (string dependencyProjectGuid in project.Dependencies)
{
// This is a project that the current project depends *ON* (ie., it must build first)
if (!solutionFile.ProjectsByGuid.TryGetValue(dependencyProjectGuid, out ProjectInSolution dependencyProject))
{
// If it's not itself part of the solution, that's an invalid solution
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(dependencyProject != null, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(solutionFile.FullPath), "SolutionParseProjectDepNotFoundError", project.ProjectGuid, dependencyProjectGuid);
}
// Add it to the list of dependencies, but only if it should build in this solution configuration
// (If a project is not selected for build in the solution configuration, it won't build even if it's depended on by something that IS selected for build)
// .. and only if it's known to be MSBuild format, as projects can't use the information otherwise
if (dependencyProject.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat)
{
if (dependencyProject.ProjectConfigurations.TryGetValue(solutionConfiguration.FullName, out ProjectConfigurationInSolution dependencyProjectConfiguration) &&
WouldProjectBuild(solutionFile, solutionConfiguration.FullName, dependencyProject, dependencyProjectConfiguration))
{
xw.WriteStartElement("ProjectDependency");
xw.WriteAttributeString("Project", dependencyProjectGuid);
xw.WriteEndElement();
}
}
}
xw.WriteEndElement(); // </ProjectConfiguration>
}
}
xw.WriteEndElement(); // </SolutionConfiguration>
}
string escapedSolutionConfigurationContents = EscapingUtilities.Escape(solutionConfigurationContents.ToString());
return escapedSolutionConfigurationContents;
}
/// <summary>
/// Add a new error/warning/message tag into the given target
/// </summary>
internal static ProjectTaskElement AddErrorWarningMessageElement(
ProjectTargetElement target,
string elementType,
bool treatAsLiteral,
string textResourceName,
params object[] args)
{
string text = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out string code, out string helpKeyword, textResourceName, args);
if (treatAsLiteral)
{
text = EscapingUtilities.Escape(text);
}
ProjectTaskElement task = target.AddTask(elementType);
task.SetParameter("Text", text);
if ((elementType != XMakeElements.message) && (code != null))
{
task.SetParameter("Code", EscapingUtilities.Escape(code));
}
if ((elementType != XMakeElements.message) && (helpKeyword != null))
{
task.SetParameter("HelpKeyword", EscapingUtilities.Escape(helpKeyword));
}
return task;
}
/// <summary>
/// Normally the active solution configuration/platform is determined when we build the solution
/// wrapper project, not when we create it. However, we need to know them to scan project references
/// for the right project configuration/platform. It's unlikely that references would be conditional,
/// but still possible and we want to get that case right.
/// </summary>
internal static string PredictActiveSolutionConfigurationName(SolutionFile solutionFile, IDictionary<string, string> globalProperties)
{
string candidateFullSolutionConfigurationName = DetermineLikelyActiveSolutionConfiguration(solutionFile, globalProperties);
// Now check if this solution configuration actually exists
string fullSolutionConfigurationName = null;
foreach (SolutionConfigurationInSolution solutionConfiguration in solutionFile.SolutionConfigurations)
{
if (String.Equals(solutionConfiguration.FullName, candidateFullSolutionConfigurationName, StringComparison.OrdinalIgnoreCase))
{
fullSolutionConfigurationName = solutionConfiguration.FullName;
break;
}
}
return fullSolutionConfigurationName;
}
/// <summary>
/// Returns the name of the metaproject for an actual project.
/// </summary>
/// <param name="fullPathToProject">The full path to the actual project</param>
/// <returns>The metaproject path name</returns>
private static string GetMetaprojectName(string fullPathToProject)
{
return EscapingUtilities.Escape(fullPathToProject + ".metaproj");
}
/// <summary>
/// Figure out what tools version to build the solution wrapper project with. If a /tv
/// switch was passed in, use that; otherwise fall back to the default (12.0).
/// </summary>
private static string DetermineWrapperProjectToolsVersion(string toolsVersionOverride, out bool explicitToolsVersionSpecified)
{
string wrapperProjectToolsVersion = toolsVersionOverride;
if (wrapperProjectToolsVersion == null)
{
explicitToolsVersionSpecified = false;
wrapperProjectToolsVersion = Constants.defaultSolutionWrapperProjectToolsVersion;
}
else
{
explicitToolsVersionSpecified = true;
}
return wrapperProjectToolsVersion;
}
#if FEATURE_ASPNET_COMPILER
/// <summary>
/// Add a call to the ResolveAssemblyReference task to crack the pre-resolved referenced
/// assemblies for the complete list of dependencies, PDBs, satellites, etc. The invoke
/// the Copy task to copy all these files (or at least the ones that RAR determined should
/// be copied local) into the web project's bin directory.
/// </summary>
private static void AddTasksToCopyAllDependenciesIntoBinDir(
ProjectTargetInstance target,
ProjectInSolution project,
string referenceItemName,
string conditionDescribingValidConfigurations)
{
string copyLocalFilesItemName = referenceItemName + "_CopyLocalFiles";
string targetFrameworkDirectoriesName = GenerateSafePropertyName(project, "_TargetFrameworkDirectories");
string fullFrameworkRefAssyPathName = GenerateSafePropertyName(project, "_FullFrameworkReferenceAssemblyPaths");
string destinationFolder = String.Format(CultureInfo.InvariantCulture, @"$({0})\Bin\", GenerateSafePropertyName(project, "AspNetPhysicalPath"));
// This is a bit of a hack. We're actually calling the "Copy" task on all of
// the *non-existent* files. Why? Because we want to emit a warning in the
// log for each non-existent file, and the Copy task does that nicely for us.
// I would have used the <Warning> task except for the fact that we are in
// string-resource lockdown.
ProjectTaskInstance copyNonExistentReferencesTask = target.AddTask("Copy", String.Format(CultureInfo.InvariantCulture, "!Exists('%({0}.Identity)')", referenceItemName), "true");
copyNonExistentReferencesTask.SetParameter("SourceFiles", "@(" + referenceItemName + "->'%(FullPath)')");
copyNonExistentReferencesTask.SetParameter("DestinationFolder", destinationFolder);
// We need to determine the appropriate TargetFrameworkMoniker to pass to GetReferenceAssemblyPaths,
// so that we will pass the appropriate target framework directories to RAR.
ProjectTaskInstance getRefAssembliesTask = target.AddTask("GetReferenceAssemblyPaths", null, null);
getRefAssembliesTask.SetParameter("TargetFrameworkMoniker", project.TargetFrameworkMoniker);
getRefAssembliesTask.SetParameter("RootPath", "$(TargetFrameworkRootPath)");
getRefAssembliesTask.AddOutputProperty("ReferenceAssemblyPaths", targetFrameworkDirectoriesName, null);
getRefAssembliesTask.AddOutputProperty("FullFrameworkReferenceAssemblyPaths", fullFrameworkRefAssyPathName, null);
// Call ResolveAssemblyReference on each of the .DLL files that were found on
// disk from the .REFRESH files as well as the P2P references. RAR will crack
// the dependencies, find PDBs, satellite assemblies, etc., and determine which
// files need to be copy-localed.
ProjectTaskInstance rarTask = target.AddTask("ResolveAssemblyReference", String.Format(CultureInfo.InvariantCulture, "Exists('%({0}.Identity)')", referenceItemName), null);
rarTask.SetParameter("Assemblies", "@(" + referenceItemName + "->'%(FullPath)')");
rarTask.SetParameter("TargetFrameworkDirectories", "$(" + targetFrameworkDirectoriesName + ")");
rarTask.SetParameter("FullFrameworkFolders", "$(" + fullFrameworkRefAssyPathName + ")");
rarTask.SetParameter("SearchPaths", "{RawFileName};{TargetFrameworkDirectory};{GAC}");
rarTask.SetParameter("FindDependencies", "true");
rarTask.SetParameter("FindSatellites", "true");
rarTask.SetParameter("FindSerializationAssemblies", "true");
rarTask.SetParameter("FindRelatedFiles", "true");
rarTask.SetParameter("TargetFrameworkMoniker", project.TargetFrameworkMoniker);
rarTask.AddOutputItem("CopyLocalFiles", copyLocalFilesItemName, null);
// Copy all the copy-local files (reported by RAR) to the web project's "bin"
// directory.
ProjectTaskInstance copyTask = target.AddTask("Copy", conditionDescribingValidConfigurations, null);
copyTask.SetParameter("SourceFiles", "@(" + copyLocalFilesItemName + ")");
copyTask.SetParameter(
"DestinationFiles",
String.Format(CultureInfo.InvariantCulture, @"@({0}->'{1}%(DestinationSubDirectory)%(Filename)%(Extension)')", copyLocalFilesItemName, destinationFolder));
}
/// <summary>
/// This code handles the *.REFRESH files that are in the "bin" subdirectory of
/// a web project. These .REFRESH files are just text files that contain absolute or
/// relative paths to the referenced assemblies. The goal of these tasks is to
/// search all *.REFRESH files and extract fully-qualified absolute paths for
/// each of the references.
/// </summary>
private static void AddTasksToResolveAutoRefreshFileReferences(
ProjectTargetInstance target,
ProjectInSolution project,
string referenceItemName)
{
string webRoot = "$(" + GenerateSafePropertyName(project, "AspNetPhysicalPath") + ")";
// Create an item list containing each of the .REFRESH files.
ProjectTaskInstance createItemTask = target.AddTask("CreateItem", null, null);
createItemTask.SetParameter("Include", webRoot + @"\Bin\*.refresh");
createItemTask.AddOutputItem("Include", referenceItemName + "_RefreshFile", null);
// Read the lines out of each .REFRESH file; they should be paths to .DLLs. Put these paths
// into an item list.
ProjectTaskInstance readLinesTask = target.AddTask("ReadLinesFromFile", String.Format(CultureInfo.InvariantCulture, @" '%({0}_RefreshFile.Identity)' != '' ", referenceItemName), null);
readLinesTask.SetParameter("File", String.Format(CultureInfo.InvariantCulture, @"%({0}_RefreshFile.Identity)", referenceItemName));
readLinesTask.AddOutputItem("Lines", referenceItemName + "_ReferenceRelPath", null);
// Take those paths and combine them with the root of the web project to form either
// an absolute path or a path relative to the .SLN file. These paths can be passed
// directly to RAR later.
ProjectTaskInstance combinePathTask = target.AddTask("CombinePath", null, null);
combinePathTask.SetParameter("BasePath", webRoot);
combinePathTask.SetParameter("Paths", String.Format(CultureInfo.InvariantCulture, @"@({0}_ReferenceRelPath)", referenceItemName));
combinePathTask.AddOutputItem("CombinedPaths", referenceItemName, null);
}
/// <summary>
/// Adds an MSBuild task to the specified target
/// </summary>
private static ProjectTaskInstance AddMSBuildTaskInstance(
ProjectTargetInstance target,
string projectPath,
string msbuildTargetName,
string configurationName,
string platformName,
bool specifyProjectToolsVersion)
{
ProjectTaskInstance msbuildTask = target.AddTask("MSBuild", null, null);
msbuildTask.SetParameter("Projects", EscapingUtilities.Escape(projectPath));
if (!string.IsNullOrEmpty(msbuildTargetName))
{
msbuildTask.SetParameter("Targets", msbuildTargetName);
}
string additionalProperties = string.Format(
CultureInfo.InvariantCulture,
"Configuration={0}; Platform={1}; BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)",
EscapingUtilities.Escape(configurationName),
EscapingUtilities.Escape(platformName));
msbuildTask.SetParameter("Properties", additionalProperties);
if (specifyProjectToolsVersion)
{
msbuildTask.SetParameter("ToolsVersion", "$(ProjectToolsVersion)");
}
return msbuildTask;
}
/// <summary>
/// Takes a project in the solution and a base property name, and creates a new property name
/// that can safely be used as an XML element name, and is also unique to that project (by
/// embedding the project's GUID into the property name.
/// </summary>
private static string GenerateSafePropertyName(
ProjectInSolution proj,
string propertyName)
{
// XML element names cannot contain curly braces, so get rid of them from the project guid.
string projectGuid = proj.ProjectGuid.Substring(1, proj.ProjectGuid.Length - 2);
return "Project_" + projectGuid + "_" + propertyName;
}
#endif // FEATURE_ASPNET_COMPILER
/// <summary>
/// Makes a legal item name from a given string by replacing invalid characters with '_'
/// </summary>
private static string MakeIntoSafeItemName(string name)
{
var builder = new StringBuilder(name);
if (name.Length > 0)
{
if (!XmlUtilities.IsValidInitialElementNameCharacter(name[0]))
{
builder[0] = '_';
}
}
for (int i = 1; i < builder.Length; i++)
{
if (!XmlUtilities.IsValidSubsequentElementNameCharacter(builder[i]))
{
builder[i] = '_';
}
}
return builder.ToString();
}
/// <summary>
/// Add a new error/warning/message tag into the given target
/// </summary>
private static ProjectTaskInstance AddErrorWarningMessageInstance(
ProjectTargetInstance target,
string condition,
string elementType,
bool treatAsLiteral,
string textResourceName,
params object[] args)
{
string text = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out string code, out string helpKeyword, textResourceName, args);
if (treatAsLiteral)
{
text = EscapingUtilities.Escape(text);
}
ProjectTaskInstance task = target.AddTask(elementType, condition, null);
task.SetParameter("Text", text);
if ((elementType != XMakeElements.message) && (code != null))
{
task.SetParameter("Code", EscapingUtilities.Escape(code));
}
if ((elementType != XMakeElements.message) && (helpKeyword != null))
{
task.SetParameter("HelpKeyword", EscapingUtilities.Escape(helpKeyword));
}
return task;
}
/// <summary>
/// A helper method for constructing conditions for a solution configuration
/// </summary>
/// <remarks>
/// Sample configuration condition:
/// '$(Configuration)' == 'Release' and '$(Platform)' == 'Any CPU'
/// </remarks>
private static string GetConditionStringForConfiguration(SolutionConfigurationInSolution configuration)
{
return string.Format(
CultureInfo.InvariantCulture,
" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
EscapingUtilities.Escape(configuration.ConfigurationName),
EscapingUtilities.Escape(configuration.PlatformName));
}
/// <summary>
/// Figure out what solution configuration we are going to build, whether or not it actually exists in the solution
/// file.
/// </summary>
private static string DetermineLikelyActiveSolutionConfiguration(SolutionFile solutionFile, IDictionary<string, string> globalProperties)
{
globalProperties.TryGetValue("Configuration", out string activeSolutionConfiguration);
globalProperties.TryGetValue("Platform", out string activeSolutionPlatform);
if (String.IsNullOrEmpty(activeSolutionConfiguration))
{
activeSolutionConfiguration = solutionFile.GetDefaultConfigurationName();
}
if (String.IsNullOrEmpty(activeSolutionPlatform))
{
activeSolutionPlatform = solutionFile.GetDefaultPlatformName();
}
var configurationInSolution = new SolutionConfigurationInSolution(activeSolutionConfiguration, activeSolutionPlatform);
return configurationInSolution.FullName;
}
/// <summary>
/// Returns true if the specified project will build in the currently selected solution configuration.
/// </summary>
internal static bool WouldProjectBuild(SolutionFile solutionFile, string selectedSolutionConfiguration, ProjectInSolution project, ProjectConfigurationInSolution projectConfiguration)
{
// If the solution filter does not contain this project, do not build it.
if (!solutionFile.ProjectShouldBuild(project.RelativePath))
{
return false;
}
if (projectConfiguration == null)
{
if (project.ProjectType == SolutionProjectType.WebProject)
{
// Sometimes web projects won't have the configuration we need (Release typically.) But they should still build if there is
// a solution configuration for it
foreach (SolutionConfigurationInSolution configuration in solutionFile.SolutionConfigurations)
{
if (String.Equals(configuration.FullName, selectedSolutionConfiguration, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
// No configuration, so it can't build.
return false;
}
if (!projectConfiguration.IncludeInBuild)
{
// Not included in the build.
return false;
}
return true;
}
/// <summary>
/// Private method: generates an MSBuild wrapper project for the solution passed in; the MSBuild wrapper
/// project to be generated is the private variable "msbuildProject" and the SolutionFile containing information
/// about the solution is the private variable "solutionFile"
/// </summary>
private ProjectInstance[] Generate()
{
// The Version is not available in the new parser.
if (!_solutionFile.UseNewParser)
{
// Validate against our minimum for upgradable projects
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(
_solutionFile.Version >= SolutionFile.slnFileMinVersion,
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(_solutionFile.FullPath),
"SolutionParseUpgradeNeeded");
}
// This is needed in order to make decisions about tools versions such as whether to put a
// ToolsVersion parameter on <MSBuild> task tags and what MSBuildToolsPath to use when
// scanning child projects for dependency information.
// The knowledge of whether it was explicitly specified is required because otherwise we
// don't know whether we need to pass the ToolsVersion on to the child projects or not.
string wrapperProjectToolsVersion = DetermineWrapperProjectToolsVersion(_toolsVersionOverride, out bool explicitToolsVersionSpecified);
return CreateSolutionProject(wrapperProjectToolsVersion, explicitToolsVersionSpecified);
}
/// <summary>
/// Given a parsed solution, generate a top level traversal project and the metaprojects representing the dependencies for each real project
/// referenced in the solution.
/// </summary>
private ProjectInstance[] CreateSolutionProject(string wrapperProjectToolsVersion, bool explicitToolsVersionSpecified)
{
AddFakeReleaseSolutionConfigurationIfNecessary();
if (_solutionFile.ContainsWebDeploymentProjects)
{
// If there are Web Deployment projects, we need to scan those project files
// and specify the references explicitly.
// Other references are either ProjectReferences (taken care of by MSBuild) or
// explicit manual references in the solution file -- which get parsed out by
// the SolutionParser.
string childProjectToolsVersion = DetermineChildProjectToolsVersion(wrapperProjectToolsVersion);
string fullSolutionConfigurationName = PredictActiveSolutionConfigurationName();
ScanProjectDependencies(childProjectToolsVersion, fullSolutionConfigurationName);
}
// Get a list of all actual projects in the solution
var projectsInOrder = new List<ProjectInSolution>(_solutionFile.ProjectsInOrder.Count);
foreach (ProjectInSolution project in _solutionFile.ProjectsInOrder)
{
if (SolutionFile.IsBuildableProject(project))
{
projectsInOrder.Add(project);
}
}
// Create the list of our generated projects.
var projectInstances = new List<ProjectInstance>(projectsInOrder.Count + 1);
// Create the project instance for the traversal project.
ProjectInstance traversalInstance = CreateTraversalInstance(wrapperProjectToolsVersion, explicitToolsVersionSpecified, projectsInOrder);
// Compute the solution configuration which will be used for this build. We will use it later.
_selectedSolutionConfiguration = String.Format(CultureInfo.InvariantCulture, "{0}|{1}", traversalInstance.GetProperty("Configuration").EvaluatedValue, traversalInstance.GetProperty("Platform").EvaluatedValue);
projectInstances.Add(traversalInstance);
// Now evaluate all of the projects in the solution and handle them appropriately.
EvaluateAndAddProjects(projectsInOrder, projectInstances, traversalInstance, _selectedSolutionConfiguration);
if (_batchProjectTargets)
{
var targetElement = traversalInstance.AddTarget(
SolutionProjectReferenceAllTargets,
string.Empty,
string.Empty,
string.Empty,
null,
string.Empty,
string.Empty,
string.Empty,
string.Empty,
false);
// Add global project reference
AddProjectBuildTask(traversalInstance, null, targetElement, string.Join(";", _targetNames), "@(ProjectReference)", string.Empty, string.Empty);
}
// Special environment variable to allow people to see the in-memory MSBuild project generated
// to represent the SLN.
foreach (ProjectInstance instance in projectInstances)
{
EmitMetaproject(instance.ToProjectRootElement(), instance.FullPath);
}
return projectInstances.ToArray();
}
/// <summary>
/// Examine each project in the solution, add references and targets for it, and create metaprojects if necessary.
/// </summary>
private void EvaluateAndAddProjects(List<ProjectInSolution> projectsInOrder, List<ProjectInstance> projectInstances, ProjectInstance traversalInstance, string selectedSolutionConfiguration)
{
// Now add all of the per-project items, targets and metaprojects.
foreach (ProjectInSolution project in projectsInOrder)
{
project.ProjectConfigurations.TryGetValue(selectedSolutionConfiguration, out ProjectConfigurationInSolution projectConfiguration);
if (!WouldProjectBuild(_solutionFile, selectedSolutionConfiguration, project, projectConfiguration))
{
// Project wouldn't build, so omit it from further processing.
continue;
}
bool canBuildDirectly = CanBuildDirectly(traversalInstance, project, projectConfiguration);
// Add an entry to @(ProjectReference) for the project. This will be either a reference directly to the project, or to the
// metaproject, as appropriate.
AddProjectReference(traversalInstance, traversalInstance, project, projectConfiguration, canBuildDirectly);
// Add the targets to the traversal project for each standard target. These will either invoke the project directly or invoke the
// metaproject, as appropriate
AddTraversalTargetForProject(traversalInstance, project, projectConfiguration, null, "BuildOutput", canBuildDirectly);
AddTraversalTargetForProject(traversalInstance, project, projectConfiguration, "Clean", null, canBuildDirectly);
AddTraversalTargetForProject(traversalInstance, project, projectConfiguration, "Rebuild", "BuildOutput", canBuildDirectly);
AddTraversalTargetForProject(traversalInstance, project, projectConfiguration, "Publish", null, canBuildDirectly);
// Add any other targets specified by the user that were not already added. A target's presence or absence must be determined at the last
// minute because whether traversalInstance.Targets.ContainsKey(i) is true or not can change during the enumeration.
foreach (string targetName in _targetNames.Where(i => !traversalInstance.Targets.ContainsKey(i)))
{
AddTraversalTargetForProject(traversalInstance, project, projectConfiguration, targetName, null, canBuildDirectly);
}
// If we cannot build the project directly, then we need to generate a metaproject for it.
if (!canBuildDirectly)
{
ProjectInstance metaproject = CreateMetaproject(traversalInstance, project, projectConfiguration);
projectInstances.Add(metaproject);
}
}
// Add any other targets specified by the user that were not already added
foreach (string targetName in _targetNames.Where(i => !traversalInstance.Targets.ContainsKey(i)))
{
AddTraversalReferencesTarget(traversalInstance, targetName, null, _batchProjectTargets);
}
}
/// <summary>
/// Adds the standard targets to the traversal project.
/// </summary>
private void AddStandardTraversalTargets(ProjectInstance traversalInstance, List<ProjectInSolution> projectsInOrder)
{
// Add the initial target with some solution configuration validation/information
AddInitialTargets(traversalInstance, projectsInOrder);
// Add the targets to traverse the metaprojects.
AddTraversalReferencesTarget(traversalInstance, null, "CollectedBuildOutput", _batchProjectTargets);
AddTraversalReferencesTarget(traversalInstance, "Clean", null, _batchProjectTargets);
AddTraversalReferencesTarget(traversalInstance, "Rebuild", "CollectedBuildOutput", _batchProjectTargets);
AddTraversalReferencesTarget(traversalInstance, "Publish", null, _batchProjectTargets);
}
/// <summary>
/// Creates the traversal project instance. This has all of the properties against which we can perform evaluations for the remainder of the process.
/// </summary>
private ProjectInstance CreateTraversalInstance(string wrapperProjectToolsVersion, bool explicitToolsVersionSpecified, List<ProjectInSolution> projectsInOrder)
{
// Create the traversal project's root element. We will later instantiate this, and use it for evaluation of conditions on
// the metaprojects.
ProjectRootElement traversalProject = ProjectRootElement.Create();
traversalProject.ToolsVersion = wrapperProjectToolsVersion;
traversalProject.DefaultTargets = "Build";
traversalProject.InitialTargets = "ValidateSolutionConfiguration;ValidateToolsVersions;ValidateProjects";
traversalProject.FullPath = _solutionFile.FullPath + ".metaproj";
// Add default solution configuration/platform names in case the user doesn't specify them on the command line
AddConfigurationPlatformDefaults(traversalProject);
// Add default Venus configuration names (for more details, see comments for this method)
AddVenusConfigurationDefaults(traversalProject);
// Add solution related macros
AddGlobalProperties(traversalProject);
// Add a property group for each solution configuration, each with one XML property containing the
// project configurations in this solution configuration.
foreach (SolutionConfigurationInSolution solutionConfiguration in _solutionFile.SolutionConfigurations)
{
AddPropertyGroupForSolutionConfiguration(traversalProject, solutionConfiguration);
}
// Add our global extensibility points to the project representing the solution:
// Imported at the top: $(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportBefore\*
// Imported at the bottom: $(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportAfter\*
ProjectImportElement importBefore = traversalProject.CreateImportElement(@"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportBefore\*");
importBefore.Condition = @"'$(ImportByWildcardBeforeSolution)' != 'false' and exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportBefore')"; // Avoids wildcard perf problem
ProjectImportElement importAfter = traversalProject.CreateImportElement(@"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportAfter\*");
importAfter.Condition = @"'$(ImportByWildcardBeforeSolution)' != 'false' and exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportAfter')"; // Avoids wildcard perf problem
/* The code below adds the following XML:
- TOP -
<PropertyGroup Condition="'$(ImportDirectorySolutionProps)' != 'false' and '$(DirectorySolutionPropsPath)' == ''">
<_DirectorySolutionPropsFile Condition="'$(_DirectorySolutionPropsFile)' == ''">Directory.Solution.props</_DirectorySolutionPropsFile>
<_DirectorySolutionPropsBasePath Condition="'$(_DirectorySolutionPropsBasePath)' == ''">$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), '$(_DirectorySolutionPropsFile)'))</_DirectorySolutionPropsBasePath>
<DirectorySolutionPropsPath Condition="'$(_DirectorySolutionPropsBasePath)' != '' and '$(_DirectorySolutionPropsFile)' != ''">$([System.IO.Path]::Combine('$(_DirectorySolutionPropsBasePath)', '$(_DirectorySolutionPropsFile)'))</DirectorySolutionPropsPath>
</PropertyGroup>
<Import Project="$(DirectorySolutionPropsPath)" Condition="'$(ImportDirectorySolutionProps)' != 'false' and exists('$(DirectorySolutionPropsPath)')"/>
- BOTTOM -
<PropertyGroup Condition="'$(ImportDirectorySolutionTargets)' != 'false' and '$(DirectorySolutionTargetsPath)' == ''">
<_DirectorySolutionTargetsFile Condition="'$(_DirectorySolutionTargetsFile)' == ''">Directory.Solution.targets</_DirectorySolutionTargetsFile>
<_DirectorySolutionTargetsBasePath Condition="'$(_DirectorySolutionTargetsBasePath)' == ''">$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), '$(_DirectorySolutionTargetsFile)'))</_DirectorySolutionTargetsBasePath>
<DirectorySolutionTargetsPath Condition="'$(_DirectorySolutionTargetsBasePath)' != '' and '$(_DirectorySolutionTargetsFile)' != ''">$([System.IO.Path]::Combine('$(_DirectorySolutionTargetsBasePath)', '$(_DirectorySolutionTargetsFile)'))</DirectorySolutionTargetsPath>
</PropertyGroup>
<Import Project="$(DirectorySolutionTargetsPath)" Condition="'$(ImportDirectorySolutionTargets)' != 'false' and exists('$(DirectorySolutionTargetsPath)')"/>
*/
ProjectPropertyGroupElement directorySolutionPropsPropertyGroup = traversalProject.CreatePropertyGroupElement();
directorySolutionPropsPropertyGroup.Condition = "'$(ImportDirectorySolutionProps)' != 'false' and '$(DirectorySolutionPropsPath)' == ''";
ProjectPropertyElement directorySolutionPropsFileProperty = traversalProject.CreatePropertyElement("_DirectorySolutionPropsFile");
directorySolutionPropsFileProperty.Value = "Directory.Solution.props";
directorySolutionPropsFileProperty.Condition = "'$(_DirectorySolutionPropsFile)' == ''";
ProjectPropertyElement directorySolutionPropsBasePathProperty = traversalProject.CreatePropertyElement("_DirectorySolutionPropsBasePath");
directorySolutionPropsBasePathProperty.Value = "$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), '$(_DirectorySolutionPropsFile)'))";
directorySolutionPropsBasePathProperty.Condition = "'$(_DirectorySolutionPropsBasePath)' == ''";
ProjectPropertyElement directorySolutionPropsPathProperty = traversalProject.CreatePropertyElement("DirectorySolutionPropsPath");
directorySolutionPropsPathProperty.Value = "$([System.IO.Path]::Combine('$(_DirectorySolutionPropsBasePath)', '$(_DirectorySolutionPropsFile)'))";
directorySolutionPropsPathProperty.Condition = "'$(_DirectorySolutionPropsBasePath)' != '' and '$(_DirectorySolutionPropsFile)' != ''";
ProjectImportElement directorySolutionPropsImport = traversalProject.CreateImportElement("$(DirectorySolutionPropsPath)");
directorySolutionPropsImport.Condition = "'$(ImportDirectorySolutionProps)' != 'false' and exists('$(DirectorySolutionPropsPath)')";
ProjectPropertyGroupElement directorySolutionTargetsPropertyGroup = traversalProject.CreatePropertyGroupElement();
directorySolutionTargetsPropertyGroup.Condition = "'$(ImportDirectorySolutionTargets)' != 'false' and '$(DirectorySolutionTargetsPath)' == ''";
ProjectPropertyElement directorySolutionTargetsFileProperty = traversalProject.CreatePropertyElement("_DirectorySolutionTargetsFile");
directorySolutionTargetsFileProperty.Value = "Directory.Solution.targets";
directorySolutionTargetsFileProperty.Condition = "'$(_DirectorySolutionTargetsFile)' == ''";
ProjectPropertyElement directorySolutionTargetsBasePathProperty = traversalProject.CreatePropertyElement("_DirectorySolutionTargetsBasePath");
directorySolutionTargetsBasePathProperty.Value = "$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), '$(_DirectorySolutionTargetsFile)'))";
directorySolutionTargetsBasePathProperty.Condition = "'$(_DirectorySolutionTargetsBasePath)' == ''";
ProjectPropertyElement directorySolutionTargetsPathProperty = traversalProject.CreatePropertyElement("DirectorySolutionTargetsPath");
directorySolutionTargetsPathProperty.Value = "$([System.IO.Path]::Combine('$(_DirectorySolutionTargetsBasePath)', '$(_DirectorySolutionTargetsFile)'))";
directorySolutionTargetsPathProperty.Condition = "'$(_DirectorySolutionTargetsBasePath)' != '' and '$(_DirectorySolutionTargetsFile)' != ''";
ProjectImportElement directorySolutionTargetsImport = traversalProject.CreateImportElement("$(DirectorySolutionTargetsPath)");
directorySolutionTargetsImport.Condition = "'$(ImportDirectorySolutionTargets)' != 'false' and exists('$(DirectorySolutionTargetsPath)')";
// Add our local extensibility points to the project representing the solution
// Imported at the top: before.mysolution.sln.targets
// Imported at the bottom: after.mysolution.sln.targets
(ProjectImportElement importBeforeLocal, ProjectImportElement importAfterLocal) = CreateBeforeAndAfterSolutionImports(traversalProject);
// Put locals second so they can override globals if they want
traversalProject.PrependChild(importBeforeLocal);
traversalProject.PrependChild(directorySolutionPropsImport);
traversalProject.PrependChild(directorySolutionPropsPropertyGroup);
traversalProject.PrependChild(importBefore);
traversalProject.AppendChild(importAfter);
traversalProject.AppendChild(directorySolutionTargetsPropertyGroup);
traversalProject.AppendChild(directorySolutionTargetsImport);
traversalProject.AppendChild(importAfterLocal);
directorySolutionTargetsPropertyGroup.AppendChild(directorySolutionTargetsFileProperty);
directorySolutionTargetsPropertyGroup.AppendChild(directorySolutionTargetsBasePathProperty);
directorySolutionTargetsPropertyGroup.AppendChild(directorySolutionTargetsPathProperty);
directorySolutionPropsPropertyGroup.AppendChild(directorySolutionPropsFileProperty);
directorySolutionPropsPropertyGroup.AppendChild(directorySolutionPropsBasePathProperty);
directorySolutionPropsPropertyGroup.AppendChild(directorySolutionPropsPathProperty);
// These are just dummies necessary to make the evaluation into a project instance succeed when
// any custom imported targets have declarations like BeforeTargets="Build"
// They'll be replaced momentarily with the real ones.
string[] dummyTargetsForEvaluationTime = _defaultTargetNames.Union(_targetNames).ToArray();
foreach (string targetName in dummyTargetsForEvaluationTime)
{
ProjectTargetElement target = traversalProject.CreateTargetElement(targetName);
// Prepend so that any imported target overrides these default ones.
traversalProject.PrependChild(target);
}
// For debugging purposes: some information is lost when evaluating into a project instance,
// so make it possible to see what we have at this point.
string path = traversalProject.FullPath;
string metaprojectPath = _solutionFile.FullPath + ".metaproj.tmp";
EmitMetaproject(traversalProject, metaprojectPath);
traversalProject.FullPath = path;
// Create the instance. From this point forward we can evaluate conditions against the traversal project directly.
var traversalInstance = new ProjectInstance(
traversalProject,
_globalProperties,
explicitToolsVersionSpecified ? wrapperProjectToolsVersion : null,
_loggingService,
_solutionFile.VisualStudioVersion,
new ProjectCollection(),
_sdkResolverService,
_submissionId);
// Traversal meta project entire state has to be serialized as it was generated and hence