Merge pull request #901 from Blewzman/FixAggregateExceptionGetBaseException
[mono.git] / mcs / tools / xbuild / SolutionParser.cs
1 //
2 // SolutionParser.cs: Generates a project file from a solution file.
3 //
4 // Author:
5 //   Jonathan Chambers (joncham@gmail.com)
6 //   Ankit Jain <jankit@novell.com>
7 //   Lluis Sanchez Gual <lluis@novell.com>
8 //
9 // (C) 2009 Jonathan Chambers
10 // Copyright 2008, 2009 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 //
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 //
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30
31 using System;
32 using System.Collections.Generic;
33 using System.Linq;
34 using System.Text;
35 using System.Text.RegularExpressions;
36 using System.IO;
37 using Microsoft.Build.BuildEngine;
38
39 namespace Mono.XBuild.CommandLine {
40         class ProjectInfo {
41                 public string Name;
42                 public string FileName;
43                 public Guid Guid;
44
45                 public ProjectInfo (string name, string fileName)
46                 {
47                         Name = name;
48                         FileName = fileName;
49                 }
50
51                 public Dictionary<TargetInfo, TargetInfo> TargetMap = new Dictionary<TargetInfo, TargetInfo> ();
52                 public Dictionary<Guid, ProjectInfo> Dependencies = new Dictionary<Guid, ProjectInfo> ();
53                 public Dictionary<string, ProjectSection> ProjectSections = new Dictionary<string, ProjectSection> ();
54                 public List<string> AspNetConfigurations = new List<string> ();
55         }
56
57         class ProjectSection {
58                 public string Name;
59                 public Dictionary<string, string> Properties = new Dictionary<string, string> ();
60
61                 public ProjectSection (string name)
62                 {
63                         Name = name;
64                 }
65         }
66
67         struct TargetInfo {
68                 public string Configuration;
69                 public string Platform;
70                 public bool Build;
71
72                 public TargetInfo (string configuration, string platform)
73                         : this (configuration, platform, false)
74                 {
75                 }
76
77                 public TargetInfo (string configuration, string platform, bool build)
78                 {
79                         Configuration = configuration;
80                         Platform = platform;
81                         Build = build;
82                 }
83         }
84
85
86         internal delegate void RaiseWarningHandler (int errorNumber, string message);
87
88         class SolutionParser {
89                 static string[] buildTargets = new string[] { "Build", "Clean", "Rebuild", "Publish" };
90
91                 static string guidExpression = "{[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}";
92
93                 static Regex slnVersionRegex = new Regex (@"Microsoft Visual Studio Solution File, Format Version (\d?\d.\d\d)");
94                 static Regex projectRegex = new Regex ("Project\\(\"(" + guidExpression + ")\"\\) = \"(.*?)\", \"(.*?)\", \"(" + guidExpression + ")\"(\\s*?)((\\s*?)ProjectSection\\((.*?)\\) = (.*?)EndProjectSection(\\s*?))*(\\s*?)(EndProject)?", RegexOptions.Singleline);
95                 static Regex projectDependenciesRegex = new Regex ("ProjectSection\\((.*?)\\) = \\w*(.*?)EndProjectSection", RegexOptions.Singleline);
96                 static Regex projectDependencyRegex = new Regex ("\\s*(" + guidExpression + ") = (" + guidExpression + ")");
97                 static Regex projectSectionPropertiesRegex = new Regex ("\\s*(?<name>.*) = \"(?<value>.*)\"");
98
99                 static Regex globalRegex = new Regex ("Global(.*)EndGlobal", RegexOptions.Singleline);
100                 static Regex globalSectionRegex = new Regex ("GlobalSection\\((.*?)\\) = \\w*(.*?)EndGlobalSection", RegexOptions.Singleline);
101
102                 static Regex solutionConfigurationRegex = new Regex ("\\s*(.*?)\\|(.*?) = (.*?)\\|(.+)");
103                 static Regex projectConfigurationActiveCfgRegex = new Regex ("\\s*(" + guidExpression + ")\\.(.+?)\\|(.+?)\\.ActiveCfg = (.+?)\\|(.+)");
104                 static Regex projectConfigurationBuildRegex = new Regex ("\\s*(" + guidExpression + ")\\.(.*?)\\|(.*?)\\.Build\\.0 = (.*?)\\|(.+)");
105
106                 static string solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}";
107                 static string vcprojGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
108                 static string websiteProjectGuid = "{E24C65DC-7377-472B-9ABA-BC803B73C61A}";
109
110                 RaiseWarningHandler RaiseWarning;
111
112                 public void ParseSolution (string file, Project p, RaiseWarningHandler RaiseWarning)
113                 {
114                         this.RaiseWarning = RaiseWarning;
115                         EmitBeforeImports (p, file);
116
117                         AddGeneralSettings (file, p);
118
119                         StreamReader reader = new StreamReader (file);
120
121                         string slnVersion = GetSlnFileVersion (reader);
122
123                         if (slnVersion == "12.00")
124 #if XBUILD_12
125                                 p.DefaultToolsVersion = "12.0";
126 #else
127                                 p.DefaultToolsVersion = "4.0";
128 #endif
129                         else if (slnVersion == "11.00")
130                                 p.DefaultToolsVersion = "4.0";
131                         else if (slnVersion == "10.00")
132                                 p.DefaultToolsVersion = "3.5";
133                         else
134                                 p.DefaultToolsVersion = "2.0";
135
136                         string line = reader.ReadToEnd ();
137                         line = line.Replace ("\r\n", "\n");
138                         string solutionDir = Path.GetDirectoryName (file);
139
140                         List<TargetInfo> solutionTargets = new List<TargetInfo> ();
141                         Dictionary<Guid, ProjectInfo> projectInfos = new Dictionary<Guid, ProjectInfo> ();
142                         Dictionary<Guid, ProjectInfo> websiteProjectInfos = new Dictionary<Guid, ProjectInfo> ();
143                         List<ProjectInfo>[] infosByLevel = null;
144                         Dictionary<Guid, ProjectInfo> unsupportedProjectInfos = new Dictionary<Guid, ProjectInfo> ();
145
146                         Match m = projectRegex.Match (line);
147                         while (m.Success) {
148                                 ProjectInfo projectInfo = new ProjectInfo (m.Groups[2].Value,
149                                                                 Path.GetFullPath (Path.Combine (solutionDir,
150                                                                         m.Groups [3].Value.Replace ('\\', Path.DirectorySeparatorChar))));
151                                 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
152                                                 StringComparison.InvariantCultureIgnoreCase) == 0) {
153                                         // Ignore solution folders
154                                         m = m.NextMatch ();
155                                         continue;
156                                 }
157
158                                 projectInfo.Guid = new Guid (m.Groups [4].Value);
159
160                                 if (String.Compare (m.Groups [1].Value, vcprojGuid,
161                                                 StringComparison.InvariantCultureIgnoreCase) == 0) {
162                                         // Ignore vcproj 
163                                         RaiseWarning (0, string.Format("Ignoring vcproj '{0}'.", projectInfo.Name));
164
165                                         unsupportedProjectInfos [projectInfo.Guid] = projectInfo;
166                                         m = m.NextMatch ();
167                                         continue;
168                                 }
169
170                                 if (String.Compare (m.Groups [1].Value, websiteProjectGuid,
171                                                 StringComparison.InvariantCultureIgnoreCase) == 0)
172                                         websiteProjectInfos.Add (new Guid (m.Groups[4].Value), projectInfo);
173                                 else
174                                         projectInfos.Add (projectInfo.Guid, projectInfo);
175
176                                 Match projectSectionMatch = projectDependenciesRegex.Match (m.Groups[6].Value);
177                                 while (projectSectionMatch.Success) {
178                                         string section_name = projectSectionMatch.Groups [1].Value;
179                                         if (String.Compare (section_name, "ProjectDependencies") == 0) {
180                                                 Match projectDependencyMatch = projectDependencyRegex.Match (projectSectionMatch.Value);
181                                                 while (projectDependencyMatch.Success) {
182                                                         // we might not have projectInfo available right now, so
183                                                         // set it to null, and fill it in later
184                                                         projectInfo.Dependencies [new Guid (projectDependencyMatch.Groups[1].Value)] = null;
185                                                         projectDependencyMatch = projectDependencyMatch.NextMatch ();
186                                                 }
187                                         } else {
188                                                 ProjectSection section = new ProjectSection (section_name);
189                                                 Match propertiesMatch = projectSectionPropertiesRegex.Match (
190                                                                         projectSectionMatch.Groups [2].Value);
191                                                 while (propertiesMatch.Success) {
192                                                         section.Properties [propertiesMatch.Groups ["name"].Value] =
193                                                                 propertiesMatch.Groups ["value"].Value;
194
195                                                         propertiesMatch = propertiesMatch.NextMatch ();
196                                                 }
197
198                                                 projectInfo.ProjectSections [section_name] = section;
199                                         }
200                                         projectSectionMatch = projectSectionMatch.NextMatch ();
201                                 }
202                                 m = m.NextMatch ();
203                         }
204
205                         foreach (ProjectInfo projectInfo in projectInfos.Values) {
206                                 string filename = projectInfo.FileName;
207                                 string projectDir = Path.GetDirectoryName (filename);
208
209                                 if (!File.Exists (filename)) {
210                                         RaiseWarning (0, String.Format ("Project file {0} referenced in the solution file, " +
211                                                                 "not found. Ignoring.", filename));
212                                         continue;
213                                 }
214
215                                 Project currentProject = p.ParentEngine.CreateNewProject ();
216                                 try {
217                                         currentProject.Load (filename, ProjectLoadSettings.IgnoreMissingImports);
218                                 } catch (InvalidProjectFileException e) {
219                                         RaiseWarning (0, e.Message);
220                                         continue;
221                                 }
222
223                                 foreach (BuildItem bi in currentProject.GetEvaluatedItemsByName ("ProjectReference")) {
224                                         ProjectInfo info = null;
225                                         string projectReferenceGuid = bi.GetEvaluatedMetadata ("Project");
226                                         bool hasGuid = !String.IsNullOrEmpty (projectReferenceGuid);
227
228                                         // try to resolve the ProjectReference by GUID
229                                         // and fallback to project filename
230
231                                         if (hasGuid) {
232                                                 Guid guid = new Guid (projectReferenceGuid);
233                                                 projectInfos.TryGetValue (guid, out info);
234                                                 if (info == null && unsupportedProjectInfos.TryGetValue (guid, out info)) {
235                                                         RaiseWarning (0, String.Format (
236                                                                         "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
237                                                                         filename, bi.Include));
238                                                         continue;
239                                                 }
240                                         }
241
242                                         if (info == null || !hasGuid) {
243                                                 // Project not found by guid or guid not available
244                                                 // Try to find by project file
245
246                                                 string fullpath = Path.GetFullPath (Path.Combine (projectDir, bi.Include.Replace ('\\', Path.DirectorySeparatorChar)));
247                                                 info = projectInfos.Values.FirstOrDefault (pi => pi.FileName == fullpath);
248
249                                                 if (info == null) {
250                                                         if (unsupportedProjectInfos.Values.Any (pi => pi.FileName == fullpath))
251                                                                 RaiseWarning (0, String.Format (
252                                                                                 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
253                                                                                 filename, bi.Include));
254                                                         else
255                                                                 RaiseWarning (0, String.Format (
256                                                                                 "{0}: ProjectReference '{1}' not found, neither by guid '{2}' nor by project file name '{3}'.",
257                                                                                 filename, bi.Include, projectReferenceGuid.Replace ("{", "").Replace ("}", ""), fullpath));
258                                                 }
259
260                                         }
261
262                                         if (info != null)
263                                                 projectInfo.Dependencies [info.Guid] = info;
264                                 }
265                         }
266
267                         // fill in the project info for deps found in the .sln file
268                         foreach (ProjectInfo projectInfo in projectInfos.Values) {
269                                 List<Guid> missingInfos = new List<Guid> ();
270                                 foreach (KeyValuePair<Guid, ProjectInfo> dependency in projectInfo.Dependencies) {
271                                         if (dependency.Value == null)
272                                                 missingInfos.Add (dependency.Key);
273                                 }
274
275                                 foreach (Guid guid in missingInfos) {
276                                         ProjectInfo info;
277                                         if (projectInfos.TryGetValue (guid, out info))
278                                                 projectInfo.Dependencies [guid] = info;
279                                         else
280                                                 projectInfo.Dependencies.Remove (guid);
281                                 }
282                         }
283
284                         Match globalMatch = globalRegex.Match (line);
285                         Match globalSectionMatch = globalSectionRegex.Match (globalMatch.Groups[1].Value);
286                         while (globalSectionMatch.Success) {
287                                 string sectionType = globalSectionMatch.Groups[1].Value;
288                                 switch (sectionType) {
289                                         case "SolutionConfigurationPlatforms":
290                                                 ParseSolutionConfigurationPlatforms (globalSectionMatch.Groups[2].Value, solutionTargets);
291                                                 break;
292                                         case "ProjectConfigurationPlatforms":
293                                                 ParseProjectConfigurationPlatforms (globalSectionMatch.Groups[2].Value,
294                                                                 projectInfos, websiteProjectInfos);
295                                                 break;
296                                         case "SolutionProperties":
297                                                 ParseSolutionProperties (globalSectionMatch.Groups[2].Value);
298                                                 break;
299                                         case "NestedProjects":
300                                                 break;
301                                         case "MonoDevelopProperties":
302                                                 break;
303                                         default:
304                                                 RaiseWarning (0, string.Format("Don't know how to handle GlobalSection {0}, Ignoring.", sectionType));
305                                                 break;
306                                 }
307                                 globalSectionMatch = globalSectionMatch.NextMatch ();
308                         }
309
310                         int num_levels = AddBuildLevels (p, solutionTargets, projectInfos, ref infosByLevel);
311
312                         AddCurrentSolutionConfigurationContents (p, solutionTargets, projectInfos, websiteProjectInfos);
313                         AddProjectReferences (p, projectInfos);
314                         AddWebsiteProperties (p, websiteProjectInfos, projectInfos);
315                         AddValidateSolutionConfiguration (p);
316
317                         EmitAfterImports (p, file);
318
319                         AddGetFrameworkPathTarget (p);
320                         AddWebsiteTargets (p, websiteProjectInfos, projectInfos, infosByLevel, solutionTargets);
321                         AddProjectTargets (p, solutionTargets, projectInfos);
322                         AddSolutionTargets (p, num_levels, websiteProjectInfos.Values);
323                 }
324
325                 string GetSlnFileVersion (StreamReader reader)
326                 {
327                         string strInput = null;
328                         Match match;
329
330                         strInput = reader.ReadLine();
331                         if (strInput == null)
332                                 return null;
333
334                         match = slnVersionRegex.Match(strInput);
335                         if (!match.Success) {
336                                 strInput = reader.ReadLine();
337                                 if (strInput == null)
338                                         return null;
339                                 match = slnVersionRegex.Match (strInput);
340                         }
341
342                         if (match.Success)
343                                 return match.Groups[1].Value;
344
345                         return null;
346                 }
347
348                 void EmitBeforeImports (Project p, string file)
349                 {
350 #if NET_4_0
351                         p.AddNewImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportBefore\\*",
352                                         "'$(ImportByWildcardBeforeSolution)' != 'false' and " +
353                                         "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportBefore')");
354 #endif
355
356                         string before_filename = Path.Combine (Path.GetDirectoryName (file), "before." + Path.GetFileName (file) + ".targets");
357                         p.AddNewImport (before_filename, String.Format ("Exists ('{0}')", before_filename));
358                 }
359
360                 void EmitAfterImports (Project p, string file)
361                 {
362 #if NET_4_0
363                         p.AddNewImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportAfter\\*",
364                                         "'$(ImportByWildcardAfterSolution)' != 'false' and " +
365                                         "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportAfter')");
366 #endif
367
368                         string after_filename = Path.Combine (Path.GetDirectoryName (file), "after." + Path.GetFileName (file) + ".targets");
369                         p.AddNewImport (after_filename, String.Format ("Exists ('{0}')", after_filename));
370                 }
371
372                 void AddGeneralSettings (string solutionFile, Project p)
373                 {
374                         p.DefaultTargets = "Build";
375                         p.InitialTargets = "ValidateSolutionConfiguration";
376                         p.AddNewUsingTaskFromAssemblyName ("CreateTemporaryVCProject", "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
377                         p.AddNewUsingTaskFromAssemblyName ("ResolveVCProjectOutput", "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
378
379                         string solutionFilePath = Path.GetFullPath (solutionFile);
380                         BuildPropertyGroup solutionPropertyGroup = p.AddNewPropertyGroup (true);
381                         solutionPropertyGroup.AddNewProperty ("SolutionDir", Path.GetDirectoryName (solutionFilePath) + Path.DirectorySeparatorChar);
382                         solutionPropertyGroup.AddNewProperty ("SolutionExt", Path.GetExtension (solutionFile));
383                         solutionPropertyGroup.AddNewProperty ("SolutionFileName", Path.GetFileName (solutionFile));
384                         solutionPropertyGroup.AddNewProperty ("SolutionName", Path.GetFileNameWithoutExtension (solutionFile));
385                         solutionPropertyGroup.AddNewProperty ("SolutionPath", solutionFilePath);
386                 }
387
388                 void ParseSolutionConfigurationPlatforms (string section, List<TargetInfo> solutionTargets)
389                 {
390                         Match solutionConfigurationPlatform = solutionConfigurationRegex.Match (section);
391                         while (solutionConfigurationPlatform.Success) {
392                                 string solutionConfiguration = solutionConfigurationPlatform.Groups[1].Value;
393                                 string solutionPlatform = solutionConfigurationPlatform.Groups[2].Value;
394                                 solutionTargets.Add (new TargetInfo (solutionConfiguration, solutionPlatform));
395                                 solutionConfigurationPlatform = solutionConfigurationPlatform.NextMatch ();
396                         }
397                 }
398
399                 // ignores the website projects, in the websiteProjectInfos
400                 void ParseProjectConfigurationPlatforms (string section, Dictionary<Guid, ProjectInfo> projectInfos,
401                                 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
402                 {
403                         List<Guid> missingGuids = new List<Guid> ();
404                         Match projectConfigurationPlatform = projectConfigurationActiveCfgRegex.Match (section);
405                         while (projectConfigurationPlatform.Success) {
406                                 Guid guid = new Guid (projectConfigurationPlatform.Groups[1].Value);
407                                 ProjectInfo projectInfo;
408                                 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
409                                         if (!missingGuids.Contains (guid)) {
410                                                 if (!websiteProjectInfos.ContainsKey (guid))
411                                                         // ignore website projects
412                                                         RaiseWarning (0, string.Format("Failed to find project {0}", guid));
413                                                 missingGuids.Add (guid);
414                                         }
415                                         projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
416                                         continue;
417                                 }
418                                 string solConf = projectConfigurationPlatform.Groups[2].Value;
419                                 string solPlat = projectConfigurationPlatform.Groups[3].Value;
420                                 string projConf = projectConfigurationPlatform.Groups[4].Value;
421                                 string projPlat = projectConfigurationPlatform.Groups[5].Value;
422                                 // hack, what are they doing here?
423                                 if (projPlat == "Any CPU")
424                                         projPlat = "AnyCPU";
425                                 projectInfo.TargetMap.Add (new TargetInfo (solConf, solPlat), new TargetInfo (projConf, projPlat));
426                                 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
427                         }
428                         Match projectConfigurationPlatformBuild = projectConfigurationBuildRegex.Match (section);
429                         while (projectConfigurationPlatformBuild.Success) {
430                                 Guid guid = new Guid (projectConfigurationPlatformBuild.Groups[1].Value);
431                                 ProjectInfo projectInfo;
432                                 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
433                                         if (!missingGuids.Contains (guid)) {
434                                                 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
435                                                 missingGuids.Add (guid);
436                                         }
437                                         projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
438                                         continue;
439                                 }
440                                 string solConf = projectConfigurationPlatformBuild.Groups[2].Value;
441                                 string solPlat = projectConfigurationPlatformBuild.Groups[3].Value;
442                                 string projConf = projectConfigurationPlatformBuild.Groups[4].Value;
443                                 string projPlat = projectConfigurationPlatformBuild.Groups[5].Value;
444                                 // hack, what are they doing here?
445                                 if (projPlat == "Any CPU")
446                                         projPlat = "AnyCPU";
447                                 projectInfo.TargetMap[new TargetInfo (solConf, solPlat)] = new TargetInfo (projConf, projPlat, true);
448                                 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
449                         }
450                 }
451
452                 void ParseSolutionProperties (string section)
453                 {
454                 }
455
456                 void AddCurrentSolutionConfigurationContents (Project p, List<TargetInfo> solutionTargets,
457                                 Dictionary<Guid, ProjectInfo> projectInfos,
458                                 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
459                 {
460                         TargetInfo default_target_info = new TargetInfo ("Debug", "Any CPU");
461                         if (solutionTargets.Count > 0) {
462                                 bool found = false;
463                                 foreach (TargetInfo tinfo in solutionTargets) {
464                                         if (String.Compare (tinfo.Platform, "Mixed Platforms") == 0) {
465                                                 default_target_info = tinfo;
466                                                 found = true;
467                                                 break;
468                                         }
469                                 }
470
471                                 if (!found)
472                                         default_target_info = solutionTargets [0];
473                         }
474
475                         AddDefaultSolutionConfiguration (p, default_target_info);
476
477                         foreach (TargetInfo solutionTarget in solutionTargets) {
478                                 BuildPropertyGroup platformPropertyGroup = p.AddNewPropertyGroup (false);
479                                 platformPropertyGroup.Condition = string.Format (
480                                         " ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
481                                         solutionTarget.Configuration,
482                                         solutionTarget.Platform
483                                         );
484
485                                 StringBuilder solutionConfigurationContents = new StringBuilder ();
486                                 solutionConfigurationContents.Append ("<SolutionConfiguration xmlns=\"\">");
487                                 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
488                                         AddProjectConfigurationItems (projectInfo.Key, projectInfo.Value, solutionTarget, solutionConfigurationContents);
489                                 }
490                                 solutionConfigurationContents.Append ("</SolutionConfiguration>");
491
492                                 platformPropertyGroup.AddNewProperty ("CurrentSolutionConfigurationContents",
493                                                 solutionConfigurationContents.ToString ());
494                         }
495                 }
496
497                 void AddProjectReferences (Project p, Dictionary<Guid, ProjectInfo> projectInfos)
498                 {
499                         BuildItemGroup big = p.AddNewItemGroup ();
500                         foreach (KeyValuePair<Guid, ProjectInfo> pair in projectInfos)
501                                 big.AddNewItem ("ProjectReference", pair.Value.FileName);
502                 }
503
504                 void AddProjectConfigurationItems (Guid guid, ProjectInfo projectInfo, TargetInfo solutionTarget,
505                                 StringBuilder solutionConfigurationContents)
506                 {
507                         foreach (KeyValuePair<TargetInfo, TargetInfo> targetInfo in projectInfo.TargetMap) {
508                                 if (solutionTarget.Configuration == targetInfo.Key.Configuration &&
509                                                 solutionTarget.Platform == targetInfo.Key.Platform) {
510                                         solutionConfigurationContents.AppendFormat (
511                                                         "<ProjectConfiguration Project=\"{0}\">{1}|{2}</ProjectConfiguration>",
512                                         guid.ToString ("B").ToUpper (), targetInfo.Value.Configuration, targetInfo.Value.Platform);
513                                 }
514                         }
515                 }
516
517                 void AddDefaultSolutionConfiguration (Project p, TargetInfo target)
518                 {
519                         BuildPropertyGroup configurationPropertyGroup = p.AddNewPropertyGroup (true);
520                         configurationPropertyGroup.Condition = " '$(Configuration)' == '' ";
521                         configurationPropertyGroup.AddNewProperty ("Configuration", target.Configuration);
522
523                         BuildPropertyGroup platformPropertyGroup = p.AddNewPropertyGroup (true);
524                         platformPropertyGroup.Condition = " '$(Platform)' == '' ";
525                         platformPropertyGroup.AddNewProperty ("Platform", target.Platform);
526                         
527                         // emit default for AspNetConfiguration also
528                         BuildPropertyGroup aspNetConfigurationPropertyGroup = p.AddNewPropertyGroup (true);
529                         aspNetConfigurationPropertyGroup.Condition = " ('$(AspNetConfiguration)' == '') ";
530                         aspNetConfigurationPropertyGroup.AddNewProperty ("AspNetConfiguration", "$(Configuration)");
531                 }
532
533                 void AddWarningForMissingProjectConfiguration (Target target, string slnConfig, string slnPlatform, string projectName)
534                 {
535                         BuildTask task = target.AddNewTask ("Warning");
536                         task.SetParameterValue ("Text",
537                                         String.Format ("The project configuration for project '{0}' corresponding " +
538                                                 "to the solution configuration '{1}|{2}' was not found in the solution file.",
539                                                 projectName, slnConfig, slnPlatform));
540                         task.Condition = String.Format ("('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}')",
541                                                 slnConfig, slnPlatform);
542
543                 }
544
545                 // Website project methods
546
547                 void AddWebsiteProperties (Project p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
548                                 Dictionary<Guid, ProjectInfo> projectInfos)
549                 {
550                         var propertyGroupByConfig = new Dictionary<string, BuildPropertyGroup> ();
551                         foreach (KeyValuePair<Guid, ProjectInfo> infoPair in websiteProjectInfos) {
552                                 ProjectInfo info = infoPair.Value;
553                                 string projectGuid = infoPair.Key.ToString ();
554
555                                 ProjectSection section;
556                                 if (!info.ProjectSections.TryGetValue ("WebsiteProperties", out section)) {
557                                         RaiseWarning (0, String.Format ("Website project '{0}' does not have the required project section: WebsiteProperties. Ignoring project.", info.Name));
558                                         return;
559                                 }
560
561                                 //parse project references
562                                 string [] ref_guids = null;
563                                 string references;
564                                 if (section.Properties.TryGetValue ("ProjectReferences", out references)) {
565                                         ref_guids = references.Split (new char [] {';'}, StringSplitOptions.RemoveEmptyEntries);
566                                         for (int i = 0; i < ref_guids.Length; i ++) {
567                                                 // "{guid}|foo.dll"
568                                                 ref_guids [i] = ref_guids [i].Split ('|') [0];
569
570                                                 Guid r_guid = new Guid (ref_guids [i]);
571                                                 ProjectInfo ref_info;
572                                                 if (projectInfos.TryGetValue (r_guid, out ref_info))
573                                                         // ignore if not found
574                                                         info.Dependencies [r_guid] = ref_info;
575                                         }
576                                 }
577
578                                 foreach (KeyValuePair<string, string> pair in section.Properties) {
579                                         //looking for -- ConfigName.AspNetCompiler.PropName
580                                         string [] parts = pair.Key.Split ('.');
581                                         if (parts.Length != 3 || String.Compare (parts [1], "AspNetCompiler") != 0)
582                                                 continue;
583
584                                         string config = parts [0];
585                                         string propertyName = parts [2];
586
587                                         BuildPropertyGroup bpg;
588                                         if (!propertyGroupByConfig.TryGetValue (config, out bpg)) {
589                                                 bpg = p.AddNewPropertyGroup (true);
590                                                 bpg.Condition = String.Format (" '$(AspNetConfiguration)' == '{0}' ", config);
591                                                 propertyGroupByConfig [config] = bpg;
592                                         }
593
594                                         bpg.AddNewProperty (String.Format ("Project_{0}_AspNet{1}", projectGuid, propertyName),
595                                                                 pair.Value);
596
597                                         if (!info.AspNetConfigurations.Contains (config))
598                                                 info.AspNetConfigurations.Add (config);
599                                 }
600                         }
601                 }
602
603                 // For WebSite projects
604                 // The main "Build" target:
605                 //      1. builds all non-website projects
606                 //      2. calls target for website project
607                 //              - gets target path for the referenced projects
608                 //              - Resolves dependencies, satellites etc for the
609                 //                referenced project assemblies, and copies them
610                 //                to bin/ folder
611                 void AddWebsiteTargets (Project p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
612                                 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo>[] infosByLevel,
613                                 List<TargetInfo> solutionTargets)
614                 {
615                         foreach (ProjectInfo w_info in websiteProjectInfos.Values) {
616                                 // gets a linear list of dependencies
617                                 List<ProjectInfo> depInfos = new List<ProjectInfo> ();
618                                 foreach (List<ProjectInfo> pinfos in infosByLevel) {
619                                         foreach (ProjectInfo pinfo in pinfos)
620                                                 if (w_info.Dependencies.ContainsKey (pinfo.Guid))
621                                                         depInfos.Add (pinfo);
622                                 }
623
624                                 foreach (string buildTarget in new string [] {"Build", "Rebuild"})
625                                         AddWebsiteTarget (p, w_info, projectInfos, depInfos, solutionTargets, buildTarget);
626
627                                 // clean/publish are not supported for website projects
628                                 foreach (string buildTarget in new string [] {"Clean", "Publish"})
629                                         AddWebsiteUnsupportedTarget (p, w_info, depInfos, buildTarget);
630                         }
631                 }
632
633                 void AddWebsiteTarget (Project p, ProjectInfo webProjectInfo,
634                                 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo> depInfos,
635                                 List<TargetInfo> solutionTargets, string buildTarget)
636                 {
637                         string w_guid = webProjectInfo.Guid.ToString ().ToUpper ();
638
639                         Target target = p.Targets.AddNewTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
640                         target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''"; 
641                         target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
642
643                         // this item collects all the references
644                         string final_ref_item = String.Format ("Project_{0}_References{1}", w_guid,
645                                                         buildTarget != "Build" ? "_" + buildTarget : String.Empty);
646
647                         foreach (TargetInfo targetInfo in solutionTargets) {
648                                 int ref_num = 0;
649                                 foreach (ProjectInfo depInfo in depInfos) {
650                                         TargetInfo projectTargetInfo;
651                                         if (!depInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo))
652                                                 // Ignore, no config, so no target path
653                                                 continue;
654
655                                         // GetTargetPath from the referenced project
656                                         AddWebsiteMSBuildTaskForReference (target, depInfo, projectTargetInfo, targetInfo,
657                                                         final_ref_item, ref_num);
658                                         ref_num ++;
659                                 }
660                         }
661
662                         // resolve the references
663                         AddWebsiteResolveAndCopyReferencesTasks (target, webProjectInfo, final_ref_item, w_guid);
664                 }
665
666                 // emits the MSBuild task to GetTargetPath for the referenced project
667                 void AddWebsiteMSBuildTaskForReference (Target target, ProjectInfo depInfo, TargetInfo projectTargetInfo,
668                                 TargetInfo solutionTargetInfo, string final_ref_item, int ref_num)
669                 {
670                         BuildTask task = target.AddNewTask ("MSBuild");
671                         task.SetParameterValue ("Projects", depInfo.FileName);
672                         task.SetParameterValue ("Targets", "GetTargetPath");
673
674                         task.SetParameterValue ("Properties", string.Format ("Configuration={0}; Platform={1}; BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)", projectTargetInfo.Configuration, projectTargetInfo.Platform));
675                         task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", solutionTargetInfo.Configuration, solutionTargetInfo.Platform);
676
677                         string ref_item = String.Format ("{0}_{1}",
678                                                 final_ref_item, ref_num); 
679
680                         task.AddOutputItem ("TargetOutputs", ref_item);
681
682                         task = target.AddNewTask ("CreateItem");
683                         task.SetParameterValue ("Include", String.Format ("@({0})", ref_item));
684                         task.SetParameterValue ("AdditionalMetadata", String.Format ("Guid={{{0}}}",
685                                                 depInfo.Guid.ToString ().ToUpper ()));
686                         task.AddOutputItem ("Include", final_ref_item);
687                 }
688
689                 void AddWebsiteResolveAndCopyReferencesTasks (Target target, ProjectInfo webProjectInfo,
690                                 string final_ref_item, string w_guid)
691                 {
692                         BuildTask task = target.AddNewTask ("ResolveAssemblyReference");
693                         task.SetParameterValue ("Assemblies", String.Format ("@({0}->'%(FullPath)')", final_ref_item));
694                         task.SetParameterValue ("TargetFrameworkDirectories", "$(TargetFrameworkPath)");
695                         task.SetParameterValue ("SearchPaths", "{RawFileName};{TargetFrameworkDirectory};{GAC}");
696                         task.SetParameterValue ("FindDependencies", "true");
697                         task.SetParameterValue ("FindSatellites", "true");
698                         task.SetParameterValue ("FindRelatedFiles", "true");
699                         task.Condition = String.Format ("Exists ('%({0}.Identity)')", final_ref_item);
700
701                         string copylocal_item = String.Format ("{0}_CopyLocalFiles", final_ref_item);
702                         task.AddOutputItem ("CopyLocalFiles", copylocal_item);
703
704                         // Copy the references
705                         task = target.AddNewTask ("Copy");
706                         task.SetParameterValue ("SourceFiles", String.Format ("@({0})", copylocal_item));
707                         task.SetParameterValue ("DestinationFiles", String.Format (
708                                                 "@({0}->'$(Project_{1}_AspNetPhysicalPath)\\Bin\\%(DestinationSubDirectory)%(Filename)%(Extension)')",
709                                                 copylocal_item, w_guid));
710
711                         // AspNetConfiguration, is config for the website project, useful
712                         // for overriding from command line
713                         StringBuilder cond = new StringBuilder ();
714                         foreach (string config in webProjectInfo.AspNetConfigurations) {
715                                 if (cond.Length > 0)
716                                         cond.Append (" or ");
717                                 cond.AppendFormat (" ('$(AspNetConfiguration)' == '{0}') ", config);
718                         }
719                         task.Condition = cond.ToString ();
720
721                         task = target.AddNewTask ("Message");
722                         cond = new StringBuilder ();
723                         foreach (string config in webProjectInfo.AspNetConfigurations) {
724                                 if (cond.Length > 0)
725                                         cond.Append (" and ");
726                                 cond.AppendFormat (" ('$(AspNetConfiguration)' != '{0}') ", config);
727                         }
728                         task.Condition = cond.ToString ();
729                         task.SetParameterValue ("Text", "Skipping as the '$(AspNetConfiguration)' configuration is " +
730                                                 "not supported by this website project.");
731                 }
732
733                 void AddWebsiteUnsupportedTarget (Project p, ProjectInfo webProjectInfo, List<ProjectInfo> depInfos,
734                                 string buildTarget)
735                 {
736                         Target target = p.Targets.AddNewTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
737                         target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
738
739                         BuildTask task = target.AddNewTask ("Message");
740                         task.SetParameterValue ("Text", String.Format (
741                                                 "Target '{0}' not support for website projects", buildTarget));
742                 }
743
744                 string GetWebsiteDependsOnTarget (List<ProjectInfo> depInfos, string buildTarget)
745                 {
746                         StringBuilder deps = new StringBuilder ();
747                         foreach (ProjectInfo pinfo in depInfos) {
748                                 if (deps.Length > 0)
749                                         deps.Append (";");
750                                 deps.Append (GetTargetNameForProject (pinfo.Name, buildTarget));
751                         }
752                         deps.Append (";GetFrameworkPath");
753                         return deps.ToString ();
754                 }
755
756                 void AddGetFrameworkPathTarget (Project p)
757                 {
758                         Target t = p.Targets.AddNewTarget ("GetFrameworkPath");
759                         BuildTask task = t.AddNewTask ("GetFrameworkPath");
760                         task.AddOutputProperty ("Path", "TargetFrameworkPath");
761                 }
762
763                 void AddValidateSolutionConfiguration (Project p)
764                 {
765                         Target t = p.Targets.AddNewTarget ("ValidateSolutionConfiguration");
766                         BuildTask task = t.AddNewTask ("Warning");
767                         task.SetParameterValue ("Text", "On windows, an environment variable 'Platform' is set to MCD sometimes, and this overrides the Platform property" +
768                                                 " for xbuild, which could be an invalid Platform for this solution file. And so you are getting the following error." +
769                                                 " You could override it by either setting the environment variable to nothing, as\n" +
770                                                 "   set Platform=\n" +
771                                                 "Or explicity specify its value on the command line, as\n" +
772                                                 "   xbuild Foo.sln /p:Platform=Release");
773                         task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')" +
774                                         " and '$(Platform)' == 'MCD' and '$(OS)' == 'Windows_NT'";
775
776                         task = t.AddNewTask ("Error");
777                         task.SetParameterValue ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
778                         task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')";
779                         task = t.AddNewTask ("Warning");
780                         task.SetParameterValue ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
781                         task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' == 'true')";
782                         task = t.AddNewTask ("Message");
783                         task.SetParameterValue ("Text", "Building solution configuration \"$(Configuration)|$(Platform)\".");
784                         task.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
785                 }
786
787                 void AddProjectTargets (Project p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos)
788                 {
789                         foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
790                                 ProjectInfo project = projectInfo.Value;
791                                 foreach (string buildTarget in buildTargets) {
792                                         string target_name = GetTargetNameForProject (project.Name, buildTarget);
793                                         bool is_build_or_rebuild = buildTarget == "Build" || buildTarget == "Rebuild";
794                                         Target target = p.Targets.AddNewTarget (target_name);
795                                         target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''"; 
796
797                                         if (is_build_or_rebuild)
798                                                 target.Outputs = "@(CollectedBuildOutput)";
799                                         if (project.Dependencies.Count > 0)
800                                                 target.DependsOnTargets = String.Join (";",
801                                                                 project.Dependencies.Values.Select (
802                                                                         di => GetTargetNameForProject (di.Name, buildTarget)).ToArray ());
803
804                                         foreach (TargetInfo targetInfo in solutionTargets) {
805                                                 BuildTask task = null;
806                                                 TargetInfo projectTargetInfo;
807                                                 if (!project.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
808                                                         AddWarningForMissingProjectConfiguration (target, targetInfo.Configuration,
809                                                                         targetInfo.Platform, project.Name);
810                                                         continue;
811                                                 }
812                                                 if (projectTargetInfo.Build) {
813                                                         task = target.AddNewTask ("MSBuild");
814                                                         task.SetParameterValue ("Projects", project.FileName);
815                                                         task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
816                                                         if (is_build_or_rebuild)
817                                                                 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
818
819                                                         if (buildTarget != "Build")
820                                                                 task.SetParameterValue ("Targets", buildTarget);
821                                                         task.SetParameterValue ("Properties", string.Format ("Configuration={0}; Platform={1}; BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)", projectTargetInfo.Configuration, projectTargetInfo.Platform));
822                                                 } else {
823                                                         task = target.AddNewTask ("Message");
824                                                         task.SetParameterValue ("Text", string.Format ("Project \"{0}\" is disabled for solution configuration \"{1}|{2}\".", project.Name, targetInfo.Configuration, targetInfo.Platform));
825                                                 }
826                                                 task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", targetInfo.Configuration, targetInfo.Platform);
827                                         }
828                                 }
829                         }
830                 }
831
832
833                 string GetTargetNameForProject (string projectName, string buildTarget)
834                 {
835                         //FIXME: hack
836                         projectName = projectName.Replace ("\\", "/").Replace (".", "_");
837                         string target_name = projectName +
838                                         (buildTarget == "Build" ? string.Empty : ":" + buildTarget);
839
840                         if (IsBuildTargetName (projectName))
841                                 target_name = "Solution:" + target_name;
842
843                         return target_name;
844                 }
845
846                 bool IsBuildTargetName (string name)
847                 {
848                         foreach (string tgt in buildTargets)
849                                 if (name == tgt)
850                                         return true;
851                         return false;
852                 }
853
854                 // returns number of levels
855                 int AddBuildLevels (Project p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos,
856                                 ref List<ProjectInfo>[] infosByLevel)
857                 {
858                         infosByLevel = TopologicalSort<ProjectInfo> (projectInfos.Values);
859
860                         foreach (TargetInfo targetInfo in solutionTargets) {
861                                 BuildItemGroup big = p.AddNewItemGroup ();
862                                 big.Condition = String.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
863                                                 targetInfo.Configuration, targetInfo.Platform);
864
865                                 //FIXME: every level has projects that can be built in parallel.
866                                 //       levels are ordered on the basis of the dependency graph
867
868                                 for (int i = 0; i < infosByLevel.Length; i ++) {
869                                         string build_level = String.Format ("BuildLevel{0}", i);
870                                         string skip_level = String.Format ("SkipLevel{0}", i);
871                                         string missing_level = String.Format ("MissingConfigLevel{0}", i);
872
873                                         foreach (ProjectInfo projectInfo in infosByLevel [i]) {
874                                                 TargetInfo projectTargetInfo;
875                                                 if (!projectInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
876                                                         // missing project config
877                                                         big.AddNewItem (missing_level, projectInfo.Name);
878                                                         continue;
879                                                 }
880
881                                                 if (projectTargetInfo.Build) {
882                                                         BuildItem item = big.AddNewItem (build_level, projectInfo.FileName);
883                                                         item.SetMetadata ("Configuration", projectTargetInfo.Configuration);
884                                                         item.SetMetadata ("Platform", projectTargetInfo.Platform);
885                                                 } else {
886                                                         // build disabled
887                                                         big.AddNewItem (skip_level, projectInfo.Name);
888                                                 }
889                                         }
890                                 }
891                         }
892
893                         return infosByLevel.Length;
894                 }
895
896                 void AddSolutionTargets (Project p, int num_levels, IEnumerable<ProjectInfo> websiteProjectInfos)
897                 {
898                         foreach (string buildTarget in buildTargets) {
899                                 Target t = p.Targets.AddNewTarget (buildTarget);
900                                 bool is_build_or_rebuild = buildTarget == "Build" || buildTarget == "Rebuild";
901
902                                 t.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
903                                 if (is_build_or_rebuild)
904                                         t.Outputs = "@(CollectedBuildOutput)";
905
906                                 BuildTask task = null;
907                                 for (int i = 0; i < num_levels; i ++) {
908                                         string level_str = String.Format ("BuildLevel{0}", i);
909                                         task = t.AddNewTask ("MSBuild");
910                                         task.SetParameterValue ("Condition", String.Format ("'@({0})' != ''", level_str));
911                                         task.SetParameterValue ("Projects", String.Format ("@({0})", level_str));
912                                         task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
913                                         task.SetParameterValue ("Properties",
914                                                 string.Format ("Configuration=%(Configuration); Platform=%(Platform); BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)"));
915                                         if (buildTarget != "Build")
916                                                 task.SetParameterValue ("Targets", buildTarget);
917                                         //FIXME: change this to BuildInParallel=true, when parallel
918                                         //       build support gets added
919                                         task.SetParameterValue ("RunEachTargetSeparately", "true");
920                                         if (is_build_or_rebuild)
921                                                 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
922
923                                         level_str = String.Format ("SkipLevel{0}", i);
924                                         task = t.AddNewTask ("Message");
925                                         task.Condition = String.Format ("'@({0})' != ''", level_str);
926                                         task.SetParameterValue ("Text",
927                                                 String.Format ("The project '%({0}.Identity)' is disabled for solution " +
928                                                         "configuration '$(Configuration)|$(Platform)'.", level_str));
929
930                                         level_str = String.Format ("MissingConfigLevel{0}", i);
931                                         task = t.AddNewTask ("Warning");
932                                         task.Condition = String.Format ("'@({0})' != ''", level_str);
933                                         task.SetParameterValue ("Text",
934                                                 String.Format ("The project configuration for project '%({0}.Identity)' " +
935                                                         "corresponding to the solution configuration " +
936                                                         "'$(Configuration)|$(Platform)' was not found.", level_str));
937                                 }
938
939                                 // "build" website projects also
940                                 StringBuilder w_targets = new StringBuilder ();
941                                 foreach (ProjectInfo info in websiteProjectInfos) {
942                                         if (w_targets.Length > 0)
943                                                 w_targets.Append (";");
944                                         w_targets.Append (GetTargetNameForProject (info.Name, buildTarget));
945                                 }
946
947                                 task = t.AddNewTask ("CallTarget");
948                                 task.SetParameterValue ("Targets", w_targets.ToString ());
949                                 task.SetParameterValue ("RunEachTargetSeparately", "true");
950                         }
951                 }
952
953                 // Sorts the ProjectInfo dependency graph, to obtain
954                 // a series of build levels with projects. Projects
955                 // in each level can be run parallel (no inter-dependency).
956                 static List<T>[] TopologicalSort<T> (IEnumerable<T> items) where T: ProjectInfo
957                 {
958                         IList<T> allItems;
959                         allItems = items as IList<T>;
960                         if (allItems == null)
961                                 allItems = new List<T> (items);
962
963                         bool[] inserted = new bool[allItems.Count];
964                         bool[] triedToInsert = new bool[allItems.Count];
965                         int[] levels = new int [allItems.Count];
966
967                         int maxdepth = 0;
968                         for (int i = 0; i < allItems.Count; ++i) {
969                                 int d = Insert<T> (i, allItems, levels, inserted, triedToInsert);
970                                 if (d > maxdepth)
971                                         maxdepth = d;
972                         }
973
974                         // Separate out the project infos by build level
975                         List<T>[] infosByLevel = new List<T>[maxdepth];
976                         for (int i = 0; i < levels.Length; i ++) {
977                                 int level = levels [i] - 1;
978                                 if (infosByLevel [level] == null)
979                                         infosByLevel [level] = new List<T> ();
980
981                                 infosByLevel [level].Add (allItems [i]);
982                         }
983
984                         return infosByLevel;
985                 }
986
987                 // returns level# for the project
988                 static int Insert<T> (int index, IList<T> allItems, int[] levels, bool[] inserted, bool[] triedToInsert)
989                         where T: ProjectInfo
990                 {
991                         if (inserted [index])
992                                 return levels [index];
993
994                         if (triedToInsert[index])
995                                 throw new InvalidOperationException (String.Format (
996                                                 "Cyclic dependency involving project {0} found in the project dependency graph",
997                                                 allItems [index].Name));
998
999                         triedToInsert[index] = true;
1000                         ProjectInfo insertItem = allItems[index];
1001
1002                         int maxdepth = 0;
1003                         foreach (ProjectInfo dependency in insertItem.Dependencies.Values) {
1004                                 for (int j = 0; j < allItems.Count; ++j) {
1005                                         ProjectInfo checkItem = allItems [j];
1006                                         if (dependency.FileName == checkItem.FileName) {
1007                                                 int d = Insert (j, allItems, levels, inserted, triedToInsert);
1008                                                 maxdepth = d > maxdepth ? d : maxdepth;
1009                                                 break;
1010                                         }
1011                                 }
1012                         }
1013                         levels [index] = maxdepth + 1;
1014                         inserted [index] = true;
1015
1016                         return levels [index];
1017                 }
1018
1019                 public static IEnumerable<string> GetAllProjectFileNames (string solutionFile)
1020                 {
1021                         StreamReader reader = new StreamReader (solutionFile);
1022                         string line = reader.ReadToEnd ();
1023                         line = line.Replace ("\r\n", "\n");
1024                         string soln_dir = Path.GetDirectoryName (solutionFile);
1025
1026                         Match m = projectRegex.Match (line);
1027                         while (m.Success) {
1028                                 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
1029                                                 StringComparison.InvariantCultureIgnoreCase) != 0)
1030                                         yield return Path.Combine (soln_dir, m.Groups [3].Value).Replace ("\\", "/");
1031
1032                                 m = m.NextMatch ();
1033                         }
1034                 }
1035         }
1036 }