Example #1
0
        public static void AddProject(this SlnFile slnFile, string fullProjectPath)
        {
            if (string.IsNullOrEmpty(fullProjectPath))
            {
                throw new ArgumentException();
            }

            var relativeProjectPath = Path.GetRelativePath(
                PathUtility.EnsureTrailingSlash(slnFile.BaseDirectory),
                fullProjectPath);

            if (slnFile.Projects.Any((p) =>
                                     string.Equals(p.FilePath, relativeProjectPath, StringComparison.OrdinalIgnoreCase)))
            {
                Reporter.Output.WriteLine(string.Format(
                                              CommonLocalizableStrings.SolutionAlreadyContainsProject,
                                              slnFile.FullPath,
                                              relativeProjectPath));
            }
            else
            {
                ProjectInstance projectInstance = null;
                try
                {
                    projectInstance = new ProjectInstance(fullProjectPath);
                }
                catch (InvalidProjectFileException e)
                {
                    Reporter.Error.WriteLine(string.Format(
                                                 CommonLocalizableStrings.InvalidProjectWithExceptionMessage,
                                                 fullProjectPath,
                                                 e.Message));
                    return;
                }

                var slnProject = new SlnProject
                {
                    Id       = projectInstance.GetProjectId(),
                    TypeGuid = projectInstance.GetProjectTypeGuid(),
                    Name     = Path.GetFileNameWithoutExtension(relativeProjectPath),
                    FilePath = relativeProjectPath
                };

                slnFile.AddDefaultBuildConfigurations(slnProject);

                slnFile.AddSolutionFolders(slnProject);

                slnFile.Projects.Add(slnProject);

                Reporter.Output.WriteLine(
                    string.Format(CommonLocalizableStrings.ProjectAddedToTheSolution, relativeProjectPath));
            }
        }
Example #2
0
        public void SingleProject()
        {
            SlnProject projectA = new SlnProject
            {
                FullPath        = GetTempFileName(),
                Name            = "ProjectA",
                ProjectGuid     = new Guid("C95D800E-F016-4167-8E1B-1D3FF94CE2E2"),
                ProjectTypeGuid = new Guid("88152E7E-47E3-45C8-B5D3-DDB15B2F0435"),
                IsMainProject   = true,
            };

            ValidateProjectInSolution(projectA);
        }
Example #3
0
        public void LotsOfProjects()
        {
            const int projectCount = 1000;

            SlnProject[] projects = new SlnProject[projectCount];

            for (int i = 0; i < projectCount; i++)
            {
                projects[i] = new SlnProject(GetTempFileName(), $"Project{i:D6}", Guid.NewGuid().ToSolutionString(), Guid.NewGuid().ToSolutionString(), isMainProject: i == 0);
            }

            ValidateProjectInSolution(projects);
        }
Example #4
0
        /// <inheritdoc cref="Task.Execute()" />
        public override bool Execute()
        {
            ISlnGenLogger logger = new TaskLogger(BuildEngine);

            if (BuildingSolutionFile)
            {
                if (!File.Exists(SolutionFileFullPath))
                {
                    Log.LogError($"Could not find part of the path '{SolutionFileFullPath}'.");
                }
            }
            else
            {
                IDictionary <string, string> globalProperties = GetGlobalProperties();

                // Load up the full project closure
                ProjectCollection projectCollection = SlnGenUtility.LoadProjectsAndReferences(
                    globalProperties,
                    ToolsVersion,
                    BuildEngine,
                    CollectStats,
                    ProjectFullPath,
                    ProjectReferences,
                    logger);

                // Return if loading projects logged any errors
                if (!Log.HasLoggedErrors)
                {
                    SlnGenUtility.GenerateSolutionFile(
                        projectCollection,
                        SolutionFileFullPath,
                        ProjectFullPath,
                        SlnProject.GetCustomProjectTypeGuids(CustomProjectTypeGuids),
                        Folders,
                        GetSolutionItems(),
                        logger);
                }
            }

            if (!Log.HasLoggedErrors && ShouldLaunchVisualStudio)
            {
                SlnGenUtility.LaunchVisualStudio(
                    DevEnvFullPath,
                    UseShellExecute,
                    SolutionFileFullPath,
                    logger);
            }

            return(!Log.HasLoggedErrors);
        }
            public SlnProject AddProject(string name)
            {
                SlnProject project = new SlnProject
                {
                    FullPath        = Path.Combine(this.FullPath, name) + ".csproj",
                    Name            = name,
                    ProjectGuid     = Guid.NewGuid(),
                    ProjectTypeGuid = SlnProject.DefaultLegacyProjectTypeGuid,
                };

                this.Projects.Add(project);

                return(project);
            }
