private void MigrateAndBuild(string groupName, string projectName, string subdirProjectTypeGuid)
        {
            var projectDirectory = TestAssets
                                   .Get(groupName, projectName)
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root;

            var solutionRelPath = Path.Combine("TestApp", "TestApp.sln");

            new DotnetCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute($"migrate \"{solutionRelPath}\"")
            .Should().Pass();

            new DotnetCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute($"restore \"{Path.Combine("TestApp", "TestApp.csproj")}\"")
            .Should().Pass();

            new DotnetCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute($"build \"{solutionRelPath}\"")
            .Should().Pass();

            SlnFile slnFile = SlnFile.Read(Path.Combine(projectDirectory.FullName, solutionRelPath));

            slnFile.Projects.Count.Should().Be(3);

            var slnProject = slnFile.Projects.Where((p) => p.Name == "TestApp").Single();

            slnProject.TypeGuid.Should().Be(ProjectTypeGuids.CSharpProjectTypeGuid);
            slnProject.FilePath.Should().Be("TestApp.csproj");

            slnProject = slnFile.Projects.Where((p) => p.Name == "TestLibrary").Single();
            slnProject.TypeGuid.Should().Be(ProjectTypeGuids.CSharpProjectTypeGuid);
            slnProject.FilePath.Should().Be(Path.Combine("..", "TestLibrary", "TestLibrary.csproj"));

            slnProject = slnFile.Projects.Where((p) => p.Name == "subdir").Single();
            slnProject.TypeGuid.Should().Be(subdirProjectTypeGuid);
            slnProject.FilePath.Should().Be(Path.Combine("src", "subdir", "subdir.csproj"));
        }
Example #2
0
        public void WhenReferenceIsRemovedSlnBuilds()
        {
            var projectDirectory = TestAssets
                                   .Get("TestAppWithSlnAndCsprojToRemove")
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root
                                   .FullName;

            var     solutionPath = Path.Combine(projectDirectory, "App.sln");
            SlnFile slnFile      = SlnFile.Read(solutionPath);

            slnFile.Projects.Count.Should().Be(2);

            var projectToRemove = Path.Combine("Lib", "Lib.csproj");
            var cmd             = new DotnetCommand()
                                  .WithWorkingDirectory(projectDirectory)
                                  .ExecuteWithCapturedOutput($"sln remove {projectToRemove}");

            cmd.Should().Pass();

            new DotnetCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute($"restore App.sln")
            .Should().Pass();

            new DotnetCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute("build App.sln --configuration Release")
            .Should().Pass();

            var reasonString = "should be built in release mode, otherwise it means build configurations are missing from the sln file";

            var releaseDirectory = Directory.EnumerateDirectories(
                Path.Combine(projectDirectory, "App", "bin"),
                "Release",
                SearchOption.AllDirectories);

            releaseDirectory.Count().Should().Be(1, $"App {reasonString}");
            Directory.EnumerateFiles(releaseDirectory.Single(), "App.dll", SearchOption.AllDirectories)
            .Count().Should().Be(1, $"App {reasonString}");
        }
Example #3
0
        public void WhenGivenASolutionWithInvalidProjectSectionItThrows()
        {
            const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Project""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}""
EndProject
";

            var tmpFile = Temp.CreateFile();

            tmpFile.WriteAllText(SolutionFile);

            Action action = () =>
            {
                SlnFile.Read(tmpFile.Path);
            };

            action.ShouldThrow <InvalidSolutionFormatException>()
            .WithMessage("Invalid format in line 3: Project section is missing '(' when parsing the line starting at position 0");
        }
        public void WhenGivenASolutionWithInvalidProjectSectionItThrows()
        {
            const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Project""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}""
