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