Exemplo n.º 1
0
        public async Task <ImmutableArray <ProjectFileInfo> > GetProjectFileInfosAsync(CancellationToken cancellationToken)
        {
            var targetFrameworkValue  = _loadedProject.GetPropertyValue(PropertyNames.TargetFramework);
            var targetFrameworksValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFrameworks);

            if (string.IsNullOrEmpty(targetFrameworkValue) && !string.IsNullOrEmpty(targetFrameworksValue))
            {
                // This project has a <TargetFrameworks> property, but does not specify a <TargetFramework>.
                // In this case, we need to iterate through the <TargetFrameworks>, set <TargetFramework> with
                // each value, and build the project.

                var targetFrameworks = targetFrameworksValue.Split(';');
                var results          = ImmutableArray.CreateBuilder <ProjectFileInfo>(targetFrameworks.Length);

                if (!_loadedProject.GlobalProperties.TryGetValue(PropertyNames.TargetFramework, out var initialGlobalTargetFrameworkValue))
                {
                    initialGlobalTargetFrameworkValue = null;
                }

                foreach (var targetFramework in targetFrameworks)
                {
                    _loadedProject.SetGlobalProperty(PropertyNames.TargetFramework, targetFramework);
                    _loadedProject.ReevaluateIfNecessary();

                    var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false);

                    results.Add(projectFileInfo);
                }

                if (initialGlobalTargetFrameworkValue is null)
                {
                    _loadedProject.RemoveGlobalProperty(PropertyNames.TargetFramework);
                }
                else
                {
                    _loadedProject.SetGlobalProperty(PropertyNames.TargetFramework, initialGlobalTargetFrameworkValue);
                }

                _loadedProject.ReevaluateIfNecessary();

                return(results.ToImmutable());
            }
            else
            {
                var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false);

                return(ImmutableArray.Create(projectFileInfo));
            }
        }
Exemplo n.º 2
0
        public async Task <ImmutableArray <ProjectFileInfo> > GetProjectFileInfosAsync(CancellationToken cancellationToken)
        {
            var targetFrameworkValue  = _loadedProject.GetPropertyValue(PropertyNames.TargetFramework);
            var targetFrameworksValue = _loadedProject.GetPropertyValue(PropertyNames.TargetFrameworks);

            if (string.IsNullOrEmpty(targetFrameworkValue) && !string.IsNullOrEmpty(targetFrameworksValue))
            {
                // This project has a <TargetFrameworks> property, but does not specify a <TargetFramework>.
                // In this case, we need to iterate through the <TargetFrameworks>, set <TargetFramework> with
                // each value, and build the project.

                var hasTargetFrameworkProp = _loadedProject.GetProperty(PropertyNames.TargetFramework) != null;
                var targetFrameworks       = targetFrameworksValue.Split(';');
                var results = ImmutableArray.CreateBuilder <ProjectFileInfo>(targetFrameworks.Length);

                foreach (var targetFramework in targetFrameworks)
                {
                    _loadedProject.SetProperty(PropertyNames.TargetFramework, targetFramework);
                    _loadedProject.ReevaluateIfNecessary();

                    var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false);

                    results.Add(projectFileInfo);
                }

                // Remove the <TargetFramework> property if it didn't exist in the file before we set it.
                // Otherwise, set it back to it's original value.
                if (!hasTargetFrameworkProp)
                {
                    var targetFrameworkProp = _loadedProject.GetProperty(PropertyNames.TargetFramework);
                    _loadedProject.RemoveProperty(targetFrameworkProp);
                }
                else
                {
                    _loadedProject.SetProperty(PropertyNames.TargetFramework, targetFrameworkValue);
                }

                _loadedProject.ReevaluateIfNecessary();

                return(results.ToImmutable());
            }
            else
            {
                var projectFileInfo = await BuildProjectFileInfoAsync(cancellationToken).ConfigureAwait(false);

                return(ImmutableArray.Create(projectFileInfo));
            }
        }
Exemplo n.º 3
0
            public void Dispose()
            {
                foreach (var propertyName in _setPropertyNames)
                {
                    _msBuildProject.RemoveGlobalProperty(propertyName);
                }

                _msBuildProject.ReevaluateIfNecessary();
            }
Exemplo n.º 4
0
            public MsBuildConditionContext(Microsoft.Build.Evaluation.Project msBuildProject, Dictionary <string, string> propertyValues)
            {
                _msBuildProject = msBuildProject;
                foreach (var propertyValue in propertyValues)
                {
                    _setPropertyNames.Add(propertyValue.Key);
                    _msBuildProject.SetGlobalProperty(propertyValue.Key, propertyValue.Value);
                }

                _msBuildProject.ReevaluateIfNecessary();
            }
