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