EndProject
";

            var tmpFile = Temp.CreateFile();

            tmpFile.WriteAllText(SolutionFile);

            Action action = () =>
            {
                SlnFile.Read(tmpFile.Path);
            };

            action.ShouldThrow <InvalidSolutionFormatException>()
            .WithMessage(FormatError(3, LocalizableStrings.ProjectParsingErrorFormatString, "(", 0));
        }
        public void WhenGivenASolutionWithSectionNotClosedItThrows()
        {
            const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
EndGlobal
";
            var          tmpFile      = Temp.CreateFile();

            tmpFile.WriteAllText(SolutionFile);

            Action action = () =>
            {
                SlnFile.Read(tmpFile.Path);
            };

            action.ShouldThrow <InvalidSolutionFormatException>()
            .WithMessage(FormatError(6, LocalizableStrings.ClosingSectionTagNotFoundError));
        }
        public void It_writes_an_sln_file()
        {
            var solutionDirectory =
                TestAssetsManager.CreateTestInstance("TestAppWithSln", callingMethod: "p").Path;

            var solutionFullPath = Path.Combine(solutionDirectory, "TestAppWithSln.sln");

            var slnFile = new SlnFile();

            slnFile.Read(solutionFullPath);

            slnFile.Projects.Count.Should().Be(1);
            var project = slnFile.Projects[0];

            project.Name.Should().Be("TestAppWithSln");
            project.Name = "New Project Name";
            project.FilePath.Should().Be("TestAppWithSln.xproj");
            project.FilePath = "New File Path";

            var newSolutionFullPath = Path.Combine(solutionDirectory, "TestAppWithSln_modified.sln");

            slnFile.Write(newSolutionFullPath);

            slnFile = new SlnFile();
            slnFile.Read(newSolutionFullPath);
            slnFile.FormatVersion.Should().Be("12.00");
            slnFile.ProductDescription.Should().Be("Visual Studio 14");
            slnFile.VisualStudioVersion.Should().Be("14.0.25420.1");
            slnFile.MinimumVisualStudioVersion.Should().Be("10.0.40219.1");
            slnFile.BaseDirectory.Should().Be(solutionDirectory);
            slnFile.FileName.FileName.Should().Be("TestAppWithSln_modified.sln");
            SlnFile.GetFileVersion(solutionFullPath).Should().Be("12.00");
            slnFile.Projects.Count.Should().Be(1);
            project = slnFile.Projects[0];
            project.Id.Should().Be("{0138CB8F-4AA9-4029-A21E-C07C30F425BA}");
            project.TypeGuid.Should().Be("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}");
            project.Name.Should().Be("New Project Name");
            project.FilePath.Should().Be("New File Path");
            slnFile.Projects.Count.Should().Be(1);
            project = slnFile.Projects[0];
        }
Example #7
0
        public void WhenDirectoryContainingProjectIsGivenProjectIsRemoved()
        {
            var projectDirectory = _testAssetsManager
                                   .CopyTestAsset("TestAppWithSlnAndCsprojToRemove")
                                   .WithSource()
                                   .Path;

            var     solutionPath = Path.Combine(projectDirectory, "App.sln");
            SlnFile slnFile      = SlnFile.Read(solutionPath);

            slnFile.Projects.Count.Should().Be(2);

            var cmd = new DotnetCommand(Log)
                      .WithWorkingDirectory(projectDirectory)
                      .Execute("sln", "remove", "Lib");

            cmd.Should().Pass();

            File.ReadAllText(solutionPath)
            .Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemove);
        }
Example #8
0
        public void WhenGivenASolutionWithMultipleGlobalSectionsItThrows()
        {
            const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Global
EndGlobal
Global
EndGlobal
";
            var          tmpFile      = Temp.CreateFile();

            tmpFile.WriteAllText(SolutionFile);

            Action action = () =>
            {
                SlnFile.Read(tmpFile.Path);
            };

            action.ShouldThrow <InvalidSolutionFormatException>()
            .WithMessage("Invalid format in line 5: Global section specified more than once");
        }
        public void WhenGivenASolutionWithInvalidSectionTypeItThrows()
        {
            const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Global
	GlobalSection(SolutionConfigurationPlatforms) = thisIsUnknown
	EndGlobalSection
EndGlobal
";
            var          tmpFile      = Temp.CreateFile();

            tmpFile.WriteAllText(SolutionFile);

            Action action = () =>
            {
                SlnFile.Read(tmpFile.Path);
            };

            action.ShouldThrow <InvalidSolutionFormatException>()
            .WithMessage(FormatError(4, LocalizableStrings.InvalidSectionTypeError, "thisIsUnknown"));
        }