Exemplo n.º 5
0
        private void AddNuGetTargets(MsBuildProject buildProject)
        {
            string targetsPath = Path.Combine(@"$(SolutionDir)", NuGetTargetsFile);

            // adds an <Import> element to this project file.
            if (buildProject.Xml.Imports == null ||
                buildProject.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
            {
                buildProject.Xml.AddImport(targetsPath);
                buildProject.ReevaluateIfNecessary();
            }
        }
        /// <summary>
        /// Removes the Import element from the project file.
        /// </summary>
        /// <param name="project">The project file.</param>
        /// <param name="targetsPath">The path to the imported file.</param>
        public static void RemoveImportStatement(MsBuildProject project, string targetsPath)
        {
            if (project.Xml.Imports != null)
            {
                // search for this import statement and remove it
                var importElement = project.Xml.Imports.FirstOrDefault(
                    import => targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase));

                if (importElement != null)
                {
                    importElement.Parent.RemoveChild(importElement);
                    NuGet.MSBuildProjectUtility.RemoveEnsureImportedTarget(project, targetsPath);
                    project.ReevaluateIfNecessary();
                }
            }
        }
        /// <summary>
        /// Removes the Import element from the project file.
        /// </summary>
        /// <param name="project">The project file.</param>
        /// <param name="targetsPath">The path to the imported file.</param>
        public static void RemoveImportStatement(MsBuildProject project, string targetsPath)
        {
            if (project.Xml.Imports != null)
            {
                // search for this import statement and remove it
                var importElement = project.Xml.Imports.FirstOrDefault(
                    import => targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase));

                if (importElement != null)
                {
                    importElement.Parent.RemoveChild(importElement);
                    NuGet.MSBuildProjectUtility.RemoveEnsureImportedTarget(project, targetsPath);
                    project.ReevaluateIfNecessary();
                }
            }
        }
