-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
SolutionFile.cs
1666 lines (1481 loc) · 79.3 KB
/
SolutionFile.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.Generic;
using System.Xml;
using System.IO;
using System.Text;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Text.Json;
using System.Text.RegularExpressions;
using ErrorUtilities = Microsoft.Build.Shared.ErrorUtilities;
using VisualStudioConstants = Microsoft.Build.Shared.VisualStudioConstants;
using ProjectFileErrorUtilities = Microsoft.Build.Shared.ProjectFileErrorUtilities;
using BuildEventFileInfo = Microsoft.Build.Shared.BuildEventFileInfo;
using ResourceUtilities = Microsoft.Build.Shared.ResourceUtilities;
using ExceptionUtilities = Microsoft.Build.Shared.ExceptionHandling;
using System.Collections.ObjectModel;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
#nullable disable
namespace Microsoft.Build.Construction
{
/// <remarks>
/// This class contains the functionality to parse a solution file and return a corresponding
/// MSBuild project file containing the projects and dependencies defined in the solution.
/// </remarks>
public sealed class SolutionFile
{
#region Solution specific constants
// An example of a project line looks like this:
// Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClassLibrary1", "ClassLibrary1\ClassLibrary1.csproj", "{05A5AD00-71B5-4612-AF2F-9EA9121C4111}"
private static readonly Lazy<Regex> s_crackProjectLine = new Lazy<Regex>(
() => new Regex
(
"^" // Beginning of line
+ "Project\\(\"(?<PROJECTTYPEGUID>.*)\"\\)"
+ "\\s*=\\s*" // Any amount of whitespace plus "=" plus any amount of whitespace
+ "\"(?<PROJECTNAME>.*)\""
+ "\\s*,\\s*" // Any amount of whitespace plus "," plus any amount of whitespace
+ "\"(?<RELATIVEPATH>.*)\""
+ "\\s*,\\s*" // Any amount of whitespace plus "," plus any amount of whitespace
+ "\"(?<PROJECTGUID>.*)\""
+ "$", // End-of-line
RegexOptions.Compiled
)
);
// An example of a property line looks like this:
// AspNetCompiler.VirtualPath = "/webprecompile"
// Because website projects now include the target framework moniker as
// one of their properties, <PROPERTYVALUE> may now have '=' in it.
private static readonly Lazy<Regex> s_crackPropertyLine = new Lazy<Regex>(
() => new Regex
(
"^" // Beginning of line
+ "(?<PROPERTYNAME>[^=]*)"
+ "\\s*=\\s*" // Any amount of whitespace plus "=" plus any amount of whitespace
+ "(?<PROPERTYVALUE>.*)"
+ "$", // End-of-line
RegexOptions.Compiled
)
);
internal const int slnFileMinUpgradableVersion = 7; // Minimum version for MSBuild to give a nice message
internal const int slnFileMinVersion = 9; // Minimum version for MSBuild to actually do anything useful
internal const int slnFileMaxVersion = VisualStudioConstants.CurrentVisualStudioSolutionFileVersion;
private const string vbProjectGuid = "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}";
private const string csProjectGuid = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}";
private const string cpsProjectGuid = "{13B669BE-BB05-4DDF-9536-439F39A36129}";
private const string cpsCsProjectGuid = "{9A19103F-16F7-4668-BE54-9A1E7A4F7556}";
private const string cpsVbProjectGuid = "{778DAE3C-4631-46EA-AA77-85C1314464D9}";
private const string cpsFsProjectGuid = "{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}";
private const string vjProjectGuid = "{E6FDF86B-F3D1-11D4-8576-0002A516ECE8}";
private const string vcProjectGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
private const string fsProjectGuid = "{F2A71F9B-5D33-465A-A702-920D77279786}";
private const string dbProjectGuid = "{C8D11400-126E-41CD-887F-60BD40844F9E}";
private const string wdProjectGuid = "{2CFEAB61-6A3B-4EB8-B523-560B4BEEF521}";
private const string synProjectGuid = "{BBD0F5D1-1CC4-42FD-BA4C-A96779C64378}";
private const string webProjectGuid = "{E24C65DC-7377-472B-9ABA-BC803B73C61A}";
private const string solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}";
private const string sharedProjectGuid = "{D954291E-2A0B-460D-934E-DC6B0785DB48}";
private const char CommentStartChar = '#';
#endregion
#region Member data
private string _solutionFile; // Could be absolute or relative path to the .SLN file.
private string _solutionFilterFile; // Could be absolute or relative path to the .SLNF file.
private HashSet<string> _solutionFilter; // The project files to include in loading the solution.
private bool _parsingForConversionOnly; // Are we parsing this solution to get project reference data during
// conversion, or in preparation for actually building the solution?
// The list of projects in this SLN, keyed by the project GUID.
private Dictionary<string, ProjectInSolution> _projects;
// The list of projects in the SLN, in order of their appearance in the SLN.
private List<ProjectInSolution> _projectsInOrder;
// The list of solution configurations in the solution
private List<SolutionConfigurationInSolution> _solutionConfigurations;
// cached default configuration name for GetDefaultConfigurationName
private string _defaultConfigurationName;
// cached default platform name for GetDefaultPlatformName
private string _defaultPlatformName;
// VisualStudionVersion specified in Dev12+ solutions
private Version _currentVisualStudioVersion;
private int _currentLineNumber;
// TODO: Unify to NativeMethodsShared.OSUsesCaseSensitive paths
// when possible.
private static StringComparer _pathComparer = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
? StringComparer.Ordinal
: StringComparer.OrdinalIgnoreCase;
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
internal SolutionFile()
{
}
#endregion
#region Properties
/// <summary>
/// This property returns the list of warnings that were generated during solution parsing
/// </summary>
internal List<string> SolutionParserWarnings { get; } = new List<string>();
/// <summary>
/// This property returns the list of comments that were generated during the solution parsing
/// </summary>
internal List<string> SolutionParserComments { get; } = new List<string>();
/// <summary>
/// This property returns the list of error codes for warnings/errors that were generated during solution parsing.
/// </summary>
internal List<string> SolutionParserErrorCodes { get; } = new List<string>();
/// <summary>
/// Returns the actual major version of the parsed solution file
/// </summary>
internal int Version { get; private set; }
/// <summary>
/// Returns Visual Studio major version
/// </summary>
internal int VisualStudioVersion
{
get
{
if (_currentVisualStudioVersion != null)
{
return _currentVisualStudioVersion.Major;
}
else
{
return Version - 1;
}
}
}
/// <summary>
/// Returns true if the solution contains any web projects
/// </summary>
internal bool ContainsWebProjects { get; private set; }
/// <summary>
/// Returns true if the solution contains any .wdproj projects. Used to determine
/// whether we need to load up any projects to examine dependencies.
/// </summary>
internal bool ContainsWebDeploymentProjects { get; private set; }
/// <summary>
/// All projects in this solution, in the order they appeared in the solution file
/// </summary>
public IReadOnlyList<ProjectInSolution> ProjectsInOrder => _projectsInOrder.AsReadOnly();
/// <summary>
/// The collection of projects in this solution, accessible by their guids as a
/// string in "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" form
/// </summary>
public IReadOnlyDictionary<string, ProjectInSolution> ProjectsByGuid => new ReadOnlyDictionary<string, ProjectInSolution>(_projects);
/// <summary>
/// This is the read/write accessor for the solution file which we will parse. This
/// must be set before calling any other methods on this class.
/// </summary>
/// <value></value>
internal string FullPath
{
get => _solutionFile;
set
{
// Should already be canonicalized to a full path
ErrorUtilities.VerifyThrowInternalRooted(value);
// To reduce code duplication, this should be
// if (FileUtilities.IsSolutionFilterFilename(value))
// But that's in Microsoft.Build.Framework and this codepath
// is called from old versions of NuGet that can't resolve
// Framework (see https://github.com/dotnet/msbuild/issues/5313).
if (value.EndsWith(".slnf", StringComparison.OrdinalIgnoreCase))
{
ParseSolutionFilter(value);
}
else
{
_solutionFile = value;
_solutionFilter = null;
SolutionFileDirectory = Path.GetDirectoryName(_solutionFile);
}
}
}
internal string SolutionFileDirectory
{
get;
// This setter is only used by the unit tests
set;
}
/// <summary>
/// For unit-testing only.
/// </summary>
/// <value></value>
internal StreamReader SolutionReader { get; set; }
/// <summary>
/// The list of all full solution configurations (configuration + platform) in this solution
/// </summary>
public IReadOnlyList<SolutionConfigurationInSolution> SolutionConfigurations => _solutionConfigurations.AsReadOnly();
#endregion
#region Methods
internal bool ProjectShouldBuild(string projectFile)
{
return _solutionFilter?.Contains(FileUtilities.FixFilePath(projectFile)) != false;
}
/// <summary>
/// This method takes a path to a solution file, parses the projects and project dependencies
/// in the solution file, and creates internal data structures representing the projects within
/// the SLN.
/// </summary>
public static SolutionFile Parse(string solutionFile)
{
var parser = new SolutionFile { FullPath = solutionFile };
parser.ParseSolutionFile();
return parser;
}
/// <summary>
/// Returns "true" if it's a project that's expected to be buildable, or false if it's
/// not (e.g. a solution folder)
/// </summary>
/// <param name="project">The project in the solution</param>
/// <returns>Whether the project is expected to be buildable</returns>
internal static bool IsBuildableProject(ProjectInSolution project)
{
return project.ProjectType != SolutionProjectType.SolutionFolder && project.ProjectConfigurations.Count > 0;
}
/// <summary>
/// Given a solution file, parses the header and returns the major version numbers of the solution file
/// and the visual studio.
/// Throws InvalidProjectFileException if the solution header is invalid, or if the version is less than
/// our minimum version.
/// </summary>
internal static void GetSolutionFileAndVisualStudioMajorVersions(string solutionFile, out int solutionVersion, out int visualStudioMajorVersion)
{
ErrorUtilities.VerifyThrow(!String.IsNullOrEmpty(solutionFile), "null solution file passed to GetSolutionFileMajorVersion!");
ErrorUtilities.VerifyThrowInternalRooted(solutionFile);
const string slnFileHeaderNoVersion = "Microsoft Visual Studio Solution File, Format Version ";
const string slnFileVSVLinePrefix = "VisualStudioVersion";
FileStream fileStream = null;
StreamReader reader = null;
bool validVersionFound = false;
solutionVersion = 0;
visualStudioMajorVersion = 0;
try
{
// Open the file
fileStream = File.OpenRead(solutionFile);
reader = new StreamReader(fileStream, Encoding.GetEncoding(0)); // HIGHCHAR: If solution files have no byte-order marks, then assume ANSI rather than ASCII.
// Read first 4 lines of the solution file.
// The header is expected to be in line 1 or 2
// VisualStudioVersion is expected to be in line 3 or 4.
for (int i = 0; i < 4; i++)
{
string line = reader.ReadLine();
if (line == null)
{
break;
}
if (line.Trim().StartsWith(slnFileHeaderNoVersion, StringComparison.Ordinal))
{
// Found it. Validate the version.
string fileVersionFromHeader = line.Substring(slnFileHeaderNoVersion.Length);
if (!System.Version.TryParse(fileVersionFromHeader, out Version version))
{
ProjectFileErrorUtilities.ThrowInvalidProjectFile
(
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(solutionFile),
"SolutionParseVersionMismatchError",
slnFileMinUpgradableVersion,
slnFileMaxVersion
);
}
solutionVersion = version.Major;
// Validate against our min & max
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile
(
solutionVersion >= slnFileMinUpgradableVersion,
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(solutionFile),
"SolutionParseVersionMismatchError",
slnFileMinUpgradableVersion,
slnFileMaxVersion
);
validVersionFound = true;
}
else if (line.Trim().StartsWith(slnFileVSVLinePrefix, StringComparison.Ordinal))
{
Version visualStudioVersion = ParseVisualStudioVersion(line);
if (visualStudioVersion != null)
{
visualStudioMajorVersion = visualStudioVersion.Major;
}
}
}
}
finally
{
fileStream?.Dispose();
reader?.Dispose();
}
if (validVersionFound)
{
return;
}
// Didn't find the header in lines 1-4, so the solution file is invalid.
ProjectFileErrorUtilities.ThrowInvalidProjectFile
(
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(solutionFile),
"SolutionParseNoHeaderError"
);
}
private void ParseSolutionFilter(string solutionFilterFile)
{
_solutionFilterFile = solutionFilterFile;
try
{
_solutionFile = ParseSolutionFromSolutionFilter(solutionFilterFile, out JsonElement solution);
if (!FileSystems.Default.FileExists(_solutionFile))
{
ProjectFileErrorUtilities.ThrowInvalidProjectFile
(
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(_solutionFile),
"SolutionFilterMissingSolutionError",
solutionFilterFile,
_solutionFile
);
}
SolutionFileDirectory = Path.GetDirectoryName(_solutionFile);
_solutionFilter = new HashSet<string>(_pathComparer);
foreach (JsonElement project in solution.GetProperty("projects").EnumerateArray())
{
_solutionFilter.Add(FileUtilities.FixFilePath(project.GetString()));
}
}
catch (Exception e) when (e is JsonException || e is KeyNotFoundException || e is InvalidOperationException)
{
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile
(
false, /* Just throw the exception */
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(solutionFilterFile),
e,
"SolutionFilterJsonParsingError",
solutionFilterFile
);
}
}
internal static string ParseSolutionFromSolutionFilter(string solutionFilterFile, out JsonElement solution)
{
try
{
// This is to align MSBuild with what VS permits in loading solution filter files. These are not in them by default but can be added manually.
JsonDocumentOptions options = new JsonDocumentOptions() { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip };
JsonDocument text = JsonDocument.Parse(File.ReadAllText(solutionFilterFile), options);
solution = text.RootElement.GetProperty("solution");
return FileUtilities.GetFullPath(solution.GetProperty("path").GetString(), Path.GetDirectoryName(solutionFilterFile));
}
catch (Exception e) when (e is JsonException || e is KeyNotFoundException || e is InvalidOperationException)
{
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile
(
false, /* Just throw the exception */
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(solutionFilterFile),
e,
"SolutionFilterJsonParsingError",
solutionFilterFile
);
}
solution = new JsonElement();
return string.Empty;
}
/// <summary>
/// Adds a configuration to this solution
/// </summary>
internal void AddSolutionConfiguration(string configurationName, string platformName)
{
_solutionConfigurations.Add(new SolutionConfigurationInSolution(configurationName, platformName));
}
/// <summary>
/// Reads a line from the StreamReader, trimming leading and trailing whitespace.
/// </summary>
/// <returns></returns>
private string ReadLine()
{
ErrorUtilities.VerifyThrow(SolutionReader != null, "ParseFileHeader(): reader is null!");
string line = SolutionReader.ReadLine();
_currentLineNumber++;
return line?.Trim();
}
/// <summary>
/// This method takes a path to a solution file, parses the projects and project dependencies
/// in the solution file, and creates internal data structures representing the projects within
/// the SLN. Used for conversion, which means it allows situations that we refuse to actually build.
/// </summary>
internal void ParseSolutionFileForConversion()
{
_parsingForConversionOnly = true;
ParseSolutionFile();
}
/// <summary>
/// This method takes a path to a solution file, parses the projects and project dependencies
/// in the solution file, and creates internal data structures representing the projects within
/// the SLN.
/// </summary>
internal void ParseSolutionFile()
{
ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(_solutionFile), "ParseSolutionFile() got a null solution file!");
ErrorUtilities.VerifyThrowInternalRooted(_solutionFile);
FileStream fileStream = null;
SolutionReader = null;
try
{
// Open the file
fileStream = File.OpenRead(_solutionFile);
SolutionReader = new StreamReader(fileStream, Encoding.GetEncoding(0)); // HIGHCHAR: If solution files have no byte-order marks, then assume ANSI rather than ASCII.
ParseSolution();
}
catch (Exception e) when (ExceptionUtilities.IsIoRelatedException(e))
{
ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(_solutionFile), "InvalidProjectFile", e.Message);
}
finally
{
fileStream?.Dispose();
SolutionReader?.Dispose();
}
}
/// <summary>
/// Parses the SLN file represented by the StreamReader in this.reader, and populates internal
/// data structures based on the SLN file contents.
/// </summary>
internal void ParseSolution()
{
_projects = new Dictionary<string, ProjectInSolution>(StringComparer.OrdinalIgnoreCase);
_projectsInOrder = new List<ProjectInSolution>();
ContainsWebProjects = false;
Version = 0;
_currentLineNumber = 0;
_solutionConfigurations = new List<SolutionConfigurationInSolution>();
_defaultConfigurationName = null;
_defaultPlatformName = null;
// the raw list of project configurations in solution configurations, to be processed after it's fully read in.
Dictionary<string, string> rawProjectConfigurationsEntries = null;
ParseFileHeader();
string str;
while ((str = ReadLine()) != null)
{
if (str.StartsWith("Project(", StringComparison.Ordinal))
{
ParseProject(str);
}
else if (str.StartsWith("GlobalSection(NestedProjects)", StringComparison.Ordinal))
{
ParseNestedProjects();
}
else if (str.StartsWith("GlobalSection(SolutionConfigurationPlatforms)", StringComparison.Ordinal))
{
ParseSolutionConfigurations();
}
else if (str.StartsWith("GlobalSection(ProjectConfigurationPlatforms)", StringComparison.Ordinal))
{
rawProjectConfigurationsEntries = ParseProjectConfigurations();
}
else if (str.StartsWith("VisualStudioVersion", StringComparison.Ordinal))
{
_currentVisualStudioVersion = ParseVisualStudioVersion(str);
}
else
{
// No other section types to process at this point, so just ignore the line
// and continue.
}
}
if (_solutionFilter != null)
{
HashSet<string> projectPaths = new HashSet<string>(_projectsInOrder.Count, _pathComparer);
foreach (ProjectInSolution project in _projectsInOrder)
{
projectPaths.Add(FileUtilities.FixFilePath(project.RelativePath));
}
foreach (string project in _solutionFilter)
{
if (!projectPaths.Contains(project))
{
ProjectFileErrorUtilities.ThrowInvalidProjectFile
(
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(FileUtilities.GetFullPath(project, Path.GetDirectoryName(_solutionFile))),
"SolutionFilterFilterContainsProjectNotInSolution",
_solutionFilterFile,
project,
_solutionFile
);
}
}
}
if (rawProjectConfigurationsEntries != null)
{
ProcessProjectConfigurationSection(rawProjectConfigurationsEntries);
}
// Cache the unique name of each project, and check that we don't have any duplicates.
var projectsByUniqueName = new Dictionary<string, ProjectInSolution>(StringComparer.OrdinalIgnoreCase);
var projectsByOriginalName = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (ProjectInSolution proj in _projectsInOrder)
{
// Find the unique name for the project. This method also caches the unique name,
// so it doesn't have to be recomputed later.
string uniqueName = proj.GetUniqueProjectName();
if (proj.ProjectType == SolutionProjectType.WebProject)
{
// Examine port information and determine if we need to disambiguate similarly-named projects with different ports.
if (Uri.TryCreate(proj.RelativePath, UriKind.Absolute, out Uri uri))
{
if (!uri.IsDefaultPort)
{
// If there are no other projects with the same name as this one, then we will keep this project's unique name, otherwise
// we will create a new unique name with the port added.
foreach (ProjectInSolution otherProj in _projectsInOrder)
{
if (ReferenceEquals(proj, otherProj))
{
continue;
}
if (String.Equals(otherProj.ProjectName, proj.ProjectName, StringComparison.OrdinalIgnoreCase))
{
uniqueName = $"{uniqueName}:{uri.Port}";
proj.UpdateUniqueProjectName(uniqueName);
break;
}
}
}
}
}
// Detect collision caused by unique name's normalization
if (projectsByUniqueName.TryGetValue(uniqueName, out ProjectInSolution project))
{
// Did normalization occur in the current project?
if (uniqueName != proj.ProjectName)
{
// Generates a new unique name
string tempUniqueName = $"{uniqueName}_{proj.GetProjectGuidWithoutCurlyBrackets()}";
proj.UpdateUniqueProjectName(tempUniqueName);
uniqueName = tempUniqueName;
}
// Did normalization occur in a previous project?
else if (uniqueName != project.ProjectName)
{
// Generates a new unique name
string tempUniqueName = $"{uniqueName}_{project.GetProjectGuidWithoutCurlyBrackets()}";
project.UpdateUniqueProjectName(tempUniqueName);
projectsByUniqueName.Remove(uniqueName);
projectsByUniqueName.Add(tempUniqueName, project);
}
}
bool uniqueNameExists = projectsByUniqueName.ContainsKey(uniqueName);
// Add the unique name (if it does not exist) to the hash table
if (!uniqueNameExists)
{
projectsByUniqueName.Add(uniqueName, proj);
}
bool didntAlreadyExist = !uniqueNameExists && projectsByOriginalName.Add(proj.GetOriginalProjectName());
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(
didntAlreadyExist,
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(FullPath),
"SolutionParseDuplicateProject",
uniqueNameExists ? uniqueName : proj.ProjectName);
}
} // ParseSolutionFile()
/// <summary>
/// This method searches the first two lines of the solution file opened by the specified
/// StreamReader for the solution file header. An exception is thrown if it is not found.
///
/// The solution file header looks like this:
///
/// Microsoft Visual Studio Solution File, Format Version 9.00
///
/// </summary>
private void ParseFileHeader()
{
ErrorUtilities.VerifyThrow(SolutionReader != null, "ParseFileHeader(): reader is null!");
const string slnFileHeaderNoVersion = "Microsoft Visual Studio Solution File, Format Version ";
// Read the file header. This can be on either of the first two lines.
for (int i = 1; i <= 2; i++)
{
string str = ReadLine();
if (str == null)
{
break;
}
if (str.StartsWith(slnFileHeaderNoVersion, StringComparison.Ordinal))
{
// Found it. Validate the version.
ValidateSolutionFileVersion(str.Substring(slnFileHeaderNoVersion.Length));
return;
}
}
// Didn't find the header on either the first or second line, so the solution file
// is invalid.
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, "SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(FullPath), "SolutionParseNoHeaderError");
}
/// <summary>
/// This method parses the Visual Studio version in Dev 12 solution files
/// The version line looks like this:
///
/// VisualStudioVersion = 12.0.20311.0 VSPRO_PLATFORM
///
/// If such a line is found, the version is stored in this.currentVisualStudioVersion
/// </summary>
private static Version ParseVisualStudioVersion(string str)
{
Version currentVisualStudioVersion = null;
char[] delimiterChars = { ' ', '=' };
string[] words = str.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
if (words.Length >= 2)
{
string versionStr = words[1];
if (!System.Version.TryParse(versionStr, out currentVisualStudioVersion))
{
currentVisualStudioVersion = null;
}
}
return currentVisualStudioVersion;
}
/// <summary>
/// This method extracts the whole part of the version number from the specified line
/// containing the solution file format header, and throws an exception if the version number
/// is outside of the valid range.
///
/// The solution file header looks like this:
///
/// Microsoft Visual Studio Solution File, Format Version 9.00
///
/// </summary>
/// <param name="versionString"></param>
private void ValidateSolutionFileVersion(string versionString)
{
ErrorUtilities.VerifyThrow(versionString != null, "ValidateSolutionFileVersion() got a null line!");
if (!System.Version.TryParse(versionString, out Version version))
{
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, "SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(FullPath, _currentLineNumber, 0), "SolutionParseVersionMismatchError",
slnFileMinUpgradableVersion, slnFileMaxVersion);
}
Version = version.Major;
// Validate against our min & max
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(
Version >= slnFileMinUpgradableVersion,
"SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(FullPath, _currentLineNumber, 0),
"SolutionParseVersionMismatchError",
slnFileMinUpgradableVersion, slnFileMaxVersion);
// If the solution file version is greater than the maximum one we will create a comment rather than warn
// as users such as blend opening a dev10 project cannot do anything about it.
if (Version > slnFileMaxVersion)
{
SolutionParserComments.Add(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("UnrecognizedSolutionComment", Version));
}
}
/// <summary>
///
/// This method processes a "Project" section in the solution file opened by the specified
/// StreamReader, and returns a populated ProjectInSolution instance, if successful.
/// An exception is thrown if the solution file is invalid.
///
/// The format of the parts of a Project section that we care about is as follows:
///
/// Project("{Project type GUID}") = "Project name", "Relative path to project file", "{Project GUID}"
/// ProjectSection(ProjectDependencies) = postProject
/// {Parent project unique name} = {Parent project unique name}
/// ...
/// EndProjectSection
/// EndProject
///
/// </summary>
private void ParseProject(string firstLine)
{
ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(firstLine), "ParseProject() got a null firstLine!");
ErrorUtilities.VerifyThrow(SolutionReader != null, "ParseProject() got a null reader!");
var proj = new ProjectInSolution(this);
// Extract the important information from the first line.
ParseFirstProjectLine(firstLine, proj);
// Search for project dependencies. Keeping reading lines until we either 1.) reach
// the end of the file, 2.) see "ProjectSection(ProjectDependencies)" at the beginning
// of the line, or 3.) see "EndProject" at the beginning of the line.
string line;
while ((line = ReadLine()) != null)
{
// If we see an "EndProject", well ... that's the end of this project!
if (line == "EndProject")
{
break;
}
else if (line.StartsWith("ProjectSection(ProjectDependencies)", StringComparison.Ordinal))
{
// We have a ProjectDependencies section. Each subsequent line should identify
// a dependency.
line = ReadLine();
while ((line?.StartsWith("EndProjectSection", StringComparison.Ordinal) == false))
{
// This should be a dependency. The GUID identifying the parent project should
// be both the property name and the property value.
Match match = s_crackPropertyLine.Value.Match(line);
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(match.Success, "SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(FullPath, _currentLineNumber, 0), "SolutionParseProjectDepGuidError", proj.ProjectName);
string referenceGuid = match.Groups["PROPERTYNAME"].Value.Trim();
proj.AddDependency(referenceGuid);
line = ReadLine();
}
}
else if (line.StartsWith("ProjectSection(WebsiteProperties)", StringComparison.Ordinal))
{
// We have a WebsiteProperties section. This section is present only in Venus
// projects, and contains properties that we'll need in order to call the
// AspNetCompiler task.
line = ReadLine();
while ((line?.StartsWith("EndProjectSection", StringComparison.Ordinal) == false))
{
Match match = s_crackPropertyLine.Value.Match(line);
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(match.Success, "SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(FullPath, _currentLineNumber, 0), "SolutionParseWebProjectPropertiesError", proj.ProjectName);
string propertyName = match.Groups["PROPERTYNAME"].Value.Trim();
string propertyValue = match.Groups["PROPERTYVALUE"].Value.Trim();
ParseAspNetCompilerProperty(proj, propertyName, propertyValue);
line = ReadLine();
}
}
else if (line.StartsWith("Project(", StringComparison.Ordinal))
{
// Another Project spotted instead of EndProject for the current one - solution file is malformed
string warning = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out _, out _, "Shared.InvalidProjectFile",
_solutionFile, proj.ProjectName);
SolutionParserWarnings.Add(warning);
// The line with new project is already read and we can't go one line back - we have no choice but to recursively parse spotted project
ParseProject(line);
// We're not waiting for the EndProject for malformed project, so we carry on
break;
}
}
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(line != null, "SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(FullPath), "SolutionParseProjectEofError", proj.ProjectName);
// Add the project to the collection
AddProjectToSolution(proj);
// If the project is an etp project then parse the etp project file
// to get the projects contained in it.
if (IsEtpProjectFile(proj.RelativePath))
{
ParseEtpProject(proj);
}
} // ParseProject()
/// <summary>
/// This method will parse a .etp project recursively and
/// add all the projects found to projects and projectsInOrder
/// </summary>
/// <param name="etpProj">ETP Project</param>
internal void ParseEtpProject(ProjectInSolution etpProj)
{
var etpProjectDocument = new XmlDocument();
// Get the full path to the .etp project file
string fullPathToEtpProj = Path.Combine(SolutionFileDirectory, etpProj.RelativePath);
string etpProjectRelativeDir = Path.GetDirectoryName(etpProj.RelativePath);
try
{
/****************************************************************************
* A Typical .etp project file will look like this
*<?xml version="1.0"?>
*<EFPROJECT>
* <GENERAL>
* <BANNER>Microsoft Visual Studio Application Template File</BANNER>
* <VERSION>1.00</VERSION>
* <Views>
* <ProjectExplorer>
* <File>ClassLibrary2\ClassLibrary2.csproj</File>
* </ProjectExplorer>
* </Views>
* <References>
* <Reference>
* <FILE>ClassLibrary2\ClassLibrary2.csproj</FILE>
* <GUIDPROJECTID>{73D0F4CE-D9D3-4E8B-81E4-B26FBF4CC2FE}</GUIDPROJECTID>
* </Reference>
* </References>
* </GENERAL>
*</EFPROJECT>
**********************************************************************************/
// Make sure the XML reader ignores DTD processing
var readerSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore };
// Load the .etp project file thru the XML reader
using (XmlReader xmlReader = XmlReader.Create(fullPathToEtpProj, readerSettings))
{
etpProjectDocument.Load(xmlReader);
}
// We need to parse the .etp project file to get the names of projects contained
// in the .etp Project. The projects are listed under /EFPROJECT/GENERAL/References/Reference node in the .etp project file.
// The /EFPROJECT/GENERAL/Views/ProjectExplorer node will not necessarily contain
// all the projects in the .etp project. Therefore, we need to look at
// /EFPROJECT/GENERAL/References/Reference.
// Find the /EFPROJECT/GENERAL/References/Reference node
// Note that this is case sensitive
XmlNodeList referenceNodes = etpProjectDocument.DocumentElement.SelectNodes("/EFPROJECT/GENERAL/References/Reference");
// Do the right thing for each <REference> element
foreach (XmlNode referenceNode in referenceNodes)
{
// Get the relative path to the project file
string fileElementValue = referenceNode.SelectSingleNode("FILE").InnerText;
// If <FILE> element is not present under <Reference> then we don't do anything.
if (fileElementValue != null)
{
// Create and populate a ProjectInSolution for the project
var proj = new ProjectInSolution(this)
{
RelativePath = Path.Combine(etpProjectRelativeDir, fileElementValue)
};
// Verify the relative path specified in the .etp proj file
ValidateProjectRelativePath(proj);
proj.ProjectType = SolutionProjectType.EtpSubProject;
proj.ProjectName = proj.RelativePath;
XmlNode projGuidNode = referenceNode.SelectSingleNode("GUIDPROJECTID");
// It is ok for a project to not have a guid inside an etp project.
// If a solution file contains a project without a guid it fails to
// load in Everett. But if an etp project contains a project without
// a guid it loads well in Everett and p2p references to/from this project
// are preserved. So we should make sure that we don’t error in this
// situation while upgrading.
proj.ProjectGuid = projGuidNode?.InnerText ?? String.Empty;
// Add the recently created proj to the collection of projects
AddProjectToSolution(proj);
// If the project is an etp project recurse
if (IsEtpProjectFile(fileElementValue))
{
ParseEtpProject(proj);
}
}
}
}
// catch all sorts of exceptions - if we encounter any problems here, we just assume the .etp project file is not in the correct format
// handle security errors
catch (SecurityException e)
{
// Log a warning
string warning = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out string errorCode, out _, "Shared.ProjectFileCouldNotBeLoaded",
etpProj.RelativePath, e.Message);
SolutionParserWarnings.Add(warning);
SolutionParserErrorCodes.Add(errorCode);
}
// handle errors in path resolution
catch (NotSupportedException e)
{
// Log a warning
string warning = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out string errorCode, out _, "Shared.ProjectFileCouldNotBeLoaded",
etpProj.RelativePath, e.Message);
SolutionParserWarnings.Add(warning);
SolutionParserErrorCodes.Add(errorCode);
}
// handle errors in loading project file
catch (IOException e)
{
// Log a warning
string warning = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out string errorCode, out _, "Shared.ProjectFileCouldNotBeLoaded",
etpProj.RelativePath, e.Message);
SolutionParserWarnings.Add(warning);
SolutionParserErrorCodes.Add(errorCode);
}
// handle errors in loading project file
catch (UnauthorizedAccessException e)
{
// Log a warning
string warning = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out string errorCode, out _, "Shared.ProjectFileCouldNotBeLoaded",
etpProj.RelativePath, e.Message);