Example #10
0
        private IEnumerable <string> GetProjectsFromSolution(string slnPath)
        {
            if (!File.Exists(slnPath))
            {
                throw new Exception($"Unable to find the solution file at {slnPath}");
            }

            _slnFile = new SlnFile();
            _slnFile.Read(slnPath);

            foreach (var project in _slnFile.Projects)
            {
                var projectFilePath = Path.Combine(_slnFile.BaseDirectory.FullPath,
                                                   Path.Combine(Path.GetDirectoryName(project.FilePath), Project.FileName));

                if (File.Exists(projectFilePath))
                {
                    yield return(projectFilePath);
                }
            }
        }
        public void WhenGivenASolutionWithMissingSectionIdTypeItThrows()
        {
            const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Global
	GlobalSection = preSolution
	EndGlobalSection
EndGlobal
";
            var          tmpFile      = Temp.CreateFile();

            tmpFile.WriteAllText(SolutionFile);

            Action action = () =>
            {
                SlnFile.Read(tmpFile.Path);
            };

            action.ShouldThrow <InvalidSolutionFormatException>()
            .WithMessage(FormatError(4, LocalizableStrings.SectionIdMissingError));
        }
        public void WhenGivenASolutionWithMultipleGlobalSectionsItThrows()
        {
            const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Global
EndGlobal
Global
EndGlobal
";
            var          tmpFile      = CreateFile();

            File.WriteAllText(tmpFile, SolutionFile);

            Action action = () =>
            {
                SlnFile.Read(tmpFile);
            };

            action.ShouldThrow <InvalidSolutionFormatException>()
            .WithMessage(FormatError(5, LocalizableStrings.GlobalSectionMoreThanOnceError));
        }
Example #13
0
        private static IReadOnlyList <SlnFile> FindSolutions(string solutionPath, bool findSolutions)
        {
            if (!string.IsNullOrWhiteSpace(solutionPath))
            {
                if (File.Exists(solutionPath))
                {
                    return(new List <SlnFile> {
                        SlnFile.Read(solutionPath)
                    });
                }
                return(new List <SlnFile>());
            }
            else if (findSolutions)
            {
                var files = Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*.sln",
                                                     SearchOption.AllDirectories).ToList();
                return(files.Select(SlnFile.Read).ToList());
            }

            return(new List <SlnFile>());
        }
Example #14
0
        public void WhenReferenceIsRemovedSlnBuilds()
        {
            var projectDirectory = _testAssetsManager
                                   .CopyTestAsset("TestAppWithSlnAndCsprojToRemove")
                                   .WithSource()
                                   .Path;

            var     solutionPath = Path.Combine(projectDirectory, "App.sln");
            SlnFile slnFile      = SlnFile.Read(solutionPath);

            slnFile.Projects.Count.Should().Be(2);

            var projectToRemove = Path.Combine("Lib", "Lib.csproj");
            var cmd             = new DotnetCommand(Log)
                                  .WithWorkingDirectory(projectDirectory)
                                  .Execute($"sln", "remove", projectToRemove);

            cmd.Should().Pass();

            new DotnetCommand(Log)
            .WithWorkingDirectory(projectDirectory)
            .Execute($"restore", "App.sln")
            .Should().Pass();

            new DotnetCommand(Log)
            .WithWorkingDirectory(projectDirectory)
            .Execute("build", "App.sln", "--configuration", "Release", "/p:ProduceReferenceAssembly=false")
            .Should().Pass();

            var reasonString = "should be built in release mode, otherwise it means build configurations are missing from the sln file";

            var releaseDirectory = Directory.EnumerateDirectories(
                Path.Combine(projectDirectory, "App", "bin"),
                "Release",
                SearchOption.AllDirectories);

            releaseDirectory.Count().Should().Be(1, $"App {reasonString}");
            Directory.EnumerateFiles(releaseDirectory.Single(), "App.dll", SearchOption.AllDirectories)
            .Count().Should().Be(1, $"App {reasonString}");
        }
        private void WhenSlnContainsSolutionFolderWithDifferentCasingItDoesNotCreateDuplicate()
        {
            var projectDirectory = TestAssets
                                   .Get("TestAppWithSlnAndCaseSensitiveSolutionFolders")
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root
                                   .FullName;

            var projectToAdd = Path.Combine("src", "Lib", "Lib.csproj");
            var cmd          = new DotnetCommand()
                               .WithWorkingDirectory(projectDirectory)
                               .Execute($"sln App.sln add {projectToAdd}");

            cmd.Should().Pass();

            var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln"));
            var solutionFolderProjects = slnFile.Projects.Where(
                p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid);

            solutionFolderProjects.Count().Should().Be(1);
        }
        public void WhenDirectoryContainingProjectIsGivenProjectIsRemoved()
        {
            var projectDirectory = TestAssets
                                   .Get("TestAppWithSlnAndCsprojToRemove")
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root
                                   .FullName;

            var     solutionPath = Path.Combine(projectDirectory, "App.sln");
            SlnFile slnFile      = SlnFile.Read(solutionPath);

            slnFile.Projects.Count.Should().Be(2);

            var cmd = new DotnetCommand()
                      .WithWorkingDirectory(projectDirectory)
                      .ExecuteWithCapturedOutput("sln remove Lib");

            cmd.Should().Pass();

            File.ReadAllText(solutionPath)
            .Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemove);
        }
