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