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