Example #17
0
        public void WhenSolutionItemsExistInFolderParentFoldersAreNotRemoved()
        {
            var projectDirectory = _testAssetsManager
                                   .CopyTestAsset("SlnFileWithSolutionItemsInNestedFolders")
                                   .WithSource()
                                   .Path;

            var     solutionPath = Path.Combine(projectDirectory, "App.sln");
            SlnFile slnFile      = SlnFile.Read(solutionPath);

            var projectToRemove = Path.Combine("ConsoleApp1", "ConsoleApp1.csproj");
            var cmd             = new DotnetCommand(Log)
                                  .WithWorkingDirectory(projectDirectory)
                                  .Execute($"sln", "remove", projectToRemove);

            cmd.Should().Pass();
            cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectRemovedFromTheSolution, projectToRemove));

            slnFile = SlnFile.Read(solutionPath);
            File.ReadAllText(solutionPath)
            .Should()
            .BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemoveProjectInSolutionWithNestedSolutionItems);
        }
        public void WhenProjectDirectoryIsAddedSolutionFoldersAreNotCreated()
        {
            var projectDirectory = TestAssets
                                   .Get("TestAppWithSlnAndCsprojFiles")
                                   .CreateInstance()
                                   .WithSourceFiles()
                                   .Root
                                   .FullName;

            var projectToAdd = Path.Combine("Lib", "Lib.csproj");
            var cmd          = new DotnetCommand()
                               .WithWorkingDirectory(projectDirectory)
                               .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}");

            cmd.Should().Pass();

            var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln"));
            var solutionFolderProjects = slnFile.Projects.Where(
                p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid);

            solutionFolderProjects.Count().Should().Be(0);
            slnFile.Sections.GetSection("NestedProjects").Should().BeNull();
        }
Example #19
0
        private IEnumerable <string> GetProjectsFromSolution(string slnPath)
        {
            if (!File.Exists(slnPath))
            {
                throw new GracefulException(
                          string.Format(LocalizableStrings.MigrationUnableToFindSolutionFile, slnPath));
            }

            _slnFile = SlnFile.Read(slnPath);

            foreach (var project in _slnFile.Projects)
            {
                var projectFilePath = Path.Combine(
                    _slnFile.BaseDirectory,
                    Path.GetDirectoryName(project.FilePath),
                    Project.FileName);

                if (File.Exists(projectFilePath))
                {
                    yield return(projectFilePath);
                }
            }
        }
Example #20
0
        private string GetExpectedSlnContents(
            string slnPath,
            string slnTemplate,
            string expectedLibProjectGuid = null)
        {
            var slnFile = SlnFile.Read(slnPath);

            if (string.IsNullOrEmpty(expectedLibProjectGuid))
            {
                var matchingProjects = slnFile.Projects
                                       .Where((p) => p.FilePath.EndsWith("Lib.csproj"))
                                       .ToList();

                matchingProjects.Count.Should().Be(1);
                var slnProject = matchingProjects[0];
                expectedLibProjectGuid = slnProject.Id;
            }
            var slnContents = slnTemplate.Replace("__LIB_PROJECT_GUID__", expectedLibProjectGuid);

            var matchingLibFolder = slnFile.Projects
                                    .Where((p) => p.FilePath == "Lib")
                                    .ToList();

            matchingLibFolder.Count.Should().Be(1);
            slnContents = slnContents.Replace("__LIB_FOLDER_GUID__", matchingLibFolder[0].Id);

            var matchingSrcFolder = slnFile.Projects
                                    .Where((p) => p.FilePath == "src")
                                    .ToList();

            if (matchingSrcFolder.Count == 1)
            {
                slnContents = slnContents.Replace("__SRC_FOLDER_GUID__", matchingSrcFolder[0].Id);
            }

            return(slnContents);
        }