Example #6
0
        public static void AddSolutionFolders(this SlnFile slnFile, SlnProject slnProject)
        {
            if (slnProject == null)
            {
                throw new ArgumentException();
            }

            var solutionFolders = slnProject.GetSolutionFoldersFromProject();

            if (solutionFolders.Any())
            {
                var nestedProjectsSection = slnFile.Sections.GetOrCreateSection(
                    "NestedProjects",
                    SlnSectionType.PreProcess);

                var pathToGuidMap = slnFile.GetSolutionFolderPaths(nestedProjectsSection.Properties);

                string parentDirGuid           = null;
                var    solutionFolderHierarchy = string.Empty;
                foreach (var dir in solutionFolders)
                {
                    solutionFolderHierarchy = Path.Combine(solutionFolderHierarchy, dir);
                    if (pathToGuidMap.ContainsKey(solutionFolderHierarchy))
                    {
                        parentDirGuid = pathToGuidMap[solutionFolderHierarchy];
                    }
                    else
                    {
                        var solutionFolder = new SlnProject
                        {
                            Id       = Guid.NewGuid().ToString("B").ToUpper(),
                            TypeGuid = ProjectTypeGuids.SolutionFolderGuid,
                            Name     = dir,
                            FilePath = dir
                        };

                        slnFile.Projects.Add(solutionFolder);

                        if (parentDirGuid != null)
                        {
                            nestedProjectsSection.Properties[solutionFolder.Id] = parentDirGuid;
                        }
                        parentDirGuid = solutionFolder.Id;
                    }
                }

                nestedProjectsSection.Properties[slnProject.Id] = parentDirGuid;
            }
        }
Example #7
0
        public static IList <string> GetSolutionFoldersFromProject(this SlnProject project)
        {
            var currentDirString = $".{Path.DirectorySeparatorChar}";

            var directoryPath = Path.GetDirectoryName(project.FilePath);

            if (directoryPath.StartsWith(currentDirString))
            {
                directoryPath = directoryPath.Substring(currentDirString.Length);
            }

            return(directoryPath.StartsWith("..")
                ? new List <string>()
                : new List <string>(directoryPath.Split(Path.DirectorySeparatorChar)));
        }
