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