Example #21
0
        public void WhenPassedAReferenceItRemovesTheReferenceButNotOtherReferences()
        {
            var projectDirectory = _testAssetsManager
                                   .CopyTestAsset("TestAppWithSlnAndExistingCsprojReferences")
                                   .WithSource()
                                   .Path;

            var     solutionPath = Path.Combine(projectDirectory, "App.sln");
            SlnFile slnFile      = SlnFile.Read(solutionPath);

            slnFile.Projects.Count.Should().Be(2);

            var projectToRemove = Path.Combine("Lib", "Lib.csproj");
            var cmd             = new DotnetCommand(Log)
                                  .WithWorkingDirectory(projectDirectory)
                                  .Execute($"sln", "remove", projectToRemove);

            cmd.Should().Pass();
            cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectRemovedFromTheSolution, projectToRemove));

            slnFile = SlnFile.Read(solutionPath);
            slnFile.Projects.Count.Should().Be(1);
            slnFile.Projects[0].FilePath.Should().Be(Path.Combine("App", "App.csproj"));
        }
Example #22
0
        public void WhenGivenAValidPathItReadsAnSlnFile()
        {
            var solutionDirectory =
                TestAssetsManager.CreateTestInstance("TestAppWithSln", callingMethod: "p").Path;

            var solutionFullPath = Path.Combine(solutionDirectory, "TestAppWithSln.sln");

            var slnFile = SlnFile.Read(solutionFullPath);

            slnFile.FormatVersion.Should().Be("12.00");
            slnFile.ProductDescription.Should().Be("Visual Studio 14");
            slnFile.VisualStudioVersion.Should().Be("14.0.25420.1");
            slnFile.MinimumVisualStudioVersion.Should().Be("10.0.40219.1");
            slnFile.BaseDirectory.Should().Be(solutionDirectory);
            slnFile.FullPath.Should().Be(solutionFullPath);

            slnFile.Projects.Count.Should().Be(1);
            var project = slnFile.Projects[0];

            project.Id.Should().Be("{0138CB8F-4AA9-4029-A21E-C07C30F425BA}");
            project.TypeGuid.Should().Be("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}");
            project.Name.Should().Be("TestAppWithSln");
            project.FilePath.Should().Be("TestAppWithSln.xproj");
        }
Example #23
0
        public void WhenFinalReferenceIsRemovedEmptySectionsAreRemoved()
        {
            var projectDirectory = _testAssetsManager
                                   .CopyTestAsset("TestAppWithSlnAndCsprojToRemove")
                                   .WithSource()
                                   .Path;

            var     solutionPath = Path.Combine(projectDirectory, "App.sln");
            SlnFile slnFile      = SlnFile.Read(solutionPath);

            slnFile.Projects.Count.Should().Be(2);

            var appPath = Path.Combine("App", "App.csproj");
            var libPath = Path.Combine("Lib", "Lib.csproj");
            var cmd     = new DotnetCommand(Log)
                          .WithWorkingDirectory(projectDirectory)
                          .Execute($"sln", "remove", libPath, appPath);

            cmd.Should().Pass();

            var solutionContents = File.ReadAllText(solutionPath);

            solutionContents.Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemoveAllProjects);
        }
		void WriteFileInternal (string file, string sourceFile, Solution solution, bool saveProjects, ProgressMonitor monitor)
		{
			if (saveProjects) {
				var items = solution.GetAllSolutionItems ().ToArray ();
				monitor.BeginTask (items.Length + 1);
				foreach (var item in items) {
					try {
						monitor.BeginStep ();
						item.SavingSolution = true;
						item.SaveAsync (monitor).Wait ();
					} finally {
						item.SavingSolution = false;
					}
				}
			} else {
				monitor.BeginTask (1);
				monitor.BeginStep ();
			}

			SlnFile sln = new SlnFile ();
			sln.FileName = file;
			if (File.Exists (sourceFile)) {
				try {
					sln.Read (sourceFile);
				} catch (Exception ex) {
					LoggingService.LogError ("Existing solution can't be updated since it can't be read", ex);
				}
			}

			sln.FormatVersion = format.SlnVersion;

			// Don't modify the product description if it already has a value
			if (string.IsNullOrEmpty (sln.ProductDescription))
				sln.ProductDescription = format.ProductDescription;

			solution.WriteSolution (monitor, sln);

			sln.Write (file);
			monitor.EndTask ();
		}