Example #8
0
        private static void AddProject(SlnFile slnFile, string projectPath)
        {
            var projectPathNormalized = PathUtility.GetPathWithBackSlashes(projectPath);

            if (slnFile.Projects.Any((p) =>
                                     string.Equals(p.FilePath, projectPathNormalized, StringComparison.OrdinalIgnoreCase)))
            {
                Reporter.Output.WriteLine(string.Format(
                                              CommonLocalizableStrings.SolutionAlreadyContainsProject,
                                              slnFile.FullPath,
                                              projectPath));
            }
            else
            {
                string projectGuidString = null;
                if (File.Exists(projectPath))
                {
                    var projectElement = ProjectRootElement.Open(
                        projectPath,
                        new ProjectCollection(),
                        preserveFormatting: true);

                    var projectGuidProperty = projectElement.Properties.Where((p) =>
                                                                              string.Equals(p.Name, "ProjectGuid", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

                    if (projectGuidProperty != null)
                    {
                        projectGuidString = projectGuidProperty.Value;
                    }
                }

                var projectGuid = (projectGuidString == null)
                    ? Guid.NewGuid()
                    : new Guid(projectGuidString);

                var slnProject = new SlnProject
                {
                    Id       = projectGuid.ToString("B").ToUpper(),
                    TypeGuid = ProjectTypeGuids.CPSProjectTypeGuid,
                    Name     = Path.GetFileNameWithoutExtension(projectPath),
                    FilePath = projectPathNormalized
                };

                slnFile.Projects.Add(slnProject);
                Reporter.Output.WriteLine(
                    string.Format(CommonLocalizableStrings.ProjectAddedToTheSolution, projectPath));
            }
        }
Example #9
0
        public void CustomConfigurationAndPlatforms_IgnoresInvalidValues()
        {
            SlnProject project = new SlnProject
            {
                Configurations  = new[] { "Debug", "Release" },
                FullPath        = GetTempFileName(),
                IsMainProject   = true,
                Name            = "ProjectA",
                Platforms       = new[] { "AnyCPU" },
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
            };

            SlnFile slnFile = new SlnFile()
            {
                Configurations = new[] { "Debug" },
                Platforms      = new[] { "Any CPU", "AnyCPU", "Invalid", "x64", "x86", "X64", "X86" },
            };

            slnFile.AddProjects(new[] { project });

            string solutionFilePath = GetTempFileName();

            slnFile.Save(solutionFilePath, useFolders: false);

            SolutionFile solutionFile = SolutionFile.Parse(solutionFilePath);

            solutionFile.SolutionConfigurations
            .Select(i => i.FullName)
            .ShouldBe(
                new[]
            {
                "Debug|Any CPU",
                "Debug|x64",
                "Debug|x86",
            });

            ProjectInSolution projectInSolution = solutionFile.ProjectsByGuid[project.ProjectGuid.ToSolutionString()];

            projectInSolution.AbsolutePath.ShouldBe(project.FullPath);

            projectInSolution.ProjectConfigurations.Keys.ShouldBe(new[] { "Debug|Any CPU", "Debug|x64", "Debug|x86" });

            ValidateSolutionPlatformAndConfiguration(projectInSolution.ProjectConfigurations, "Debug|Any CPU", "Debug", "AnyCPU");
            ValidateSolutionPlatformAndConfiguration(projectInSolution.ProjectConfigurations, "Debug|x64", "Debug", "AnyCPU");
            ValidateSolutionPlatformAndConfiguration(projectInSolution.ProjectConfigurations, "Debug|x86", "Debug", "AnyCPU");
        }
        public void HierarchyWithCollapsedFoldersIsCorrectlyFormed()
        {
            DummyFolder root = DummyFolder.CreateRoot(@"D:\zoo\foo");
            DummyFolder bar  = root.AddSubDirectory("bar");
            DummyFolder qux  = bar.AddSubDirectory("qux");
            SlnProject  baz  = qux.AddProjectWithDirectory("baz");
            SlnProject  baz1 = qux.AddProjectWithDirectory("baz1");
            SlnProject  baz2 = qux.AddProjectWithDirectory("baz2");
            SlnProject  bar1 = root.AddProjectWithDirectory("bar1");
            SlnProject  baz3 = root
                               .AddSubDirectory("foo1")
                               .AddSubDirectory("foo2")
                               .AddProjectWithDirectory("baz3");

            DummyFolder rootExpected   = DummyFolder.CreateRoot(@"D:\zoo\foo");
            DummyFolder barQuxExpected = rootExpected.AddSubDirectory($"bar {SlnHierarchy.Separator} qux");

            barQuxExpected.Projects.Add(baz);
            barQuxExpected.Projects.Add(baz1);
            barQuxExpected.Projects.Add(baz2);
            rootExpected.Projects.Add(bar1);
            rootExpected.AddSubDirectory($"foo1 {SlnHierarchy.Separator} foo2 {SlnHierarchy.Separator} baz3").Projects.Add(baz3);

            SlnHierarchy hierarchy = new SlnHierarchy(root.GetAllProjects(), collapseFolders: true);

            SlnFolder[]   resultFolders   = hierarchy.Folders.OrderBy(f => f.FullPath).ToArray();
            DummyFolder[] expectedFolders = rootExpected.GetAllFolders().OrderBy(f => f.FullPath).ToArray();

            resultFolders.Length.ShouldBe(expectedFolders.Length);

            for (int i = 0; i < resultFolders.Length; i++)
            {
                SlnFolder   resultFolder   = resultFolders[i];
                DummyFolder expectedFolder = expectedFolders[i];

                resultFolder.Name.ShouldBe(expectedFolder.Name);

                // Verify that expected and results projects match
                resultFolder.Projects.Count.ShouldBe(expectedFolder.Projects.Count);
                resultFolder.Projects.ShouldAllBe(p => expectedFolder.Projects.Contains(p));

                // Verify that expected and results child folders match
                resultFolder.Folders.Count.ShouldBe(expectedFolder.Folders.Count);
                resultFolder.Folders.ShouldAllBe(p => expectedFolder.Folders.Exists(f => f.Name == p.Name));
            }
        }
Example #11
0
        public void ConfigurationsAndPlatformsWithGlobalProperties()
        {
            Dictionary <string, string> globalProperties = new Dictionary <string, string>
            {
                ["Configuration"] = "Mix",
                ["Platform"]      = "x86",
            };

            using (TestProject testProject = TestProject.Create(globalProperties))
            {
                SlnProject slnProject = SlnProject.FromProject(testProject.Project, new Dictionary <string, Guid>(), true);

                slnProject.Configurations.ShouldBe(new[] { "Debug", "Mix", "Release" }, ignoreOrder: true);

                slnProject.Platforms.ShouldBe(new[] { "amd64", "Any CPU", "x86", "x64" }, ignoreOrder: true);
            }
        }
Example #12
0
        private IDotNetSolutionFolder CreateSolutionFolderAtRoot(string folderName)
        {
            var newProject = new SlnProject
            {
                Id       = Guid.NewGuid().ToId(),
                TypeGuid = KnownProjectTypeGuids.SolutionFolderProject.ToId(),
                Name     = folderName,
                FilePath = folderName
            };

            SlnFile.Projects.Add(newProject);

            var projectInstance = new DotNetProjectInstance(this, newProject);
            var solutionFolder  = new DotNetSolutionFolder(projectInstance);

            _allProjects.Add(solutionFolder);

            return(solutionFolder);
        }
Example #13
0
        public void SolutionItems()
        {
            TestLogger logger = new TestLogger();

            string[] items =
            {
                Path.Combine(TestRootPath, "foo"),
                Path.Combine(TestRootPath, "bar"),
            };

            Project project = ProjectCreator.Create(
                path: Path.Combine(TestRootPath, "foo.proj"))
                              .ItemInclude(MSBuildItemNames.SlnGenSolutionItem, "foo")
                              .ItemInclude(MSBuildItemNames.SlnGenSolutionItem, "bar");

            SlnProject.GetSolutionItems(project, logger, path => true).ShouldBe(items);

            logger.LowImportanceMessages.ShouldBeEmpty();
        }
Example #14
0
        public void GetPlatformsAndConfigurationsFromCppProject()
        {
            Project project = ProjectCreator.Create()
                              .ItemInclude(
                "ProjectConfiguration",
                "ConfigA|PlatformA",
                metadata: new Dictionary <string, string>
            {
                ["Configuration"] = "ConfigA",
                ["Platform"]      = "PlatformA",
            })
                              .ItemInclude(
                "ProjectConfiguration",
                "ConfigA|PlatformB",
                metadata: new Dictionary <string, string>
            {
                ["Configuration"] = "ConfigA",
                ["Platform"]      = "PlatformB",
            })
                              .ItemInclude(
                "ProjectConfiguration",
                "ConfigB|PlatformA",
                metadata: new Dictionary <string, string>
            {
                ["Configuration"] = "ConfigB",
                ["Platform"]      = "PlatformA",
            })
                              .ItemInclude(
                "ProjectConfiguration",
                "ConfigB|PlatformB",
                metadata: new Dictionary <string, string>
            {
                ["Configuration"] = "ConfigB",
                ["Platform"]      = "PlatformB",
            })
                              .Save(GetTempFileName(".vcxproj"));

            SlnProject slnProject = SlnProject.FromProject(project, new Dictionary <string, Guid>());

            slnProject.Configurations.ShouldBe(new[] { "ConfigA", "ConfigB" });
            slnProject.Platforms.ShouldBe(new[] { "PlatformA", "PlatformB" });
        }
Example #15
0
        public void MultipleProjects()
        {
            SlnProject projectA = new SlnProject
            {
                FullPath        = GetTempFileName(),
                Name            = "ProjectA",
                ProjectGuid     = new Guid("C95D800E-F016-4167-8E1B-1D3FF94CE2E2"),
                ProjectTypeGuid = new Guid("88152E7E-47E3-45C8-B5D3-DDB15B2F0435"),
                IsMainProject   = true,
            };

            SlnProject projectB = new SlnProject
            {
                FullPath        = GetTempFileName(),
                Name            = "ProjectB",
                ProjectGuid     = new Guid("EAD108BE-AC70-41E6-A8C3-450C545FDC0E"),
                ProjectTypeGuid = new Guid("F38341C3-343F-421A-AE68-94CD9ADCD32F"),
            };

            ValidateProjectInSolution(projectA, projectB);
        }
Example #16
0
        public void LotsOfProjects()
        {
            const int projectCount = 1000;

            SlnProject[] projects = new SlnProject[projectCount];

            string[] configurations = { "Debug", "Release" };
            string[] platforms      = { "x64", "x86", "Any CPU", "amd64" };

            Random randomGenerator = new Random(Guid.NewGuid().GetHashCode());

            for (int i = 0; i < projectCount; i++)
            {
                // pick random and shuffled configurations and platforms
                List <string> projectConfigurations = configurations.OrderBy(a => Guid.NewGuid()).Take(randomGenerator.Next(1, configurations.Length)).ToList();
                List <string> projectPlatforms      = platforms.OrderBy(a => Guid.NewGuid()).Take(randomGenerator.Next(1, platforms.Length)).ToList();
                projects[i] = new SlnProject(GetTempFileName(), $"Project{i:D6}", Guid.NewGuid(), Guid.NewGuid(), projectConfigurations, projectPlatforms, isMainProject: i == 0, isDeployable: false);
            }

            ValidateProjectInSolution(projects);
        }
Example #17
0
        private void AddDefaultBuildConfigurations(SlnFile slnFile, SlnProject slnProject)
        {
            var defaultConfigurations = new List <string>()
            {
                "Debug|Any CPU",
                "Debug|x64",
                "Debug|x86",
                "Release|Any CPU",
                "Release|x64",
                "Release|x86",
            };

            // NOTE: The order you create the sections determines the order they are written to the sln
            // file. In the case of an empty sln file, in order to make sure the solution configurations
            // section comes first we need to add it first. This doesn't affect correctness but does
            // stop VS from re-ordering things later on. Since we are keeping the SlnFile class low-level
            // it shouldn't care about the VS implementation details. That's why we handle this here.
            AddDefaultSolutionConfigurations(defaultConfigurations, slnFile.SolutionConfigurationsSection);
            AddDefaultProjectConfigurations(
                defaultConfigurations,
                slnFile.ProjectConfigurationsSection.GetOrCreatePropertySet(slnProject.Id));
        }
Example #18
0
        private SlnProject CreateAndValidateProject(bool isMainProject = false, string expectedGuid = null, string expectedName = null, string extension = ".csproj", IDictionary <string, string> globalProperties = null)
        {
            Project expectedProject = CreateProject(expectedGuid, expectedName, extension, globalProperties);

            SlnProject actualProject = SlnProject.FromProject(expectedProject, new Dictionary <string, Guid>(), isMainProject);

            actualProject.FullPath.ShouldBe(expectedProject.FullPath);

            if (!string.IsNullOrWhiteSpace(expectedName))
            {
                actualProject.Name.ShouldBe(expectedName);
            }

            if (expectedGuid != null)
            {
                actualProject.ProjectGuid.ToSolutionString().ShouldBe(expectedGuid);
            }

            actualProject.IsMainProject.ShouldBe(isMainProject);

            return(actualProject);
        }
Example #19
0
        public void ExistingSolutionIsReused()
        {
            string path = GetTempFileName();

            Guid projectGuid = Guid.Parse("7BE5A5CA-169D-4955-AB4D-EDDE662F4AE5");

            SlnProject project = new SlnProject
            {
                FullPath        = GetTempFileName(),
                Name            = "Project",
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
                IsMainProject   = true,
            };

            SlnFile slnFile = new SlnFile
            {
                ExistingProjectGuids = new Dictionary <string, Guid>
                {
                    [project.FullPath] = projectGuid,
                },
                SolutionGuid = Guid.NewGuid(),
            };

            slnFile.AddProjects(new[] { project });

            slnFile.Save(path, useFolders: false);

            SlnFile.TryParseExistingSolution(path, out Guid solutionGuid, out _).ShouldBeTrue();

            solutionGuid.ShouldBe(slnFile.SolutionGuid);

            SolutionFile solutionFile = SolutionFile.Parse(path);

            ProjectInSolution projectInSolution = solutionFile.ProjectsInOrder.ShouldHaveSingleItem();

            projectInSolution.ProjectGuid.ShouldBe(projectGuid.ToString("B").ToUpperInvariant());
        }
Example #20
0
        public void GetProjectTypeGuidLegacyProject(string extension)
        {
            SlnProject actualProject = CreateAndValidateProject(extension: extension);

            switch (extension)
            {
            case "":
                actualProject.ProjectTypeGuid.ShouldBe(SlnProject.DefaultLegacyProjectTypeGuid);
                break;

            case ".csproj":
                actualProject.ProjectTypeGuid.ShouldBe(new Guid("FAE04EC0-301F-11D3-BF4B-00C04F79EFBC"));
                break;

            case ".vbproj":
                actualProject.ProjectTypeGuid.ShouldBe(new Guid("F184B08F-C81C-45F6-A57F-5ABD9991F28F"));
                break;

            default:
                actualProject.ProjectTypeGuid.ShouldBe(SlnProject.KnownProjectTypeGuids[extension]);
                break;
            }
        }
Example #21
0
        private void AddProject(SlnFile slnFile, string fullProjectPath)
        {
            var relativeProjectPath = PathUtility.GetRelativePath(
                PathUtility.EnsureTrailingSlash(slnFile.BaseDirectory),
                fullProjectPath);

            if (slnFile.Projects.Any((p) =>
                                     string.Equals(p.FilePath, relativeProjectPath, StringComparison.OrdinalIgnoreCase)))
            {
                Reporter.Output.WriteLine(string.Format(
                                              CommonLocalizableStrings.SolutionAlreadyContainsProject,
                                              slnFile.FullPath,
                                              relativeProjectPath));
            }
            else
            {
                var projectInstance = new ProjectInstance(fullProjectPath);

                var slnProject = new SlnProject
                {
                    Id       = projectInstance.GetProjectId(),
                    TypeGuid = projectInstance.GetProjectTypeGuid(),
                    Name     = Path.GetFileNameWithoutExtension(relativeProjectPath),
                    FilePath = relativeProjectPath
                };

                AddDefaultBuildConfigurations(slnFile, slnProject);

                AddSolutionFolders(slnFile, slnProject);

                slnFile.Projects.Add(slnProject);

                Reporter.Output.WriteLine(
                    string.Format(CommonLocalizableStrings.ProjectAddedToTheSolution, relativeProjectPath));
            }
        }
Example #22
0
        private void GenerateSolutionFile(ICollection <Project> projects)
        {
            if (String.IsNullOrWhiteSpace(SolutionFileFullPath))
            {
                SolutionFileFullPath = Path.ChangeExtension(ProjectFullPath, ".sln");
            }

            Dictionary <string, string> customProjectTypeGuids = ParseCustomProjectTypeGuids();

            LogMessageHigh($"Generating Visual Studio solution \"{SolutionFileFullPath}\" ...");

            if (customProjectTypeGuids.Count > 0)
            {
                LogMessageLow("Custom Project Type GUIDs:");
                foreach (KeyValuePair <string, string> item in customProjectTypeGuids)
                {
                    LogMessageLow("  {0} = {1}", item.Key, item.Value);
                }
            }

            SlnFile solution = new SlnFile(projects.Where(ShouldIncludeInSolution).Select(p => SlnProject.FromProject(p, customProjectTypeGuids, p.FullPath == ProjectFullPath)));

            solution.AddSolutionItems(GetSolutionItems());

            solution.Save(SolutionFileFullPath);
        }
		void WriteFolderFiles (SlnProject proj, SolutionFolder folder)
		{
			if (folder.Files.Count > 0) {
				var sec = proj.Sections.GetOrCreateSection ("SolutionItems", SlnSectionType.PreProcess);
				sec.Properties.Clear ();
				foreach (FilePath f in folder.Files) {
					string relFile = MSBuildProjectService.ToMSBuildPathRelative (folder.ParentSolution.ItemDirectory, f);
					sec.Properties.SetValue (relFile, relFile);
				}
			} else
				proj.Sections.RemoveSection ("SolutionItems");
		}
Example #24
0
        public void CustomConfigurationAndPlatforms()
        {
            SlnProject projectA = new SlnProject
            {
                Configurations  = new[] { "Debug", "Release" },
                FullPath        = GetTempFileName(),
                IsMainProject   = true,
                Name            = "ProjectA",
                Platforms       = new[] { "AnyCPU", "x64", "x86" },
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
            };

            SlnProject projectB = new SlnProject
            {
                Configurations  = new[] { "Debug", "Release" },
                FullPath        = GetTempFileName(),
                IsMainProject   = true,
                Name            = "ProjectB",
                Platforms       = new[] { "x64", "x86" },
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
            };

            SlnProject projectC = new SlnProject
            {
                Configurations  = new[] { "Debug", "Release" },
                FullPath        = GetTempFileName(),
                IsMainProject   = true,
                Name            = "ProjectC",
                Platforms       = new[] { "amd64" },
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
            };

            SlnProject projectD = new SlnProject
            {
                Configurations  = new[] { "Debug", "Release" },
                FullPath        = GetTempFileName(),
                IsMainProject   = true,
                Name            = "ProjectD",
                Platforms       = new[] { "Razzle" },
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
            };

            SlnProject projectE = new SlnProject
            {
                Configurations  = new[] { "Release" },
                FullPath        = GetTempFileName(),
                IsMainProject   = true,
                Name            = "ProjectE",
                Platforms       = new[] { "AnyCPU" },
                ProjectGuid     = Guid.NewGuid(),
                ProjectTypeGuid = Guid.NewGuid(),
            };

            SlnFile slnFile = new SlnFile()
            {
                Configurations = new[] { "Debug" },
                Platforms      = new[] { "Any CPU" },
            };

            slnFile.AddProjects(new[] { projectA, projectB, projectC, projectD, projectE });

            string solutionFilePath = GetTempFileName();

            slnFile.Save(solutionFilePath, useFolders: false);

            SolutionFile solutionFile = SolutionFile.Parse(solutionFilePath);

            ValidateSolutionPlatformAndConfiguration(projectA, solutionFile, "Debug", "AnyCPU");

            ValidateSolutionPlatformAndConfiguration(projectB, solutionFile, "Debug", "x64");

            ValidateSolutionPlatformAndConfiguration(projectC, solutionFile, "Debug", "amd64");

            ValidateSolutionPlatformAndConfiguration(projectD, solutionFile, "Debug", "Razzle", expectedIncludeInBuild: false);

            ValidateSolutionPlatformAndConfiguration(projectE, solutionFile, "Release", "AnyCPU", expectedIncludeInBuild: false);
        }
Example #25
0
        public void GetProjectGuidLegacyProjectSystem()
        {
            SlnProject actualProject = CreateAndValidateProject(expectedGuid: "{C69AC4B3-A0E1-40FC-94AB-C0F2E1F8D779}");

            actualProject.ProjectTypeGuid.ShouldBe(SlnProject.DefaultLegacyProjectTypeGuid);
        }
Example #26
0
        public void IsDeployable(string isDeployable, string projectExtension, bool expected)
        {
            SlnProject project = CreateAndValidateProject(extension: projectExtension, isDeployable: isDeployable);

            project.IsDeployable.ShouldBe(expected);
        }
		void DeserializeSolutionItem (ProgressMonitor monitor, Solution sln, SolutionFolderItem item, SlnProject proj)
		{
			// Deserialize the object
			var sec = proj.Sections.GetSection ("MonoDevelopProperties");
			if (sec == null)
				return;

			sln.ReadSolutionFolderItemData (monitor, sec.Properties, item);
		}
Example #28
0
        private int Generate()
        {
            using (SlnGenTelemetryData telemetryData = new SlnGenTelemetryData
            {
                DevEnvFullPathSpecified = !_programArguments.DevEnvFullPath.IsNullOrWhitespace(),
                EntryProjectCount = _programArguments.Projects.Length,
                Folders = _programArguments.Folders,
                LaunchVisualStudio = _programArguments.LaunchVisualStudio,
                SolutionFileFullPathSpecified = !_programArguments.SolutionFileFullPath.IsNullOrWhitespace(),
                UseBinaryLogger = _programArguments.BinaryLogger.HasValue,
                UseFileLogger = _programArguments.FileLoggerParameters.HasValue,
                UseShellExecute = _programArguments.UseShellExecute,
            })
            {
                _logger.LogMessageHigh("Loading project references...");

                Stopwatch sw = Stopwatch.StartNew();

                IDictionary <string, string> globalProperties = new Dictionary <string, string>
                {
                    ["BuildingProject"] = "false",
                    ["DesignTimeBuild"] = "true",
                    ["ExcludeRestorePackageImports"] = "true",
                };

                ICollection <ProjectGraphEntryPoint> entryProjects = _programArguments.GetProjects(_logger).Select(i => new ProjectGraphEntryPoint(i, globalProperties)).ToList();

                _ = new ProjectGraph(entryProjects, _projectCollection, CreateProjectInstance);

                sw.Stop();

                _logger.LogMessageNormal($"Loaded {_projectCollection.LoadedProjects.Count} project(s) in {sw.ElapsedMilliseconds:N2}ms");

                telemetryData.ProjectEvaluationMilliseconds = sw.ElapsedMilliseconds;
                telemetryData.ProjectEvaluationCount        = _projectCollection.LoadedProjects.Count;

                Project project = _projectCollection.LoadedProjects.First();

                Dictionary <string, Guid> customProjectTypeGuids = SlnProject.GetCustomProjectTypeGuids(project.GetItems("SlnGenCustomProjectTypeGuid").Select(i => new MSBuildProjectItem(i)));

                IReadOnlyCollection <string> solutionItems = SlnFile.GetSolutionItems(project.GetItems("SlnGenSolutionItem").Select(i => new MSBuildProjectItem(i)), _logger).ToList();

                telemetryData.CustomProjectTypeGuidCount = customProjectTypeGuids.Count;

                telemetryData.SolutionItemCount = solutionItems.Count;

                string solutionFileFullPath = SlnGenUtility.GenerateSolutionFile(
                    _projectCollection,
                    solutionFileFullPath: null,
                    projectFileFullPath: entryProjects.First().ProjectFile,
                    customProjectTypeGuids: customProjectTypeGuids,
                    folders: _programArguments.Folders,
                    solutionItems: solutionItems,
                    logger: _logger);

                if (_programArguments.LaunchVisualStudio)
                {
                    SlnGenUtility.LaunchVisualStudio(_programArguments.DevEnvFullPath, _programArguments.UseShellExecute, solutionFileFullPath, _logger);
                }

                return(_logger.HasLoggedErrors ? 1 : 0);
            }
        }
Example #29
0
 public static IProjectType GetProjectType(this SlnProject solutionModel)
 {
     return(Guid.Parse(solutionModel.TypeGuid).GetProjectType());
 }
Example #30
0
        public void SingleProject()
        {
            SlnProject projectA = new SlnProject(GetTempFileName(), "ProjectA", new Guid("C95D800E-F016-4167-8E1B-1D3FF94CE2E2"), new Guid("88152E7E-47E3-45C8-B5D3-DDB15B2F0435"), new[] { "Debug" }, new[] { "x64" }, isMainProject: true, isDeployable: false);

            ValidateProjectInSolution(projectA);
        }
		List<string> ReadSolutionItemDependencies (SlnProject proj)
		{
			// Find a project section of type ProjectDependencies
			var sec = proj.Sections.GetSection ("ProjectDependencies");
			if (sec == null)
				return null;

			return sec.Properties.Keys.ToList ();
		}
		IEnumerable<string> ReadFolderFiles (SlnProject proj)
		{
			// Find a solution item section of type SolutionItems
			var sec = proj.Sections.GetSection ("SolutionItems");
			if (sec == null)
				return new string[0];

			return sec.Properties.Keys.ToList ();
		}
Example #33
0
        public static void AddProject(this SlnFile slnFile, string fullProjectPath)
        {
            if (string.IsNullOrEmpty(fullProjectPath))
            {
                throw new ArgumentException();
            }

            var relativeProjectPath = PathUtility.GetRelativePath(
                PathUtility.EnsureTrailingSlash(slnFile.BaseDirectory),
                fullProjectPath);

            if (slnFile.Projects.Any((p) =>
                                     string.Equals(p.FilePath, relativeProjectPath, StringComparison.OrdinalIgnoreCase)))
            {
                Reporter.Output.WriteLine(string.Format(
                                              CommonLocalizableStrings.SolutionAlreadyContainsProject,
                                              slnFile.FullPath,
                                              relativeProjectPath));
            }
            else
            {
                ProjectRootElement rootElement     = null;
                ProjectInstance    projectInstance = null;
                try
                {
                    rootElement     = ProjectRootElement.Open(fullProjectPath);
                    projectInstance = new ProjectInstance(rootElement);
                }
                catch (InvalidProjectFileException e)
                {
                    Reporter.Error.WriteLine(string.Format(
                                                 CommonLocalizableStrings.InvalidProjectWithExceptionMessage,
                                                 fullProjectPath,
                                                 e.Message));
                    return;
                }

                var slnProject = new SlnProject
                {
                    Id       = projectInstance.GetProjectId(),
                    TypeGuid = rootElement.GetProjectTypeGuid() ?? projectInstance.GetDefaultProjectTypeGuid(),
                    Name     = Path.GetFileNameWithoutExtension(relativeProjectPath),
                    FilePath = relativeProjectPath
                };

                if (string.IsNullOrEmpty(slnProject.TypeGuid))
                {
                    Reporter.Error.WriteLine(
                        string.Format(
                            CommonLocalizableStrings.UnsupportedProjectType,
                            projectInstance.FullPath));
                    return;
                }

                // NOTE: The order you create the sections determines the order they are written to the sln
                // file. In the case of an empty sln file, in order to make sure the solution configurations
                // section comes first we need to add it first. This doesn't affect correctness but does
                // stop VS from re-ordering things later on. Since we are keeping the SlnFile class low-level
                // it shouldn't care about the VS implementation details. That's why we handle this here.
                slnFile.AddDefaultBuildConfigurations();

                slnFile.MapSolutionConfigurationsToProject(
                    projectInstance,
                    slnFile.ProjectConfigurationsSection.GetOrCreatePropertySet(slnProject.Id));

                slnFile.AddSolutionFolders(slnProject);

                slnFile.Projects.Add(slnProject);

                Reporter.Output.WriteLine(
                    string.Format(CommonLocalizableStrings.ProjectAddedToTheSolution, relativeProjectPath));
            }
        }
Example #34
0
 private static bool ContainsSolutionItems(SlnProject project)
 {
     return project.Sections
         .GetSection("SolutionItems", SlnSectionType.PreProcess) != null;
 }