-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
SolutionWrapperProject.cs
2316 lines (2028 loc) · 123 KB
/
SolutionWrapperProject.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) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using Microsoft.Build.BuildEngine.Shared;
using Microsoft.Build.Framework;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class is used to generate an MSBuild wrapper project for a solution file or standalone VC project.
/// </summary>
/// <owner>LukaszG, RGoel</owner>
static public class SolutionWrapperProject
{
private const string webProjectOverrideFolder = "_PublishedWebsites";
private const string cacheSolutionConfigurationPropertyName = "_SolutionProjectConfiguration";
private const string cacheToolsVersionPropertyName = "_SolutionProjectToolsVersion";
private const string cacheProjectListName = "_SolutionProjectProjects";
private const string cacheVersionNumber = "_SolutionProjectCacheVersion";
/// <summary>
/// Given the full path to a solution, returns a string containing the v3.5 MSBuild-format
/// wrapper project for that solution.
/// </summary>
/// <param name="solutionPath">Full path to the solution we are wrapping</param>
/// <param name="toolsVersionOverride">May be null. If non-null, contains the ToolsVersion passed in on the command line</param>\
/// <param name="projectBuildEventContext">An event context for logging purposes.</param>
/// <returns></returns>
static public string Generate(string solutionPath, string toolsVersionOverride, BuildEventContext projectBuildEventContext)
{
Project msbuildProject = new Project();
SolutionParser solution = new SolutionParser();
solution.SolutionFile = solutionPath;
solution.ParseSolutionFile();
Generate(solution, msbuildProject, toolsVersionOverride, projectBuildEventContext);
return msbuildProject.Xml;
}
/// <summary>
/// This method generates an XmlDocument representing an MSBuild project file from the list of
/// projects and project dependencies that have been collected from the solution file.
/// </summary>
/// <param name="solution"></param>
/// <param name="msbuildProject"></param>
/// <param name="toolsVersionOverride">Tools Version override (may be null).
/// Any /tv:xxx switch would cause a value here.</param>
/// <returns></returns>
/// <owner>RGoel</owner>
static internal void Generate(SolutionParser solution, Project msbuildProject, string toolsVersionOverride, BuildEventContext projectBuildEventContext)
{
// Validate against our minimum for upgradable projects
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(solution.Version >= SolutionParser.slnFileMinVersion,
"SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(solution.SolutionFile), "SolutionParseUpgradeNeeded");
// Although we only return an XmlDocument back, we need to make decisions about tools versions because
// we have to choose what <UsingTask> tags to put in, whether to put a ToolsVersion parameter
// on <MSBuild> task tags, and what MSBuildToolsPath to use when scanning child projects
// for dependency information.
string wrapperProjectToolsVersion = DetermineWrapperProjectToolsVersion(toolsVersionOverride);
msbuildProject.DefaultTargets = "Build";
msbuildProject.DefaultToolsVersion = wrapperProjectToolsVersion;
Engine parentEngine = msbuildProject.ParentEngine;
string solutionProjectCache = solution.SolutionFile + ".cache";
bool? upToDate = LoadCache(solution, msbuildProject, projectBuildEventContext, wrapperProjectToolsVersion, parentEngine, solutionProjectCache);
if (upToDate == true)
{
// Cache exists, was loaded, and was up to date: we're done
return;
}
// Cache didn't exist or wasn't up to date; generate a new one
Project solutionProject = msbuildProject;
if (upToDate == false)
{
// We have already loaded a cache file we can't use; we need to work in a new project object
solutionProject = CreateNewProject(solution, wrapperProjectToolsVersion, parentEngine, solutionProject);
}
CreateSolutionProject(solution, solutionProject, projectBuildEventContext, wrapperProjectToolsVersion, parentEngine, solutionProjectCache);
if (upToDate == false)
{
// Put the contents of the new project object into the one we were passed
msbuildProject.LoadFromXmlDocument(solutionProject.XmlDocument, projectBuildEventContext, msbuildProject.LoadSettings);
}
// Write a new cache file, hopefully we can use it next time
UpdateCache(parentEngine, msbuildProject, solutionProjectCache, projectBuildEventContext);
}
/// <summary>
/// Attempts to load the solution cache if any into the project provided. Returns null if no attempt was made to load the cache,
/// false if it was loaded but could not be used, or true if it was loaded and can be used.
/// </summary>
private static bool? LoadCache(SolutionParser solution, Project msbuildProject, BuildEventContext projectBuildEventContext, string wrapperProjectToolsVersion, Engine parentEngine, string solutionProjectCache)
{
if (!IsSolutionCacheEnabled() || !File.Exists(solutionProjectCache))
{
return null;
}
try
{
msbuildProject.Load(solutionProjectCache);
string fullSolutionConfigurationName = DetermineLikelyActiveSolutionConfiguration(solution, parentEngine);
bool cacheUpToDate = IsCacheUpToDate(parentEngine, solution.SolutionFile, solution.SolutionFileDirectory, msbuildProject, projectBuildEventContext, fullSolutionConfigurationName, wrapperProjectToolsVersion);
if (cacheUpToDate)
{
// We're done -- use the cache
parentEngine.LoggingServices.LogComment(projectBuildEventContext, "SolutionCacheBeingUsed", solutionProjectCache, fullSolutionConfigurationName, wrapperProjectToolsVersion);
return true;
}
}
catch (Exception ex)
{
if (ExceptionHandling.IsCriticalException(ex))
throw;
// Eat any regular exceptions: we'll just not use the cache
parentEngine.LoggingServices.LogComment(projectBuildEventContext, "SolutionCacheReadError", solutionProjectCache, ex.Message);
}
// Cache exists, but was not useable
return false;
}
/// <summary>
/// Attempt to save a new, updated solution cache file.
/// </summary>
private static void UpdateCache(Engine parentEngine, Project msbuildProject, string solutionProjectCache, BuildEventContext projectBuildEventContext)
{
if (!IsSolutionCacheEnabled())
{
return;
}
try
{
msbuildProject.Save(solutionProjectCache);
}
catch (Exception ex)
{
if (ExceptionHandling.IsCriticalException(ex))
throw;
// Eat any regular exceptions: we'll just not use the cache
parentEngine.LoggingServices.LogComment(projectBuildEventContext, "SolutionCacheWriteError", solutionProjectCache, ex.Message);
}
}
/// <summary>
/// Determine whether solution file caches are enabled. If the environment variable "MSBuildUseNoSolutionCache" is
/// NOT defined, they are enabled.
/// </summary>
private static bool IsSolutionCacheEnabled()
{
bool solutionCacheEnabled = String.IsNullOrEmpty(Environment.GetEnvironmentVariable("MSBuildUseNoSolutionCache"));
return solutionCacheEnabled;
}
/// <summary>
/// Given a cache loaded into a project, determines whether it is up to date with respect to the projects and the solution file listed
/// with it, and was created with the same configuration/platform and tools version values as the ones currently in use.
/// </summary>
private static bool IsCacheUpToDate(Engine parentEngine, string solutionFile, string solutionFileDirectory, Project msbuildProject, BuildEventContext projectBuildEventContext, string fullSolutionConfigurationName, string wrapperProjectToolsVersion)
{
// Check the full solution configuration matches, eg "Debug|AnyCPU"
string cacheSolutionConfigurationName = msbuildProject.GetEvaluatedProperty(cacheSolutionConfigurationPropertyName);
string cacheToolsVersion = msbuildProject.GetEvaluatedProperty(cacheToolsVersionPropertyName);
string cacheVersion = msbuildProject.GetEvaluatedProperty(cacheVersionNumber);
if (cacheSolutionConfigurationName == null || cacheToolsVersion == null)
{
// Unexpected cache format; we can't use it
return false;
}
if (!String.Equals(fullSolutionConfigurationName, cacheSolutionConfigurationName, StringComparison.OrdinalIgnoreCase))
{
parentEngine.LoggingServices.LogComment(projectBuildEventContext, "SolutionCacheNotApplicable", "Configuration", cacheSolutionConfigurationName, fullSolutionConfigurationName);
return false;
}
if (!String.Equals(wrapperProjectToolsVersion, cacheToolsVersion, StringComparison.OrdinalIgnoreCase))
{
parentEngine.LoggingServices.LogComment(projectBuildEventContext, "SolutionCacheNotApplicable", "ToolsVersion", cacheToolsVersion, wrapperProjectToolsVersion);
return false;
}
// We also store the version of MSBuild that wrote the file and verify it's the same as ours: that ensures that we
// don't read possibly incompatible caches.
string thisVersion = Constants.AssemblyVersion;
if (!String.Equals(cacheVersion, thisVersion, StringComparison.OrdinalIgnoreCase))
{
parentEngine.LoggingServices.LogComment(projectBuildEventContext, "SolutionCacheNotApplicableDueToCacheVersion", cacheVersion, thisVersion);
return false;
}
// Finally check timestamps
BuildItemGroup allProjects = msbuildProject.GetEvaluatedItemsByName(cacheProjectListName);
List<string> inputs = new List<string>();
foreach (BuildItem item in allProjects.Items)
{
inputs.Add(item.EvaluatedItemSpec);
}
if (inputs.Count == 0)
{
// There's no inputs; either an old-format cache file, or there's really
// no projects in this solution. In the former case, we need to regenerate.
// In the latter case, we don't really care if we do. So say it's out of date.
return false;
}
// If there are inputs to check, we should also add the solution file, as we need to make sure the
// solution file is up to date with respect to the cache file
// Get the solution file name because the solution file may be something like myDirectory\mysolution.sln
// and since we have already calculated the directory for the solution file, we just need the filename name to
// combine with the directory to get the full path to the solution file without having to call GetFullPath again.
string solutionFileName = Path.GetFileName(solutionFile);
string solutionFileLocation = Path.Combine(solutionFileDirectory, solutionFileName);
inputs.Add(solutionFileLocation);
List<string> outputs = new List<string>();
outputs.Add(msbuildProject.FullFileName);
DependencyAnalysisLogDetail dependencyAnalysisDetail;
bool isAnyOutOfDate = TargetDependencyAnalyzer.IsAnyOutOfDate(out dependencyAnalysisDetail, solutionFileDirectory, inputs, outputs);
if (isAnyOutOfDate)
{
string reason = TargetDependencyAnalyzer.GetFullBuildReason(dependencyAnalysisDetail);
string message = ResourceUtilities.FormatResourceString("SolutionCacheOutOfDate", reason);
parentEngine.LoggingServices.LogCommentFromText(projectBuildEventContext, MessageImportance.Low, message);
return false;
}
else
{
return true;
}
}
/// <summary>
/// Create a new project to construct a solution wrapper cache inside
/// </summary>
private static Project CreateNewProject(SolutionParser solution, string wrapperProjectToolsVersion, Engine parentEngine, Project solutionProject)
{
try
{
solutionProject = new Project(parentEngine, wrapperProjectToolsVersion);
solutionProject.DefaultTargets = "Build";
solutionProject.DefaultToolsVersion = wrapperProjectToolsVersion;
solutionProject.IsLoadedByHost = false;
}
catch (InvalidOperationException)
{
BuildEventFileInfo fileInfo = new BuildEventFileInfo(solution.SolutionFile);
string errorCode;
string helpKeyword;
string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "UnrecognizedToolsVersion", wrapperProjectToolsVersion);
throw new InvalidProjectFileException(solution.SolutionFile, fileInfo.Line, fileInfo.Column, fileInfo.EndLine, fileInfo.EndColumn, message, null, errorCode, helpKeyword);
}
return solutionProject;
}
/// <summary>
/// Given an empty project and a solution, create a new solution project from the solution.
/// </summary>
private static void CreateSolutionProject(SolutionParser solution, Project msbuildProject, BuildEventContext projectBuildEventContext, string wrapperProjectToolsVersion, Engine parentEngine, string solutionProjectCache)
{
// We have to figure out what tools version the children will be built with, because we will
// have to load and scan them to construct the solution wrapper project, and we should use the
// same tools version they'll build with.
string childProjectToolsVersion = DetermineChildProjectToolsVersion(parentEngine, wrapperProjectToolsVersion);
string taskAssembly;
if (String.Equals(msbuildProject.ToolsVersion, "2.0", StringComparison.OrdinalIgnoreCase))
{
taskAssembly = "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
}
else
{
taskAssembly = "Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
}
// Fully qualified class names are more performant
msbuildProject.AddNewUsingTaskFromAssemblyName("Microsoft.Build.Tasks.CreateTemporaryVCProject", taskAssembly);
msbuildProject.AddNewUsingTaskFromAssemblyName("Microsoft.Build.Tasks.ResolveVCProjectOutput", taskAssembly);
AddFakeReleaseSolutionConfigurationIfNecessary(solution);
Dictionary<int, List<ProjectInSolution>> projectsByDependencyLevel = new Dictionary<int, List<ProjectInSolution>>();
string fullSolutionConfigurationName = PredictActiveSolutionConfigurationName(solution, parentEngine);
ScanProjectDependencies(solution, parentEngine, childProjectToolsVersion, fullSolutionConfigurationName, projectBuildEventContext);
ConvertVcToVcDependenciesToReferences(solution, parentEngine, projectBuildEventContext);
AssignDependencyLevels(solution, projectsByDependencyLevel);
AddVirtualReferencesForStaticLibraries(solution);
// Add config, platform and tools version to indicate relevance of cache
AddCacheRelatedProperties(msbuildProject, fullSolutionConfigurationName, wrapperProjectToolsVersion, solution.ProjectsInOrder);
// Add default solution configuration/platform names in case the user doesn't specify them on the command line
AddConfigurationPlatformDefaults(msbuildProject, solution);
// Add default Venus configuration names (for more details, see comments for this method)
AddVenusConfigurationDefaults(msbuildProject);
// Add solution related macros
AddGlobalProperties(msbuildProject, solution);
// Add a property group for each solution configuration, each with one XML property containing the
// project configurations in this solution configuration.
foreach (ConfigurationInSolution solutionConfiguration in solution.SolutionConfigurations)
{
AddPropertyGroupForSolutionConfiguration(msbuildProject, solution, solutionConfiguration);
}
// Add the initial target with some solution configuration validation/information
// Only do it if we actually have any solution configurations...
if (solution.SolutionConfigurations.Count > 0)
{
AddInitialTargets(msbuildProject);
}
// Add a <target> element for each project we have
foreach (ProjectInSolution proj in solution.ProjectsInOrder)
{
string errorMessage;
// is it a solution folder?
if (proj.ProjectType == SolutionProjectType.SolutionFolder)
{
// Don't add any targets. Solution folder "projects" aren't actually projects at all and should be ignored.
}
else if (proj.ProjectType == SolutionProjectType.WebProject)
{
AddTargetForWebProject(msbuildProject, solution, proj, null);
AddTargetForWebProject(msbuildProject, solution, proj, "Clean");
AddTargetForWebProject(msbuildProject, solution, proj, "Rebuild");
AddTargetForWebProject(msbuildProject, solution, proj, "Publish");
}
else if (proj.ProjectType == SolutionProjectType.VCProject)
{
AddTargetForVCProject(msbuildProject, solution, proj, null);
AddTargetForVCProject(msbuildProject, solution, proj, "Clean");
AddTargetForVCProject(msbuildProject, solution, proj, "Rebuild");
AddTargetForVCProject(msbuildProject, solution, proj, "Publish");
}
// is it an MSBuild project?
else if ((proj.ProjectType == SolutionProjectType.ManagedProject) ||
(proj.CanBeMSBuildProjectFile(out errorMessage)))
{
string safeItemNameFromProjectName = MakeIntoSafeItemName(proj.ProjectName);
string targetOutputItemName = string.Format(CultureInfo.InvariantCulture, "{0}BuildOutput", safeItemNameFromProjectName);
AddTargetForManagedProject(msbuildProject, solution, proj, targetOutputItemName, null);
AddTargetForManagedProject(msbuildProject, solution, proj, null, "Clean");
AddTargetForManagedProject(msbuildProject, solution, proj, targetOutputItemName, "Rebuild");
AddTargetForManagedProject(msbuildProject, solution, proj, null, "Publish");
}
else
{
AddTargetForUnknownProjectType(msbuildProject, solution, proj, null, errorMessage);
AddTargetForUnknownProjectType(msbuildProject, solution, proj, "Clean", errorMessage);
AddTargetForUnknownProjectType(msbuildProject, solution, proj, "Rebuild", errorMessage);
AddTargetForUnknownProjectType(msbuildProject, solution, proj, "Publish", errorMessage);
}
}
// Add a target called "Build" that depends on all the other projects. This will be the
// default target that is invoked when the "project" is built.
AddAllDependencyTarget(msbuildProject, "Build", "CollectedBuildOutput", null, projectsByDependencyLevel);
Target cleanTarget = AddAllDependencyTarget(msbuildProject, "Clean", null, "Clean", projectsByDependencyLevel);
// As far as cleaning the solution project cache (if any) goes, we can't do it easily, because by the time we know we
// need to do a clean, we've already loaded the cache. Instead, at the end of a solution clean, we'll delete the cache
// file if any. A solution rebuild won't delete the cache, because probably one would expect a rebuild to leave it behind.
if (IsSolutionCacheEnabled())
{
BuildTask deleteTask = cleanTarget.AddNewTask("Delete");
// Don't use $(MSBuildProjectFile) for safety, in case user has copied and re-purposed this cache file
deleteTask.SetParameterValue("Files", Path.GetFileName(solutionProjectCache));
}
AddAllDependencyTarget(msbuildProject, "Rebuild", "CollectedBuildOutput", "Rebuild", projectsByDependencyLevel);
AddAllDependencyTarget(msbuildProject, "Publish", null, "Publish", projectsByDependencyLevel);
// Special environment variable to allow people to see the in-memory MSBuild project generated
// to represent the SLN.
if (Environment.GetEnvironmentVariable("MSBuildEmitSolution") != null)
{
msbuildProject.Save(solution.SolutionFile + ".proj");
}
}
/// <summary>
/// Adds properties indicating the current solution configuration and tools version into the solution project.
/// Also lists all the projects in the solution, as items.
/// </summary>
private static void AddCacheRelatedProperties(Project msbuildProject, string fullSolutionConfigurationName, string toolsVersion, ArrayList projects)
{
BuildPropertyGroup cachePropertyGroup = msbuildProject.AddNewPropertyGroup(false /* insertAtEndOfProject = false */);
// Store the solution configuration, if it's available (ie., not null because it's invalid)
if (fullSolutionConfigurationName != null)
{
cachePropertyGroup.AddNewProperty(cacheSolutionConfigurationPropertyName, fullSolutionConfigurationName);
}
// Store the tools version, too.
cachePropertyGroup.AddNewProperty(cacheToolsVersionPropertyName, toolsVersion);
// And the engine version, so we don't read caches written by other engines.
cachePropertyGroup.AddNewProperty(cacheVersionNumber, Constants.AssemblyVersion);
// And store a list of all the projects. We can use this next time for timestamp checking.
BuildItemGroup cacheItemGroup = msbuildProject.AddNewItemGroup();
foreach (ProjectInSolution project in projects)
{
// Only add projects that correspond to actual files on disk. Solution folders and web projects correspond to folders, so we don't care about them.
if (project.ProjectType != SolutionProjectType.SolutionFolder && project.ProjectType != SolutionProjectType.WebProject)
{
cacheItemGroup.AddNewItem(cacheProjectListName, EscapingUtilities.Escape(project.RelativePath));
}
}
}
/// <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 (4.0).
/// </summary>
internal static string DetermineWrapperProjectToolsVersion(string toolsVersionOverride)
{
string wrapperProjectToolsVersion = toolsVersionOverride;
if (wrapperProjectToolsVersion == null)
{
wrapperProjectToolsVersion = Constants.defaultSolutionWrapperProjectToolsVersion;
}
return wrapperProjectToolsVersion;
}
/// <summary>
/// We have to know the child projects' tools version in order to know what tools version to use when
/// scanning them for dependencies. If $(ProjectToolsVersion) is defined, we use that; otherwise
/// fall back on the tools version of the solution wrapper project.
/// </summary>
/// <param name="parentEngine"></param>
/// <param name="toolsVersionOverride"></param>
/// <returns></returns>
private static string DetermineChildProjectToolsVersion(Engine parentEngine, string wrapperProjectToolsVersion)
{
BuildProperty property = parentEngine.GlobalProperties["ProjectToolsVersion"];
string childProjectToolsVersion = null;
if (property != null)
{
childProjectToolsVersion = property.Value;
}
if (childProjectToolsVersion == null)
{
childProjectToolsVersion = wrapperProjectToolsVersion;
}
return childProjectToolsVersion;
}
/// <summary>
/// Adds an MSBuild task to the specified target
/// </summary>
/// <param name="target"></param>
/// <param name="projectPath"></param>
/// <param name="msbuildTargetName"></param>
/// <param name="configurationName"></param>
/// <param name="platformName"></param>
/// <returns></returns>
/// <owner>RGoel, LukaszG</owner>
static private BuildTask AddMSBuildTaskElement
(
Target target,
string projectPath,
string msbuildTargetName,
string configurationName,
string platformName,
bool specifyProjectToolsVersion
)
{
BuildTask newTask = target.AddNewTask("MSBuild");
newTask.SetParameterValue("Projects", projectPath, true /* treat as literal */);
if (!string.IsNullOrEmpty(msbuildTargetName))
{
newTask.SetParameterValue("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)
);
newTask.SetParameterValue("Properties", additionalProperties);
if (specifyProjectToolsVersion)
{
newTask.SetParameterValue("ToolsVersion", "$(ProjectToolsVersion)");
newTask.SetParameterValue("UnloadProjectsOnCompletion", "$(UnloadProjectsOnCompletion)");
newTask.SetParameterValue("UseResultsCache", "$(UseResultsCache)");
}
return newTask;
}
/// <summary>
/// Add a target for a project into the XML doc that's being generated.
/// </summary>
/// <param name="msbuildProject"></param>
/// <param name="solution"></param>
/// <param name="proj"></param>
/// <param name="targetOutputItemName">The name of the item exposing this target's outputs. May be null.</param>
/// <param name="subTargetName"></param>
/// <owner>RGoel, LukaszG</owner>
static private void AddTargetForManagedProject
(
Project msbuildProject,
SolutionParser solution,
ProjectInSolution proj,
string targetOutputItemName,
string subTargetName
)
{
string targetName = ProjectInSolution.DisambiguateProjectTargetName(proj.GetUniqueProjectName());
if (!string.IsNullOrEmpty(subTargetName))
{
targetName = targetName + ":" + subTargetName;
}
Target newTarget = msbuildProject.Targets.AddNewTarget(targetName);
newTarget.DependsOnTargets = GetProjectDependencies(proj.ParentSolution, proj, subTargetName);
newTarget.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
if (!String.IsNullOrEmpty(targetOutputItemName))
{
newTarget.TargetElement.SetAttribute("Outputs", string.Format(CultureInfo.InvariantCulture, "@({0})", targetOutputItemName));
}
// Only create build items if we're called with the null subtarget. We're getting called
// a total of four times and only want to create the build items once.
bool createBuildItems = (subTargetName == null);
foreach (ConfigurationInSolution solutionConfiguration in solution.SolutionConfigurations)
{
string condition = GetConditionStringForConfiguration(solutionConfiguration);
// Create the build item group for this configuration if we haven't already
if (solutionConfiguration.ProjectBuildItems == null)
{
solutionConfiguration.ProjectBuildItems = msbuildProject.AddNewItemGroup();
solutionConfiguration.ProjectBuildItems.Condition = condition;
}
ProjectConfigurationInSolution projectConfiguration;
if (proj.ProjectConfigurations.TryGetValue(solutionConfiguration.FullName, out projectConfiguration))
{
if (projectConfiguration.IncludeInBuild)
{
// We want to specify ToolsVersion on the MSBuild task only if the solution
// is building with a non-Whidbey toolset, because the Whidbey MSBuild task
// does not support the ToolsVersion parameter. If the user explicitly requested
// the 2.0 toolset be used to build the solution while specifying some value
// for the ProjectToolsVersion property, then one of the InitialTargets should
// have produced an error before reaching this point.
// PERF: We could emit two <MSBuild> tasks, with a condition on them. But this doubles the size of
// the solution wrapper project, and the cost is too high. The consequence is that when solution wrapper
// projects are emitted to disk (with MSBUILDEMITSOLUION=1) they cannot be reused for tools version v2.0.
bool specifyProjectToolsVersion =
String.Equals(msbuildProject.ToolsVersion, "2.0", StringComparison.OrdinalIgnoreCase) ? false : true;
BuildTask msbuildTask = AddMSBuildTaskElement(newTarget, proj.RelativePath, subTargetName,
projectConfiguration.ConfigurationName, projectConfiguration.PlatformName, specifyProjectToolsVersion);
msbuildTask.Condition = condition;
if (!String.IsNullOrEmpty(targetOutputItemName))
{
msbuildTask.AddOutputItem("TargetOutputs", targetOutputItemName);
}
if (createBuildItems)
{
string baseItemName = "BuildLevel" + proj.DependencyLevel;
BuildItem projectItem = solutionConfiguration.ProjectBuildItems.AddNewItem(baseItemName, proj.RelativePath, true /* treat as literal */);
projectItem.SetMetadata("Configuration", EscapingUtilities.Escape(projectConfiguration.ConfigurationName));
projectItem.SetMetadata("Platform", EscapingUtilities.Escape(projectConfiguration.PlatformName));
}
}
else
{
BuildTask messageTask = AddErrorWarningMessageElement(newTarget, XMakeElements.message, true, "SolutionProjectSkippedForBuilding", proj.ProjectName, solutionConfiguration.FullName);
messageTask.Condition = condition;
if (createBuildItems)
{
string baseItemName = "SkipLevel" + proj.DependencyLevel;
BuildItem projectItem = solutionConfiguration.ProjectBuildItems.AddNewItem(baseItemName, proj.ProjectName, true /* treat as literal */);
}
}
}
else
{
BuildTask warningTask = AddErrorWarningMessageElement(newTarget, XMakeElements.warning, true, "SolutionProjectConfigurationMissing", proj.ProjectName, solutionConfiguration.FullName);
warningTask.Condition = condition;
if (createBuildItems)
{
string baseItemName = "MissingConfigLevel" + proj.DependencyLevel;
BuildItem projectItem = solutionConfiguration.ProjectBuildItems.AddNewItem(baseItemName, proj.ProjectName, true /* treat as literal */);
}
}
}
}
/// <summary>
/// Adds a new ResolveVCProjectOutput task element to the specified target
/// </summary>
/// <param name="target"></param>
/// <param name="solutionPath"></param>
/// <param name="projectPath"></param>
/// <param name="fullConfigurationName"></param>
/// <returns></returns>
/// <owner>LukaszG</owner>
static private BuildTask AddResolveVCProjectOutputTaskElement
(
Target target,
string solutionPath,
string projectPath,
string fullConfigurationName
)
{
BuildTask newTask = target.AddNewTask("ResolveVCProjectOutput");
newTask.SetParameterValue("ProjectReferences", projectPath, true /* treat as literal */);
newTask.SetParameterValue("Configuration", fullConfigurationName, true /* treat as literal */);
newTask.SetParameterValue("SolutionFile", solutionPath, true /* treat as literal */);
// If the user passed in an override stylesheet for this .VCPROJ (by specifying a global
// property called VCBuildOverride), we need to use it to resolve the output path. Override
// stylesheets can be used to change the directory that VC projects get built to.
newTask.SetParameterValue("Override", "$(VCBuildOverride)");
return newTask;
}
/// <summary>
/// Adds MSBuild and ResolveVCProjectOutput tasks to a project target to pre-resolve its project references
/// </summary>
/// <param name="solution"></param>
/// <param name="target"></param>
/// <param name="proj"></param>
/// <param name="solutionConfiguration"></param>
/// <param name="outputReferenceItemName"></param>
/// <param name="outputImportLibraryItemName"></param>
/// <param name="addedReferenceGuids"></param>
/// <owner>LukaszG</owner>
static private void AddResolveProjectReferenceTasks
(
SolutionParser solution,
Project msbuildProject,
Target target,
ProjectInSolution proj,
ConfigurationInSolution solutionConfiguration,
string outputReferenceItemName,
string outputImportLibraryItemName,
out string addedReferenceGuids
)
{
StringBuilder referenceGuids = new StringBuilder();
// Suffix for the reference item name. Since we need to attach additional (different) metadata to every
// reference item, we need to have helper item lists each with only one item
int outputReferenceItemNameSuffix = 0;
// Pre-resolve the MSBuild/VC project references
foreach (string projectReferenceGuid in proj.ProjectReferences)
{
ProjectInSolution referencedProject = (ProjectInSolution)solution.ProjectsByGuid[projectReferenceGuid];
ProjectConfigurationInSolution referencedProjectConfiguration = null;
if ((referencedProject != null) &&
(referencedProject.ProjectConfigurations.TryGetValue(solutionConfiguration.FullName, out referencedProjectConfiguration)) &&
(referencedProjectConfiguration != null))
{
string outputReferenceItemNameWithSuffix = string.Format(CultureInfo.InvariantCulture, "{0}_{1}",
outputReferenceItemName, outputReferenceItemNameSuffix);
bool addCreateItem = false;
string message;
if ((referencedProject.ProjectType == SolutionProjectType.ManagedProject) ||
((referencedProject.ProjectType == SolutionProjectType.Unknown) && (referencedProject.CanBeMSBuildProjectFile(out message))))
{
string condition = GetConditionStringForConfiguration(solutionConfiguration);
bool specifyProjectToolsVersion =
String.Equals(msbuildProject.ToolsVersion, "2.0", StringComparison.OrdinalIgnoreCase) ? false : true;
BuildTask msbuildTask = AddMSBuildTaskElement(target, referencedProject.RelativePath, "GetTargetPath",
referencedProjectConfiguration.ConfigurationName, referencedProjectConfiguration.PlatformName, specifyProjectToolsVersion);
msbuildTask.Condition = condition;
msbuildTask.AddOutputItem("TargetOutputs", outputReferenceItemNameWithSuffix);
if (referenceGuids.Length > 0)
{
referenceGuids.Append(';');
}
referenceGuids.Append(projectReferenceGuid);
addCreateItem = true;
}
else if (referencedProject.ProjectType == SolutionProjectType.VCProject)
{
BuildTask vcbuildTask = null;
try
{
vcbuildTask = AddResolveVCProjectOutputTaskElement(target, Path.Combine(solution.SolutionFileDirectory, Path.GetFileName(solution.SolutionFile)),
referencedProject.AbsolutePath, referencedProjectConfiguration.FullName);
}
catch (Exception e) when (!ExceptionHandling.NotExpectedException(e))
{
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false,
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(solution.SolutionFile),
"SolutionParseInvalidProjectFileName",
referencedProject.RelativePath, e.Message);
}
vcbuildTask.Condition = GetConditionStringForConfiguration(solutionConfiguration);
vcbuildTask.AddOutputItem("ResolvedOutputPaths", outputReferenceItemNameWithSuffix);
if (outputImportLibraryItemName != null)
{
vcbuildTask.AddOutputItem("ResolvedImportLibraryPaths", outputImportLibraryItemName);
}
if (referenceGuids.Length > 0)
{
referenceGuids.Append(';');
}
referenceGuids.Append(projectReferenceGuid);
addCreateItem = true;
}
// Add create item if either of the conditions above was true.
// This merges the one-item item list into the main list, adding the appropriate guid metadata
if (addCreateItem)
{
BuildTask createItemTask = target.AddNewTask("CreateItem");
createItemTask.SetParameterValue("Include", "@(" + outputReferenceItemNameWithSuffix + ")", false /* do not treat as literal */);
createItemTask.SetParameterValue("AdditionalMetadata", "Guid=" + projectReferenceGuid, false /* do not treat as literal */);
createItemTask.AddOutputItem("Include", outputReferenceItemName);
}
outputReferenceItemNameSuffix++;
}
}
addedReferenceGuids = referenceGuids.ToString();
}
/// <summary>
/// Adds tasks that create a temporary VC project file with pre-resolved project references (that is,
/// replaced with file references)
/// </summary>
/// <param name="solution"></param>
/// <param name="target"></param>
/// <param name="proj"></param>
/// <param name="solutionConfiguration"></param>
/// <param name="subTargetName"></param>
/// <param name="projectConfigurationName"></param>
/// <returns>The path to the temporary project file</returns>
/// <owner>LukaszG</owner>
static private string AddCreateTemporaryVCProjectTasks
(
SolutionParser solution,
Project msbuildProject,
Target target,
ProjectInSolution proj,
ConfigurationInSolution solutionConfiguration,
string subTargetName,
string projectConfigurationName
)
{
StringBuilder referenceItemName = new StringBuilder(GenerateSafePropertyName(proj, "References"));
if (!string.IsNullOrEmpty(subTargetName))
{
referenceItemName.Append('_');
referenceItemName.Append(subTargetName);
}
StringBuilder importLibraryItemName = new StringBuilder(GenerateSafePropertyName(proj, "ImportLibraries"));
if (!string.IsNullOrEmpty(subTargetName))
{
importLibraryItemName.Append('_');
importLibraryItemName.Append(subTargetName);
}
string referenceGuidsToRemove;
AddResolveProjectReferenceTasks(solution, msbuildProject, target, proj, solutionConfiguration,
referenceItemName.ToString(), importLibraryItemName.ToString(), out referenceGuidsToRemove);
if (string.IsNullOrEmpty(referenceGuidsToRemove))
referenceGuidsToRemove = string.Empty;
string fullProjectPath = null;
string projectPath = null;
try
{
fullProjectPath = proj.AbsolutePath;
string tmpExtension = string.Format(CultureInfo.InvariantCulture, ".tmp_{0}_{1}.vcproj", solutionConfiguration.ConfigurationName, solutionConfiguration.PlatformName);
projectPath = Path.ChangeExtension(fullProjectPath, tmpExtension);
}
catch (Exception e)
{
if (ExceptionHandling.NotExpectedException(e))
throw;
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false,
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(solution.SolutionFile),
"SolutionParseInvalidProjectFileName",
proj.RelativePath, e.Message);
}
// Create the temporary VC project
BuildTask createVCProjectTask = target.AddNewTask("CreateTemporaryVCProject");
createVCProjectTask.SetParameterValue("ProjectFile", fullProjectPath, true /* treat as literal */);
createVCProjectTask.SetParameterValue("Configuration", projectConfigurationName, true /* treat as literal */);
createVCProjectTask.SetParameterValue("OutputProjectFile", projectPath, true /* treat as literal */);
createVCProjectTask.SetParameterValue("ReferenceGuids", referenceGuidsToRemove, false /* Contains semicolon-separated list. DO NOT treat as literal */);
createVCProjectTask.SetParameterValue("ReferenceAssemblies",
string.Format(CultureInfo.InvariantCulture, "@({0})", referenceItemName.ToString()), false /* DO NOT treat as literal */);
createVCProjectTask.SetParameterValue("ReferenceImportLibraries",
string.Format(CultureInfo.InvariantCulture, "@({0})", importLibraryItemName.ToString()), false /* DO NOT treat as literal */);
createVCProjectTask.Condition = GetConditionStringForConfiguration(solutionConfiguration);
return projectPath;
}
/// <summary>
/// Add a target for a project into the XML doc that's being generated.
/// </summary>
/// <param name="msbuildProject"></param>
/// <param name="solution"></param>
/// <param name="proj"></param>
/// <param name="subTargetName"></param>
/// <owner>LukaszG, RGoel</owner>
static private void AddTargetForVCProject
(
Project msbuildProject,
SolutionParser solution,
ProjectInSolution proj,
string subTargetName
)
{
string targetName = ProjectInSolution.DisambiguateProjectTargetName(proj.GetUniqueProjectName());
if (!string.IsNullOrEmpty(subTargetName))
{
targetName = targetName + ":" + subTargetName;
}
Target newTarget = msbuildProject.Targets.AddNewTarget(targetName);
newTarget.DependsOnTargets = GetProjectDependencies(proj.ParentSolution, proj, subTargetName);
newTarget.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
if (subTargetName == "Publish")
{
// Well, hmmm. The VCBuild doesn't support any kind of
// a "Publish" operation. The best we can really do is offer up a
// message saying so.
AddErrorWarningMessageElement(newTarget, XMakeElements.warning, true, "SolutionVCProjectNoPublish");
// ... and now pretend it's a Build subtarget. This way references to VC projects from projects
// that are about to publish will at least get built.
subTargetName = null;
}
string projectPath = null;
try
{
projectPath = proj.AbsolutePath;
}
catch (Exception e)
{
if (ExceptionHandling.NotExpectedException(e))
throw;
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false,
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(solution.SolutionFile),
"SolutionParseInvalidProjectFileName",
proj.RelativePath, e.Message);
}
foreach (ConfigurationInSolution solutionConfiguration in solution.SolutionConfigurations)
{
string solutionConfigurationCondition = GetConditionStringForConfiguration(solutionConfiguration);
ProjectConfigurationInSolution vcProjectConfiguration = null;
BuildTask newTask = null;
if (proj.ProjectConfigurations.TryGetValue(solutionConfiguration.FullName, out vcProjectConfiguration))
{
if (vcProjectConfiguration.IncludeInBuild)
{
// Create a temporary VC project with references to MSBuild projects replaced with file references.
if (proj.ProjectReferences.Count > 0)
{
projectPath = AddCreateTemporaryVCProjectTasks(solution, msbuildProject, newTarget, proj,
solutionConfiguration, subTargetName,
vcProjectConfiguration.FullName);
}
newTask = VCWrapperProject.AddVCBuildTaskElement(
msbuildProject,
newTarget,
EscapingUtilities.Escape(Path.Combine(solution.SolutionFileDirectory, Path.GetFileName(solution.SolutionFile))),
projectPath, subTargetName,
null, EscapingUtilities.Escape(vcProjectConfiguration.FullName));
// Delete the temporary VC project
if (proj.ProjectReferences.Count > 0)
{
BuildTask deleteTask = newTarget.AddNewTask("Delete");
deleteTask.SetParameterValue("Files", projectPath, true /* treat as literal */);
deleteTask.Condition = solutionConfigurationCondition;
}
}
else
{
newTask = AddErrorWarningMessageElement(newTarget, XMakeElements.message, true, "SolutionProjectSkippedForBuilding", proj.ProjectName, solutionConfiguration.FullName);
}
}
else
{
newTask = AddErrorWarningMessageElement(newTarget, XMakeElements.warning, true, "SolutionProjectConfigurationMissing", proj.ProjectName, solutionConfiguration.FullName);
}
if (newTask != null)
{
newTask.Condition = solutionConfigurationCondition;
}
}
}
/// <summary>
/// Add a target to the project called "GetFrameworkPathAndRedistList". This target calls the
/// GetFrameworkPath task and then CreateItem to populate @(_CombinedTargetFrameworkDirectoriesItem) and
/// @(InstalledAssemblyTables), so that we can pass these into the ResolveAssemblyReference task
/// when building web projects.
/// </summary>
/// <param name="msbuildProject"></param>
/// <owner>RGoel</owner>
static private void AddTargetForGetFrameworkPathAndRedistList
(
Project msbuildProject
)
{
// See if there's already a target called "GetFrameworkPathAndRedistList" in this project.
// If so, no need to do anything.
foreach (Target target in msbuildProject.Targets)