Example #25
0
		public async Task SaveSolutionAfterChangingCSharpFormattingPolicyForTheFirstTime ()
		{
			string dir = Util.CreateTmpDir ("FormattingPolicyChangedOnce");
			var pset = PolicyService.GetPolicySet ("Mono");
			var monoFormattingPolicy = pset.Get<CSharpFormattingPolicy> ("text/x-csharp");
			var formattingPolicy = monoFormattingPolicy.Clone ();
			var solution = new Solution ();
			solution.Policies.Set (formattingPolicy);

			bool expectedSetting = !formattingPolicy.IndentSwitchCaseSection;
			formattingPolicy.IndentSwitchCaseSection = expectedSetting;
			string fileName = Path.Combine (dir, "FormattingPolicyChangedOnce.sln");

			await solution.SaveAsync (fileName, Util.GetMonitor ());

			var file = new SlnFile ();
			file.Read (fileName);
			var s = file.Sections.GetSection ("MonoDevelopProperties", SlnSectionType.PreProcess);
			var missingItem = default(KeyValuePair<string, string>);
			Assert.AreEqual (expectedSetting.ToString (), s.Properties.SingleOrDefault (p => p.Key.Contains ("IndentSwitchCaseSection")).Value);
			Assert.AreEqual (missingItem, s.Properties.SingleOrDefault (p => p.Key.Contains ("IndentSwitchSection")));
			Assert.AreEqual (missingItem, s.Properties.SingleOrDefault (p => p.Key.Contains ("IndentBlock")));
			Assert.AreEqual (missingItem, s.Properties.SingleOrDefault (p => p.Key.Contains ("SpaceBeforeDot")));
			Assert.AreEqual (missingItem, s.Properties.SingleOrDefault (p => p.Key.Contains ("NewLineForElse")));
		}