Exemplo n.º 8
0
        private static void SetTargetFrameworkIfNeeded(MSB.Evaluation.Project evaluatedProject)
        {
            var targetFramework  = evaluatedProject.GetPropertyValue(PropertyNames.TargetFramework);
            var targetFrameworks = PropertyConverter.SplitList(evaluatedProject.GetPropertyValue(PropertyNames.TargetFrameworks), ';');

            // If the project supports multiple target frameworks and specific framework isn't
            // selected, we must pick one before execution. Otherwise, the ResolveReferences
            // target might not be available to us.
            if (string.IsNullOrWhiteSpace(targetFramework) && targetFrameworks.Length > 0)
            {
                // For now, we'll just pick the first target framework. Eventually, we'll need to
                // do better and potentially allow OmniSharp hosts to select a target framework.
                targetFramework = targetFrameworks[0];
                evaluatedProject.SetGlobalProperty(PropertyNames.TargetFramework, targetFramework);
                evaluatedProject.ReevaluateIfNecessary();
            }
        }
        /// <summary>
        /// Adds an Import element to this project file if it doesn't already exist.            
        /// </summary>
        /// <param name="project">The project file.</param>
        /// <param name="targetsPath">The path to the imported file.</param>
        /// <param name="location">The location where the Import is added.</param>
        public static void AddImportStatement(MsBuildProject project, string targetsPath, ProjectImportLocation location)
        {
            if (project.Xml.Imports == null ||
                project.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
            {
                ProjectImportElement pie = project.Xml.AddImport(targetsPath);
                pie.Condition = "Exists('" + targetsPath + "')";
                if (location == ProjectImportLocation.Top)
                {
                    // There's no public constructor to create a ProjectImportElement directly.
                    // So we have to cheat by adding Import at the end, then remove it and insert at the beginning
                    pie.Parent.RemoveChild(pie);
                    project.Xml.InsertBeforeChild(pie, project.Xml.FirstChild);
                }

                NuGet.MSBuildProjectUtility.AddEnsureImportedTarget(project, targetsPath);
                project.ReevaluateIfNecessary();
            }
        }
        /// <summary>
        /// Adds an Import element to this project file if it doesn't already exist.
        /// </summary>
        /// <param name="project">The project file.</param>
        /// <param name="targetsPath">The path to the imported file.</param>
        /// <param name="location">The location where the Import is added.</param>
        public static void AddImportStatement(MsBuildProject project, string targetsPath, ProjectImportLocation location)
        {
            if (project.Xml.Imports == null ||
                project.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
            {
                ProjectImportElement pie = project.Xml.AddImport(targetsPath);
                pie.Condition = "Exists('" + targetsPath + "')";
                if (location == ProjectImportLocation.Top)
                {
                    // There's no public constructor to create a ProjectImportElement directly.
                    // So we have to cheat by adding Import at the end, then remove it and insert at the beginning
                    pie.Parent.RemoveChild(pie);
                    project.Xml.InsertBeforeChild(pie, project.Xml.FirstChild);
                }

                NuGet.MSBuildProjectUtility.AddEnsureImportedTarget(project, targetsPath);
                project.ReevaluateIfNecessary();
            }
        }
 public List <String> FindOutputPaths()
 {
     //TODO: Move to a new class (OutputPathResolver?)
     Console.WriteLine("Attempting to parse configuration output paths.");
     Console.WriteLine("Project File: " + Options.TargetPath);
     try
     {
         Microsoft.Build.Evaluation.Project proj = new Microsoft.Build.Evaluation.Project(Options.TargetPath);
         List <string> outputPaths = new List <string>();
         List <string> configurations;
         proj.ConditionedProperties.TryGetValue("Configuration", out configurations);
         if (configurations == null)
         {
             configurations = new List <string>();
         }
         foreach (var config in configurations)
         {
             proj.SetProperty("Configuration", config);
             proj.ReevaluateIfNecessary();
             var path     = proj.GetPropertyValue("OutputPath");
             var fullPath = PathUtil.Combine(proj.DirectoryPath, path);
             outputPaths.Add(fullPath);
             Console.WriteLine("Found path: " + fullPath);
         }
         Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection.UnloadProject(proj);
         Console.WriteLine($"Found {outputPaths.Count} paths.");
         return(outputPaths);
     }
     catch (Exception e)
     {
         Console.WriteLine("Skipping configuration output paths.");
         return(new List <string>()
         {
         });
     }
 }
        public void TestAddPropertyGroupForSolutionConfigurationBuildProjectInSolutionNotSet()
        {
            string solutionFileContents =
                @"
                Microsoft Visual Studio Solution File, Format Version 9.00
                # Visual Studio 2005
                Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}'
                EndProject
                Global
                    GlobalSection(SolutionConfigurationPlatforms) = preSolution
                        Debug|Mixed Platforms = Debug|Mixed Platforms
                        Release|Any CPU = Release|Any CPU
                    EndGlobalSection
                     GlobalSection(ProjectConfigurationPlatforms) = postSolution
                        {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.ActiveCfg = CSConfig1|Any CPU
                    EndGlobalSection
                EndGlobal
                ";

            SolutionFile solution = SolutionFile_Tests.ParseSolutionHelper(solutionFileContents);

            ProjectRootElement projectXml = ProjectRootElement.Create();

            foreach (SolutionConfigurationInSolution solutionConfiguration in solution.SolutionConfigurations)
            {
                SolutionProjectGenerator.AddPropertyGroupForSolutionConfiguration(projectXml, solution, solutionConfiguration);
            }

            Project msbuildProject = new Project(projectXml);

            // Both projects configurations should be present for solution configuration "Debug|Mixed Platforms"
            msbuildProject.SetGlobalProperty("Configuration", "Debug");
            msbuildProject.SetGlobalProperty("Platform", "Mixed Platforms");
            msbuildProject.ReevaluateIfNecessary();

            string solutionConfigurationContents = msbuildProject.GetPropertyValue("CurrentSolutionConfigurationContents");
            Assert.IsTrue(solutionConfigurationContents.Contains(@"BuildProjectInSolution=""" + bool.FalseString + @""""));
        }
        public void TestAddPropertyGroupForSolutionConfiguration()
        {
            string solutionFileContents =
                @"
                Microsoft Visual Studio Solution File, Format Version 9.00
                # Visual Studio 2005
                Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}'
                EndProject
                Project('{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}') = 'MainApp', 'MainApp\MainApp.vcxproj', '{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}'
                EndProject
                Global
                    GlobalSection(SolutionConfigurationPlatforms) = preSolution
                        Debug|Mixed Platforms = Debug|Mixed Platforms
                        Release|Any CPU = Release|Any CPU
                    EndGlobalSection
                    GlobalSection(ProjectConfigurationPlatforms) = postSolution
                        {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.ActiveCfg = CSConfig1|Any CPU
                        {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.Build.0 = CSConfig1|Any CPU
                        {6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.ActiveCfg = CSConfig2|Any CPU
                        {A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.ActiveCfg = VCConfig1|Win32
                        {A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.Build.0 = VCConfig1|Win32
                    EndGlobalSection
                EndGlobal
                ";

            SolutionFile solution = SolutionFile_Tests.ParseSolutionHelper(solutionFileContents);

            ProjectRootElement projectXml = ProjectRootElement.Create();

            foreach (SolutionConfigurationInSolution solutionConfiguration in solution.SolutionConfigurations)
            {
                SolutionProjectGenerator.AddPropertyGroupForSolutionConfiguration(projectXml, solution, solutionConfiguration);
            }

            Project msbuildProject = new Project(projectXml);

            // Both projects configurations should be present for solution configuration "Debug|Mixed Platforms"
            msbuildProject.SetGlobalProperty("Configuration", "Debug");
            msbuildProject.SetGlobalProperty("Platform", "Mixed Platforms");
            msbuildProject.ReevaluateIfNecessary();

            string solutionConfigurationContents = msbuildProject.GetPropertyValue("CurrentSolutionConfigurationContents");
            string tempProjectPath = Path.Combine(Path.GetTempPath(), "ClassLibrary1\\ClassLibrary1.csproj");

            Assert.IsTrue(solutionConfigurationContents.Contains("{6185CC21-BE89-448A-B3C0-D1C27112E595}"));
            tempProjectPath = Path.GetFullPath(tempProjectPath);
            Assert.IsTrue(solutionConfigurationContents.IndexOf(tempProjectPath, StringComparison.OrdinalIgnoreCase) > 0);
            Assert.IsTrue(solutionConfigurationContents.Contains("CSConfig1|AnyCPU"));

            tempProjectPath = Path.Combine(Path.GetTempPath(), "MainApp\\MainApp.vcxproj");
            tempProjectPath = Path.GetFullPath(tempProjectPath);
            Assert.IsTrue(solutionConfigurationContents.Contains("{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}"));
            Assert.IsTrue(solutionConfigurationContents.IndexOf(tempProjectPath, StringComparison.OrdinalIgnoreCase) > 0);
            Assert.IsTrue(solutionConfigurationContents.Contains("VCConfig1|Win32"));

            // Only the C# project should be present for solution configuration "Release|Any CPU", since the VC project
            // is missing
            msbuildProject.SetGlobalProperty("Configuration", "Release");
            msbuildProject.SetGlobalProperty("Platform", "Any CPU");
            msbuildProject.ReevaluateIfNecessary();

            solutionConfigurationContents = msbuildProject.GetPropertyValue("CurrentSolutionConfigurationContents");

            Assert.IsTrue(solutionConfigurationContents.Contains("{6185CC21-BE89-448A-B3C0-D1C27112E595}"));
            Assert.IsTrue(solutionConfigurationContents.Contains("CSConfig2|AnyCPU"));

            Assert.IsFalse(solutionConfigurationContents.Contains("{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}"));
        }
        public void SolutionConfigurationWithDependencies()
        {
            string solutionFileContents =
                @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 11
Project(`{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}`) = `A`, `Project1\A.csproj`, `{786E302A-96CE-43DC-B640-D6B6CC9BF6C0}`
EndProject
Project(`{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}`) = `B`, `Project2\B.csproj`, `{881C1674-4ECA-451D-85B6-D7C59B7F16FA}`
	ProjectSection(ProjectDependencies) = postProject
		{4A727FF8-65F2-401E-95AD-7C8BBFBE3167} = {4A727FF8-65F2-401E-95AD-7C8BBFBE3167}
	EndProjectSection
EndProject
Project(`{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}`) = `C`, `Project3\C.csproj`, `{4A727FF8-65F2-401E-95AD-7C8BBFBE3167}`
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Debug|x64 = Debug|x64
		Release|Any CPU = Release|Any CPU
		Release|x64 = Release|x64
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = preSolution
		{4A727FF8-65F2-401E-95AD-7C8BBFBE3167}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{4A727FF8-65F2-401E-95AD-7C8BBFBE3167}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{4A727FF8-65F2-401E-95AD-7C8BBFBE3167}.Debug|x64.ActiveCfg = Debug|Any CPU
		{4A727FF8-65F2-401E-95AD-7C8BBFBE3167}.Debug|x64.Build.0 = Debug|Any CPU
		{4A727FF8-65F2-401E-95AD-7C8BBFBE3167}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{4A727FF8-65F2-401E-95AD-7C8BBFBE3167}.Release|Any CPU.Build.0 = Release|Any CPU
		{4A727FF8-65F2-401E-95AD-7C8BBFBE3167}.Release|x64.ActiveCfg = Release|Any CPU
		{4A727FF8-65F2-401E-95AD-7C8BBFBE3167}.Release|x64.Build.0 = Release|Any CPU
		{786E302A-96CE-43DC-B640-D6B6CC9BF6C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{786E302A-96CE-43DC-B640-D6B6CC9BF6C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{786E302A-96CE-43DC-B640-D6B6CC9BF6C0}.Debug|x64.ActiveCfg = Debug|Any CPU
		{786E302A-96CE-43DC-B640-D6B6CC9BF6C0}.Debug|x64.Build.0 = Debug|Any CPU
		{786E302A-96CE-43DC-B640-D6B6CC9BF6C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{786E302A-96CE-43DC-B640-D6B6CC9BF6C0}.Release|Any CPU.Build.0 = Release|Any CPU
		{786E302A-96CE-43DC-B640-D6B6CC9BF6C0}.Release|x64.ActiveCfg = Release|Any CPU
		{786E302A-96CE-43DC-B640-D6B6CC9BF6C0}.Release|x64.Build.0 = Release|Any CPU
		{881C1674-4ECA-451D-85B6-D7C59B7F16FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{881C1674-4ECA-451D-85B6-D7C59B7F16FA}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{881C1674-4ECA-451D-85B6-D7C59B7F16FA}.Debug|x64.ActiveCfg = Debug|Any CPU
		{881C1674-4ECA-451D-85B6-D7C59B7F16FA}.Debug|x64.Build.0 = Debug|Any CPU
		{881C1674-4ECA-451D-85B6-D7C59B7F16FA}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{881C1674-4ECA-451D-85B6-D7C59B7F16FA}.Release|Any CPU.Build.0 = Release|Any CPU
		{881C1674-4ECA-451D-85B6-D7C59B7F16FA}.Release|x64.ActiveCfg = Release|Any CPU
		{881C1674-4ECA-451D-85B6-D7C59B7F16FA}.Release|x64.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal
".Replace("`", "\"");

            SolutionFile solution = SolutionFile_Tests.ParseSolutionHelper(solutionFileContents);

            ProjectRootElement projectXml = ProjectRootElement.Create();

            foreach (SolutionConfigurationInSolution solutionConfiguration in solution.SolutionConfigurations)
            {
                SolutionProjectGenerator.AddPropertyGroupForSolutionConfiguration(projectXml, solution, solutionConfiguration);
            }

            Project msbuildProject = new Project(projectXml);

            // Both projects configurations should be present for solution configuration "Debug|Mixed Platforms"
            msbuildProject.SetGlobalProperty("Configuration", "Debug");
            msbuildProject.SetGlobalProperty("Platform", "Any CPU");
            msbuildProject.ReevaluateIfNecessary();

            string solutionConfigurationContents = msbuildProject.GetPropertyValue("CurrentSolutionConfigurationContents");

            // Only the specified solution configuration is represented in THE BLOB: nothing for x64 in this case
            string expected = @"<SolutionConfiguration>
  <ProjectConfiguration Project=`{786E302A-96CE-43DC-B640-D6B6CC9BF6C0}` AbsolutePath=`##temp##Project1\A.csproj` BuildProjectInSolution=`True`>Debug|AnyCPU</ProjectConfiguration>
  <ProjectConfiguration Project=`{881C1674-4ECA-451D-85B6-D7C59B7F16FA}` AbsolutePath=`##temp##Project2\B.csproj` BuildProjectInSolution=`True`>Debug|AnyCPU<ProjectDependency Project=`{4A727FF8-65F2-401E-95AD-7C8BBFBE3167}` /></ProjectConfiguration>
  <ProjectConfiguration Project=`{4A727FF8-65F2-401E-95AD-7C8BBFBE3167}` AbsolutePath=`##temp##Project3\C.csproj` BuildProjectInSolution=`True`>Debug|AnyCPU</ProjectConfiguration>
</SolutionConfiguration>".Replace("`", "\"").Replace("##temp##", Path.GetTempPath());

            Helpers.VerifyAssertLineByLine(expected, solutionConfigurationContents);
        }
Exemplo n.º 15
0
        protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
        {
            // Get active project
            // TODO: Instead of a custom code generator, we should have a context command or something like that.
            // This should also allow generation of multiple files

            var lines = Regex.Split(inputFileContent, "\r\n|\r|\n");

            if (lines.Length == 0 || lines[0].Length == 0)
            {
                throw new InvalidOperationException("Source should contain project filename.");
            }

            var projectFullName = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(inputFileName), lines[0]));

            if (!File.Exists(projectFullName))
            {
                throw new InvalidOperationException("Project file doesn't exist.");
            }

            string assemblyOutput, intermediateAssembly;

            // Get Evaluation Project
            Microsoft.Build.Evaluation.Project msbuildProject = Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection.GetLoadedProjects(projectFullName).First();

            // Set ParadoxBuildStep variable and change IntermediateOutputPath
            var property1 = msbuildProject.SetProperty("ParadoxBuildStep", "StepData");
            var property2 = msbuildProject.SetProperty("IntermediateOutputPath", @"obj\StepData\");

            // Reevaluate dependent properties
            msbuildProject.ReevaluateIfNecessary();

            try
            {
                var outputPane = GetOutputPane();

                // Create logger
                var buildLogger = new IDEBuildLogger(outputPane, new TaskProvider(GlobalServiceProvider), VsHelper.GetCurrentHierarchy(GlobalServiceProvider));
                buildLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic;

                var evaluatedProperties = new Dictionary <string, Microsoft.Build.Evaluation.ProjectProperty>();
                foreach (var evaluatedProperty in msbuildProject.AllEvaluatedProperties)
                {
                    evaluatedProperties[evaluatedProperty.Name] = evaluatedProperty;
                }

                // Output properties
                foreach (var evaluatedProperty in evaluatedProperties)
                {
                    outputPane.OutputStringThreadSafe(string.Format(
                                                          "$({0}) = {1} was evaluated as {2}\n",
                                                          evaluatedProperty.Key,
                                                          evaluatedProperty.Value.UnevaluatedValue,
                                                          evaluatedProperty.Value.EvaluatedValue));
                }

                // Compile project (only intermediate assembly)
                // Dependencies will be built as well
                //var manager = BuildManager.DefaultBuildManager;
                using (var manager = new BuildManager())
                {
                    var pc = new Microsoft.Build.Evaluation.ProjectCollection();
                    var globalProperties = new Dictionary <string, string>();
                    globalProperties["SolutionName"] = evaluatedProperties["SolutionName"].EvaluatedValue;
                    globalProperties["SolutionDir"]  = evaluatedProperties["SolutionDir"].EvaluatedValue;
                    var projectInstance = new ProjectInstance(projectFullName, globalProperties, null);
                    var buildResult     = manager.Build(
                        new BuildParameters(pc)
                    {
                        Loggers         = new[] { buildLogger },
                        DetailedSummary = true,
                    },
                        new BuildRequestData(projectInstance, new[] { "Compile" }, null));

                    if (buildResult.OverallResult == BuildResultCode.Failure)
                    {
                        throw new InvalidOperationException(string.Format("Build of {0} failed.", projectFullName));
                    }
                }

                // Get TargetPath and IntermediateAssembly
                assemblyOutput       = msbuildProject.AllEvaluatedProperties.Last(x => x.Name == "TargetPath").EvaluatedValue;
                intermediateAssembly = msbuildProject.AllEvaluatedItems.First(x => x.ItemType == "IntermediateAssembly").EvaluatedInclude;
            }
            finally
            {
                msbuildProject.RemoveProperty(property1);
                msbuildProject.RemoveProperty(property2);
            }

            // Defer execution to current Paradox VS package plugin
            try
            {
                var remoteCommands = ParadoxCommandsProxy.GetProxy();
                return(remoteCommands.GenerateDataClasses(assemblyOutput, projectFullName, intermediateAssembly));
            }
            catch (Exception ex)
            {
                GeneratorError(4, ex.ToString(), 0, 0);

                return(new byte[0]);
            }
        }
Exemplo n.º 16
0
        private void AddNuGetTargets(Project project, MsBuildProject buildProject)
        {
            string targetsPath = Path.Combine(@"$(SolutionDir)", NuGetTargetsFile);

            // adds an <Import> element to this project file.
            if (buildProject.Xml.Imports == null ||
                buildProject.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
            {
                buildProject.Xml.AddImport(targetsPath);
                project.Save();
                buildProject.ReevaluateIfNecessary();
            }
        }