Example #26
0
        public void Generate(bool ForceRegenerate)
        {
            var s = new SlnFile();

            s.FullPath = OutputDirectory / (SolutionName + ".sln");
            using (var sr = new StringReader(SlnTemplateText))
            {
                s.Read(sr);
            }

            s.Projects.Clear();
            s.SolutionConfigurationsSection.Clear();
            s.ProjectConfigurationsSection.Clear();

            foreach (var ConfigurationType in Enum.GetValues(typeof(ConfigurationType)).Cast <ConfigurationType>())
            {
                var ConfigurationTypeAndArchitecture = $"{ConfigurationType}|{GetArchitectureString(TargetOperatingSystem, TargetArchitecture)}";
                s.SolutionConfigurationsSection.SetValue(ConfigurationTypeAndArchitecture, ConfigurationTypeAndArchitecture);
            }

            SlnSection NestedProjects = null;

            foreach (var Section in s.Sections.Where(Section => Section.Id == "NestedProjects"))
            {
                Section.Clear();
                NestedProjects = Section;
            }

            if (NestedProjects == null)
            {
                NestedProjects = new SlnSection
                {
                    Id = "NestedProjects"
                };
                s.Sections.Add(NestedProjects);
            }

            var Filters = new Dictionary <String, String>(StringComparer.OrdinalIgnoreCase);

            foreach (var Project in ProjectReferences)
            {
                var Dir = Project.VirtualDir.ToString(PathStringStyle.Windows);
                if (!Filters.ContainsKey(Dir))
                {
                    var CurrentDir       = Dir.AsPath();
                    var CurrentDirFilter = CurrentDir.ToString(PathStringStyle.Windows);
                    while ((CurrentDirFilter != ".") && !Filters.ContainsKey(CurrentDirFilter))
                    {
                        var g = Guid.ParseExact(Hash.GetHashForPath(CurrentDirFilter, 32), "N").ToString().ToUpper();
                        Filters.Add(CurrentDirFilter, g);
                        CurrentDir       = CurrentDir.Parent;
                        CurrentDirFilter = CurrentDir.ToString(PathStringStyle.Windows);
                        if (CurrentDirFilter != ".")
                        {
                            var gUpper = Guid.ParseExact(Hash.GetHashForPath(CurrentDirFilter, 32), "N").ToString().ToUpper();
                            NestedProjects.Properties.SetValue("{" + g + "}", "{" + gUpper + "}");
                        }
                    }
                }

                s.Projects.Add(new SlnProject
                {
                    TypeGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}",
                    Name     = Project.Name,
                    FilePath = Project.FilePath.FullPath.RelativeTo(OutputDirectory).ToString(PathStringStyle.Windows),
                    Id       = "{" + Project.Id + "}"
                });

                var conf = new SlnPropertySet("{" + Project.Id + "}");
                foreach (var c in s.SolutionConfigurationsSection)
                {
                    var Value = TargetOperatingSystem == OperatingSystemType.Windows ? c.Value.Replace("|x86", "|Win32") : c.Value;
                    conf.SetValue(c.Key + ".ActiveCfg", Value);
                    conf.SetValue(c.Key + ".Build.0", Value);
                }
                s.ProjectConfigurationsSection.Add(conf);

                if (Dir != ".")
                {
                    NestedProjects.Properties.SetValue("{" + Project.Id + "}", "{" + Filters[Dir] + "}");
                }
            }

            foreach (var f in Filters)
            {
                s.Projects.Add(new SlnProject
                {
                    TypeGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                    Name     = f.Key.AsPath().FileName,
                    FilePath = f.Key.AsPath().FileName,
                    Id       = "{" + f.Value + "}"
                });
            }

            foreach (var Section in s.Sections.Where(Section => Section.Id == "ExtensibilityGlobals"))
            {
                Section.Properties.SetValue("SolutionGuid", "{" + SolutionId.ToUpper() + "}");
            }

            String Text;

            using (var sw = new StringWriter())
            {
                s.Write(sw);
                Text = sw.ToString();
            }
            TextFile.WriteToFile(s.FullPath, Text, Encoding.UTF8, !ForceRegenerate);
        }
 public static VisualStudioSolution Load(string fileName)
 {
     return(new VisualStudioSolution(SlnFile.Read(fileName)));
 }
        public void WhenGivenAValidSlnFileItReadsAndVerifiesContents()
        {
            var tmpFile = Temp.CreateFile();

            tmpFile.WriteAllText(SolutionWithAppAndLibProjects);

            SlnFile slnFile = SlnFile.Read(tmpFile.Path);

            Console.WriteLine(new
            {
                slnFile_FormatVersion              = slnFile.FormatVersion,
                slnFile_ProductDescription         = slnFile.ProductDescription,
                slnFile_VisualStudioVersion        = slnFile.VisualStudioVersion,
                slnFile_MinimumVisualStudioVersion = slnFile.MinimumVisualStudioVersion,
                slnFile_BaseDirectory              = slnFile.BaseDirectory,
                slnFile_FullPath = slnFile.FullPath,
                tmpFilePath      = tmpFile.Path
            }.ToString());

            slnFile.FormatVersion.Should().Be("12.00");
            slnFile.ProductDescription.Should().Be("Visual Studio 15");
            slnFile.VisualStudioVersion.Should().Be("15.0.26006.2");
            slnFile.MinimumVisualStudioVersion.Should().Be("10.0.40219.1");
            slnFile.BaseDirectory.Should().Be(Path.GetDirectoryName(tmpFile.Path));
            slnFile.FullPath.Should().Be(Path.GetFullPath(tmpFile.Path));

            slnFile.Projects.Count.Should().Be(2);
            var project = slnFile.Projects[0];

            project.Id.Should().Be("{7072A694-548F-4CAE-A58F-12D257D5F486}");
            project.TypeGuid.Should().Be("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}");
            project.Name.Should().Be("App");
            project.FilePath.Should().Be(Path.Combine("App", "App.csproj"));
            project = slnFile.Projects[1];
            project.Id.Should().Be("{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}");
            project.TypeGuid.Should().Be("{13B669BE-BB05-4DDF-9536-439F39A36129}");
            project.Name.Should().Be("Lib");
            project.FilePath.Should().Be(Path.Combine("..", "Lib", "Lib.csproj"));

            slnFile.SolutionConfigurationsSection.Count.Should().Be(6);
            slnFile.SolutionConfigurationsSection
            .GetValue("Debug|Any CPU", string.Empty)
            .Should().Be("Debug|Any CPU");
            slnFile.SolutionConfigurationsSection
            .GetValue("Debug|x64", string.Empty)
            .Should().Be("Debug|x64");
            slnFile.SolutionConfigurationsSection
            .GetValue("Debug|x86", string.Empty)
            .Should().Be("Debug|x86");
            slnFile.SolutionConfigurationsSection
            .GetValue("Release|Any CPU", string.Empty)
            .Should().Be("Release|Any CPU");
            slnFile.SolutionConfigurationsSection
            .GetValue("Release|x64", string.Empty)
            .Should().Be("Release|x64");
            slnFile.SolutionConfigurationsSection
            .GetValue("Release|x86", string.Empty)
            .Should().Be("Release|x86");

            slnFile.ProjectConfigurationsSection.Count.Should().Be(2);
            var projectConfigSection = slnFile
                                       .ProjectConfigurationsSection
                                       .GetPropertySet("{7072A694-548F-4CAE-A58F-12D257D5F486}");

            projectConfigSection.Count.Should().Be(12);
            projectConfigSection
            .GetValue("Debug|Any CPU.ActiveCfg", string.Empty)
            .Should().Be("Debug|Any CPU");
            projectConfigSection
            .GetValue("Debug|Any CPU.Build.0", string.Empty)
            .Should().Be("Debug|Any CPU");
            projectConfigSection
            .GetValue("Debug|x64.ActiveCfg", string.Empty)
            .Should().Be("Debug|x64");
            projectConfigSection
            .GetValue("Debug|x64.Build.0", string.Empty)
            .Should().Be("Debug|x64");
            projectConfigSection
            .GetValue("Debug|x86.ActiveCfg", string.Empty)
            .Should().Be("Debug|x86");
            projectConfigSection
            .GetValue("Debug|x86.Build.0", string.Empty)
            .Should().Be("Debug|x86");
            projectConfigSection
            .GetValue("Release|Any CPU.ActiveCfg", string.Empty)
            .Should().Be("Release|Any CPU");
            projectConfigSection
            .GetValue("Release|Any CPU.Build.0", string.Empty)
            .Should().Be("Release|Any CPU");
            projectConfigSection
            .GetValue("Release|x64.ActiveCfg", string.Empty)
            .Should().Be("Release|x64");
            projectConfigSection
            .GetValue("Release|x64.Build.0", string.Empty)
            .Should().Be("Release|x64");
            projectConfigSection
            .GetValue("Release|x86.ActiveCfg", string.Empty)
            .Should().Be("Release|x86");
            projectConfigSection
            .GetValue("Release|x86.Build.0", string.Empty)
            .Should().Be("Release|x86");
            projectConfigSection = slnFile
                                   .ProjectConfigurationsSection
                                   .GetPropertySet("{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}");
            projectConfigSection.Count.Should().Be(12);
            projectConfigSection
            .GetValue("Debug|Any CPU.ActiveCfg", string.Empty)
            .Should().Be("Debug|Any CPU");
            projectConfigSection
            .GetValue("Debug|Any CPU.Build.0", string.Empty)
            .Should().Be("Debug|Any CPU");
            projectConfigSection
            .GetValue("Debug|x64.ActiveCfg", string.Empty)
            .Should().Be("Debug|x64");
            projectConfigSection
            .GetValue("Debug|x64.Build.0", string.Empty)
            .Should().Be("Debug|x64");
            projectConfigSection
            .GetValue("Debug|x86.ActiveCfg", string.Empty)
            .Should().Be("Debug|x86");
            projectConfigSection
            .GetValue("Debug|x86.Build.0", string.Empty)
            .Should().Be("Debug|x86");
            projectConfigSection
            .GetValue("Release|Any CPU.ActiveCfg", string.Empty)
            .Should().Be("Release|Any CPU");
            projectConfigSection
            .GetValue("Release|Any CPU.Build.0", string.Empty)
            .Should().Be("Release|Any CPU");
            projectConfigSection
            .GetValue("Release|x64.ActiveCfg", string.Empty)
            .Should().Be("Release|x64");
            projectConfigSection
            .GetValue("Release|x64.Build.0", string.Empty)
            .Should().Be("Release|x64");
            projectConfigSection
            .GetValue("Release|x86.ActiveCfg", string.Empty)
            .Should().Be("Release|x86");
            projectConfigSection
            .GetValue("Release|x86.Build.0", string.Empty)
            .Should().Be("Release|x86");

            slnFile.Sections.Count.Should().Be(3);
            var solutionPropertiesSection = slnFile.Sections.GetSection("SolutionProperties");

            solutionPropertiesSection.Properties.Count.Should().Be(1);
            solutionPropertiesSection.Properties
            .GetValue("HideSolutionNode", string.Empty)
            .Should().Be("FALSE");
        }