Ejemplo n.º 1
0
        public static Project LoadedProject(string path, bool cached)
        {
            Project           project    = null;
            bool              cpp        = path.EndsWith(".vcxproj");
            ProjectCollection collection = cpp ? cppProjectColletion : ProjectCollection.GlobalProjectCollection;

            project = collection.GetLoadedProjects(path).FirstOrDefault();

            if (project == null)
            {
                project = collection.LoadProject(path);
            }
            else
            {
                if (cpp && !cached)
                {
                    //
                    // That is required to get C++ project properties re-evaluated
                    // with Visual Studio 2013 and Visual Studio 2015
                    //
                    collection.UnloadProject(project);
                    collection.UnloadAllProjects();
                    project = collection.LoadProject(path);
                }
            }
            return(project);
        }
Ejemplo n.º 2
0
        Project ConfigureProject(string file, string configuration, string platform, string slnConfigContents)
        {
            var p = engine.GetLoadedProjects(file).FirstOrDefault();

            if (p == null)
            {
                var content = buildEngine.GetUnsavedProjectContent(file);
                if (content == null)
                {
                    p = engine.LoadProject(file);
                }
                else
                {
                    Environment.CurrentDirectory = Path.GetDirectoryName(file);
                    p          = engine.LoadProject(new XmlTextReader(new StringReader(content)));
                    p.FullPath = file;
                }
            }
            p.SetProperty("CurrentSolutionConfigurationContents", slnConfigContents);
            p.SetProperty("Configuration", configuration);
            if (!string.IsNullOrEmpty(platform))
            {
                p.SetProperty("Platform", platform);
            }
            else
            {
                p.SetProperty("Platform", "");
            }
            return(p);
        }
Ejemplo n.º 3
0
        public static Microsoft.Build.Evaluation.Project LoadedProject(String path, bool cpp, bool cached)
        {
            Microsoft.Build.Evaluation.Project project = null;
            ProjectCollection collection = cpp ? cppProjectColletion : ProjectCollection.GlobalProjectCollection;
            ICollection <Microsoft.Build.Evaluation.Project> projects = collection.GetLoadedProjects(path);


            if (projects.Count == 0)
            {
                project = collection.LoadProject(path);
            }
            else
            {
                project = projects.First();
                if (cpp && !cached)
                {
                    //
                    // That is required to get C++ project properties re-evaluated
                    // with Visual Studio 2013 and Visual Studio 2015
                    //
                    collection.UnloadProject(project);
                    collection.UnloadAllProjects();
                    project = collection.LoadProject(path);
                }
            }
            return(project);
        }
Ejemplo n.º 4
0
        public bool BuildProjectFile
        (
            string projectFileName,
            string[] targetNames,
            IDictionary globalPropertiesPassedIntoTask,
            IDictionary targetOutputs,
            string toolsVersion
        )
        {
            Dictionary <string, string> finalGlobalProperties = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            // Finally, whatever global properties were passed into the task ... those are the final winners.
            if (globalPropertiesPassedIntoTask != null)
            {
                foreach (DictionaryEntry newGlobalProperty in globalPropertiesPassedIntoTask)
                {
                    finalGlobalProperties[(string)newGlobalProperty.Key] = (string)newGlobalProperty.Value;
                }
            }

            Project project = _projectCollection.LoadProject(projectFileName, finalGlobalProperties, toolsVersion);

            ILogger[] loggers = new ILogger[2] {
                _mockLogger, new ConsoleLogger()
            };

            return(project.Build(targetNames, loggers));
        }
Ejemplo n.º 5
0
        Project ConfigureProject(string file, string configuration, string platform)
        {
            var p = engine.GetLoadedProjects(file).FirstOrDefault();

            if (p == null)
            {
                var content = buildEngine.GetUnsavedProjectContent(file);
                if (content == null)
                {
                    p = engine.LoadProject(file);
                }
                else
                {
                    p          = engine.LoadProject(new XmlTextReader(new StringReader(content)));
                    p.FullPath = file;
                }
            }
            p.SetProperty("Configuration", configuration);
            if (!string.IsNullOrEmpty(platform))
            {
                p.SetProperty("Platform", platform);
            }
            else
            {
                p.SetProperty("Platform", "");
            }

            return(p);
        }
Ejemplo n.º 6
0
        private static ProjectInstance LoadProject(
            string filePath, string solutionDirectory, string sdksPath, ILogger logger,
            MSBuildOptions options, ICollection <MSBuildDiagnosticsMessage> diagnostics, out ImmutableArray <string> targetFrameworks)
        {
            options = options ?? new MSBuildOptions();

            var globalProperties = GetGlobalProperties(options, solutionDirectory, sdksPath, logger);

            const string MSBuildSDKsPath  = "MSBuildSDKsPath";
            var          oldSdksPathValue = Environment.GetEnvironmentVariable(MSBuildSDKsPath);

            try
            {
                if (globalProperties.TryGetValue(MSBuildSDKsPath, out var sdksPathValue))
                {
                    Environment.SetEnvironmentVariable(MSBuildSDKsPath, sdksPathValue);
                }

                var collection = new ProjectCollection(globalProperties);

                // Evaluate the MSBuild project
                var project = string.IsNullOrEmpty(options.ToolsVersion)
                    ? collection.LoadProject(filePath)
                    : collection.LoadProject(filePath, options.ToolsVersion);

                var targetFramework = project.GetPropertyValue(PropertyNames.TargetFramework);
                targetFrameworks = PropertyConverter.SplitList(project.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];
                    project.SetProperty(PropertyNames.TargetFramework, targetFramework);
                }
                else if (!string.IsNullOrWhiteSpace(targetFramework) && targetFrameworks.Length == 0)
                {
                    targetFrameworks = ImmutableArray.Create(targetFramework);
                }

                var projectInstance = project.CreateProjectInstance();
                var buildResult     = projectInstance.Build(TargetNames.Compile,
                                                            new[] { new MSBuildLogForwarder(logger, diagnostics) });

                return(buildResult
                    ? projectInstance
                    : null);
            }
            finally
            {
                Environment.SetEnvironmentVariable(MSBuildSDKsPath, oldSdksPathValue);
            }
        }
Ejemplo n.º 7
0
        public void VersionSetToValidValueButInvalidVersionSetsNextVersion()
        {
            using (TestEnvironment env = TestEnvironment.Create())
            {
                env.SetChangeWave($"{ChangeWaves.LowestWaveAsVersion.Major}.{ChangeWaves.LowestWaveAsVersion.Minor}.{ChangeWaves.LowestWaveAsVersion.Build+1}");
                BuildEnvironmentHelper.ResetInstance_ForUnitTestsOnly();

                // All waves should be disabled
                string projectFile = $"" +
                                     $"<Project>" +
                                     $"<Target Name='HelloWorld' Condition=\"'$(MSBUILDDISABLEFEATURESFROMVERSION)' == '{ChangeWaves.AllWaves[1]}' and $([MSBuild]::AreFeaturesEnabled('{ChangeWaves.LowestWave}'))\">" +
                                     $"<Message Text='Hello World!'/>" +
                                     $"</Target>" +
                                     $"</Project>";

                TransientTestFile file = env.CreateFile("proj.csproj", projectFile);

                ProjectCollection collection = new ProjectCollection();
                MockLogger        log        = new MockLogger();
                collection.RegisterLogger(log);

                Project p = collection.LoadProject(file.Path);
                p.Build().ShouldBeTrue();

                BuildEnvironmentHelper.ResetInstance_ForUnitTestsOnly();
                log.AssertLogContains("Hello World!");
            }
        }
Ejemplo n.º 8
0
        public void VersionTooHighClampsToHighestVersionInRotation(string disableFromWave)
        {
            using (TestEnvironment env = TestEnvironment.Create())
            {
                env.SetChangeWave(disableFromWave);
                BuildEnvironmentHelper.ResetInstance_ForUnitTestsOnly();

                // all waves but the highest should pass
                for (int i = 0; i < ChangeWaves.AllWaves.Length - 1; i++)
                {
                    ChangeWaves.ResetStateForTests();
                    string projectFile = $"" +
                                         $"<Project>" +
                                         $"<Target Name='HelloWorld' Condition=\"'$(MSBUILDDISABLEFEATURESFROMVERSION)' == '{ChangeWaves.HighestWave}' and $([MSBuild]::AreFeaturesEnabled('{ChangeWaves.AllWaves[i]}'))\">" +
                                         $"<Message Text='Hello World!'/>" +
                                         $"</Target>" +
                                         $"</Project>";

                    TransientTestFile file = env.CreateFile("proj.csproj", projectFile);

                    ProjectCollection collection = new ProjectCollection();
                    MockLogger        log        = new MockLogger();
                    collection.RegisterLogger(log);

                    Project p = collection.LoadProject(file.Path);
                    p.Build().ShouldBeTrue();

                    BuildEnvironmentHelper.ResetInstance_ForUnitTestsOnly();

                    log.WarningCount.ShouldBe(1);
                    log.AssertLogContains("out of rotation");
                    log.AssertLogContains("Hello World!");
                }
            }
        }
Ejemplo n.º 9
0
        internal static ProjectWrapper LoadProject(string projectPath)
        {
            var projectCollection = new ProjectCollection();

            projectCollection.DefaultToolsVersion = ToolsVersion;
            projectCollection.SetGlobalProperty("Configuration", GetConfiguration());

            var project = projectCollection.LoadProject(projectPath, ToolsVersion);

            project.SetProperty("BuildProjectReferences", "false");

            if (project.GetProperty("TargetFramework") == null)
            {
                var targetFrameworks = project.GetProperty("TargetFrameworks")?.EvaluatedValue;
                if (targetFrameworks != null)
                {
                    if (!targetFrameworks.Contains(';'))
                    {
                        project.SetGlobalProperty("TargetFramework", targetFrameworks);
                    }
                    else
                    {
                        // fallback to silverlight since that what client
                        // projects currently should use
                        project.SetGlobalProperty("TargetFramework", "sl5");
                    }
                }
            }

            return(new ProjectWrapper(project));
        }
        public void ImportFromExtensionsPathNotFound()
        {
            string extnDir1        = null;
            string mainProjectPath = null;

            try {
                extnDir1        = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), GetExtensionTargetsFileContent1());
                mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());

                var projColln = new ProjectCollection();
                projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", extnDir1, Path.Combine("tmp", "nonexistant")));
                var logger = new MockLogger();
                projColln.RegisterLogger(logger);

                Assert.Throws <InvalidProjectFileException>(() => projColln.LoadProject(mainProjectPath));

                logger.AssertLogContains("MSB4226");
            } finally {
                if (mainProjectPath != null)
                {
                    FileUtilities.DeleteNoThrow(mainProjectPath);
                }
                if (extnDir1 != null)
                {
                    FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
                }
            }
        }
Ejemplo n.º 11
0
        public void BuildAndAnalyze()
        {
            var globalProps = new Dictionary <string, string> {
                { "VisualStudioVersion", "12.0" }
            };

            pc = new ProjectCollection(globalProps);

            var diagLogger = new DiagnosticXmlLogger(this);

            diagLogger.LogFile = _logFilepath;

            project      = pc.LoadProject(_projectFilepath, "12.0");
            projInst     = project.CreateProjectInstance();
            buildManager = new BuildManager();
            var buildParams = new BuildParameters();

            buildParams.Loggers = new ILogger[] { diagLogger };
            buildManager.BeginBuild(buildParams);

            var brd = new BuildRequestData(projInst, _targets, null, BuildRequestDataFlags.ReplaceExistingProjectInstance);

            submission  = buildManager.PendBuildRequest(brd);
            buildResult = submission.Execute();

            buildManager.EndBuild();
        }
        public string Build(string target)
        {
            var builder = new StringBuilder();

            var loggers = new List <ILogger>();

            // capture log output to string for test assertions
            loggers.Add(CreateLogger(builder));

            // capture log output for display by nunit test results
            loggers.Add(new ConsoleLogger(m_verbosity));

            var projectCollection = new ProjectCollection();

            projectCollection.RegisterLoggers(loggers);

            var project = projectCollection.LoadProject(m_path);

            try
            {
                project.Build(target);
            }
            finally
            {
                projectCollection.UnregisterAllLoggers();
            }

            return(builder.ToString());
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Builds the solution file.
        /// </summary>
        /// <param name="configurationName">Name of the configuration to build.</param>
        /// <returns>
        ///   <c>true</c> if solution has been built successfully; <c>false</c> otherwise;
        /// </returns>
        /// <seealso cref="CurrentlyLoadedSolutionFile" />
        ///   <seealso cref="LoadSolutionFile" />
        /// <remarks>
        /// The solution file to be built is available in <see cref="CurrentlyLoadedSolutionFile" />. If no solution file has been loaded this method will return <c>false</c>.
        /// </remarks>
        public bool BuildSolution(string configurationName)
        {
            if (_currentlyLoadedSolutionFile == null)
            {
                return(false);
            }
            else
            {
                bool result = false;

                string msBuildProjectFile = BuildMsBuildProjectFile(_currentlyLoadedSolutionFile, configurationName);
                using (ProjectCollection msBuildProjectCollection = new ProjectCollection())
                {
                    msBuildProjectCollection.LoadProject(msBuildProjectFile);

                    if (msBuildProjectCollection.IsBuildEnabled)
                    {
                        result = true;
                        msBuildProjectCollection.LoadedProjects.ToList().ForEach(p => result = result && p.Build("Build"));
                    }
                }

                if (result)
                {
                    File.Delete(msBuildProjectFile);
                }

                return(result);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Adjusts the references to the Flutter module AARs that need to be embedded
        /// inside the Xamarin.Android bindings library.
        /// </summary>
        /// <param name="csprojPath">Path of the Xamarin.Android bindings library project file</param>
        /// <param name="project"><see cref="DartProject"/> representing the newly created Flutter module</param>
        private static void SetNativeReference_AndroidBindings(string csprojPath, DartProject project)
        {
            string aarDebugPath   = project.GetAndroidArchivePath(FlutterModuleBuildConfig.Debug);
            string aarReleasePath = project.GetAndroidArchivePath(FlutterModuleBuildConfig.Release);

            FileSystemInfo csProjPathDirInfo = new FileInfo(csprojPath);

            string aarDebugPathRelative   = csProjPathDirInfo.GetRelativePathTo(new FileInfo(aarDebugPath));
            string aarReleasePathRelative = csProjPathDirInfo.GetRelativePathTo(new FileInfo(aarReleasePath));

            using (ProjectCollection prjColl = new ProjectCollection())
            {
                Project prj = prjColl.LoadProject(csprojPath);

                ICollection <ProjectItem> aarItems = prj.GetItemsIgnoringCondition("LibraryProjectZip");
                prj.RemoveItems(aarItems);

                IList <ProjectItem> debugItems = prj.AddItem("LibraryProjectZip", aarDebugPathRelative);
                // need to specify Condition on parent ItemGroup
                debugItems[0].Xml.Parent.Condition = MSBuildDebugCondition;
                //debugItems[0].Xml.Condition = MSBuildDebugCondition;
                debugItems[0].SetMetadataValue("Link", $"Jars\\{FlutterModuleDebugAAR}");

                IList <ProjectItem> releaseItems = prj.AddItem("LibraryProjectZip", aarReleasePathRelative);
                // need to specify Condition on parent ItemGroup
                releaseItems[0].Xml.Parent.Condition = MSBuildReleaseCondition;
                //releaseItems[0].Xml.Condition = MSBuildReleaseCondition;
                releaseItems[0].SetMetadataValue("Link", $"Jars\\{FlutterModuleReleaseAAR}");

                prj.Save();
            }
        }
        private bool ModifyProjectFile(string projectFilePath, string packageName, string newVersion)
        {
            bool isModified = false;

            using (var projectCollection = new ProjectCollection())
            {
                var csProject             = projectCollection.LoadProject(projectFilePath);
                var packageReferenceGroup = csProject.Xml.ItemGroups.FirstOrDefault(i => i.FirstChild != null && i.FirstChild.ElementName == "PackageReference");
                if (packageReferenceGroup != null)
                {
                    var packageToModify = packageReferenceGroup.Items.FirstOrDefault(i => i.Include == packageName);
                    if (packageToModify != null)
                    {
                        foreach (var child in packageToModify.AllChildren)
                        {
                            if (child is ProjectMetadataElement childToModify && childToModify.Name == "Version")
                            {
                                childToModify.Value = newVersion;
                                isModified          = true;
                                break;
                            }
                        }
                    }
                }

                if (isModified)
                {
                    csProject.Save(projectFilePath);
                    return(true);
                }
                return(false);
            }
        }
Ejemplo n.º 16
0
        public override bool Execute()
        {
            var properties = new Dictionary <string, string>
            {
                { "Configuration", "$(Configuration)" },
                { "Platform", "$(Platform)" },
                { "TargetFramework", "$(TargetFramework)" }
            };

            Log.LogMessage(MessageImportance.High, "Configuration : {0}", Configuration);
            Log.LogMessage(MessageImportance.High, "Platform : {0}", Platform);
            Log.LogMessage(MessageImportance.High, "TargetFramework : {0}", TargetFramework);

            List <ITaskItem> pList     = ProjectFiles.ToList();
            List <ITaskItem> tizenList = new List <ITaskItem>();

            foreach (var pItem in pList)
            {
                // Load the project into a separate project collection so
                // we don't get a redundant-project-load error.
                var             collection = new ProjectCollection(properties);
                var             project    = collection.LoadProject(pItem.ItemSpec);
                ProjectProperty pp         = project.Properties.Where(p => p.Name == "TizenProject" && p.EvaluatedValue == "true").FirstOrDefault();
                if (pp != null)
                {
                    tizenList.Add(pItem);
                }
            }

            tizenProjectFiles = tizenList;

            return(true);
        }
Ejemplo n.º 17
0
        public void CorrectlyDetermineDisabledFeatures()
        {
            using (TestEnvironment env = TestEnvironment.Create())
            {
                env.SetChangeWave(ChangeWaves.LowestWave);
                BuildEnvironmentHelper.ResetInstance_ForUnitTestsOnly();

                foreach (string wave in ChangeWaves.AllWaves)
                {
                    ChangeWaves.AreFeaturesEnabled(wave).ShouldBeFalse();

                    string projectFile = $"" +
                                         $"<Project>" +
                                         $"<Target Name='HelloWorld' Condition=\"$([MSBuild]::AreFeaturesEnabled('{wave}')) == false\">" +
                                         $"<Message Text='Hello World!'/>" +
                                         $"</Target>" +
                                         $"</Project>";

                    TransientTestFile file = env.CreateFile("proj.csproj", projectFile);

                    ProjectCollection collection = new ProjectCollection();
                    MockLogger        log        = new MockLogger();
                    collection.RegisterLogger(log);

                    Project p = collection.LoadProject(file.Path);
                    p.Build().ShouldBeTrue();

                    log.AssertLogContains("Hello World!");
                }
                BuildEnvironmentHelper.ResetInstance_ForUnitTestsOnly();
            }
        }
Ejemplo n.º 18
0
        public static ProjectInformation LoadProject(string projectPath, IDictionary <string, string> globalProperties = null)
        {
            // Based on https://daveaglick.com/posts/running-a-design-time-build-with-msbuild-apis

            if (globalProperties == null)
            {
                globalProperties = GetGlobalProperties(projectPath);
            }

            var isSdkStyle = false;

            using (var reader = XmlReader.Create(projectPath))
            {
                if (reader.MoveToContent() == XmlNodeType.Element && reader.HasAttributes)
                {
                    isSdkStyle = reader.MoveToAttribute("Sdk");
                }
            }

            try
            {
                var projectCollection = new ProjectCollection(globalProperties);
                var project           = projectCollection.LoadProject(projectPath);

                return(new ProjectInformation(projectCollection, project, !isSdkStyle));
            }
            catch (InvalidProjectFileException projectFileException)
            {
                throw new InvalidOperationException("Not a project: " + projectPath, projectFileException);
            }
        }
Ejemplo n.º 19
0
        public void NoChangeWaveSetMeansAllChangeWavesAreEnabled(string featureWave)
        {
            using (TestEnvironment env = TestEnvironment.Create())
            {
                ChangeWaves.ResetStateForTests();
                ChangeWaves.AreFeaturesEnabled(featureWave).ShouldBe(true);

                string projectFile = $"" +
                                     $"<Project>" +
                                     $"<Target Name='HelloWorld' Condition=\"'$(MSBUILDDISABLEFEATURESFROMVERSION)' == '{ChangeWaves.EnableAllFeatures}' and $([MSBuild]::AreFeaturesEnabled('{featureWave}'))\">" +
                                     $"<Message Text='Hello World!'/>" +
                                     $"</Target>" +
                                     $"</Project>";

                TransientTestFile file = env.CreateFile("proj.csproj", projectFile);

                ProjectCollection collection = new ProjectCollection();
                MockLogger        log        = new MockLogger();
                collection.RegisterLogger(log);

                collection.LoadProject(file.Path).Build().ShouldBeTrue();
                log.AssertLogContains("Hello World!");
                BuildEnvironmentHelper.ResetInstance_ForUnitTestsOnly();
            }
        }
Ejemplo n.º 20
0
        public Project Load()
        {
            if (_project != null)
            {
                return(_project);
            }

            // Create a project collection for each project since the toolset might change depending on the type of project
            ProjectCollection projectCollection = CreateProjectCollection();

            // Load the project
            _buildEnvironment.SetEnvironmentVars(GlobalProperties);
            try
            {
                using (XmlReader projectReader = _projectDocument.CreateReader())
                {
                    _project          = projectCollection.LoadProject(projectReader);
                    _project.FullPath = ProjectFilePath;
                }
                return(_project);
            }
            finally
            {
                _buildEnvironment.UnsetEnvironmentVars();
            }
        }
        public static Project LoadProject(string fullPath, IDictionary <string, string> args)
        {
            var collection = new ProjectCollection(args);

            // parsing fails in Mono with the default "15.0" as /usr/lib/mono/xbuild/15.0/bin/Microsoft.CSharp.targets not found
            return(collection.LoadProject(fullPath, MonoHack.IsMono ? "14.0" : null));
        }
        public override bool Execute()
        {
            if (AttachDebugger)
            {
                System.Diagnostics.Debugger.Launch();
            }

            try
            {
                Regex excludeFilterRegex = !ExcludeFilter.IsNullOrEmpty() ? new Regex(ExcludeFilter) : null;

                using (ProjectCollection collection = new ProjectCollection())
                {
                    Project sourceProject = collection.LoadProject(ProjectPath);
                    Project targetProject = new Project(collection);

                    AddGeneratedItems(targetProject, GetGeneratedItems(CompileItems, sourceProject.GetItems(CompileItemType), excludeFilterRegex), CompileItemType);

                    targetProject.Save(OutputTargetsPath);
                }
            }
            catch (Exception e)
            {
                Log.LogError($"{nameof(WriteGeneratedItemsTask)} - Error reading \"{ProjectPath}\"");
                Log.LogErrorFromException(e);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Helper function to build a simple project based on a particular change wave being set.
        /// Call SetChangeWave on your TestEnvironment before calling this function.
        /// </summary>
        /// <param name="testEnvironment">The TestEnvironment being used for this test.</param>
        /// <param name="versionToCheckAgainstCurrentChangeWave">The version to compare to the current set Change Wave.</param>
        /// <param name="currentChangeWaveShouldUltimatelyResolveTo">What the project property for the environment variable MSBuildDisableFeaturesFromVersion ultimately resolves to.</param>
        /// <param name="warningCodesLogShouldContain">An array of warning codes that should exist in the resulting log. Ex: "MSB4271".</param>
        private void buildSimpleProjectAndValidateChangeWave(TestEnvironment testEnvironment, Version versionToCheckAgainstCurrentChangeWave, Version currentChangeWaveShouldUltimatelyResolveTo, params string[] warningCodesLogShouldContain)
        {
            bool isThisWaveEnabled = versionToCheckAgainstCurrentChangeWave < currentChangeWaveShouldUltimatelyResolveTo || currentChangeWaveShouldUltimatelyResolveTo == ChangeWaves.EnableAllFeatures;

            ChangeWaves.AreFeaturesEnabled(versionToCheckAgainstCurrentChangeWave).ShouldBe(isThisWaveEnabled);

            string projectFile = $"" +
                                 $"<Project>" +
                                 $"<Target Name='HelloWorld' Condition=\"$([MSBuild]::AreFeaturesEnabled('{versionToCheckAgainstCurrentChangeWave}')) and '$(MSBUILDDISABLEFEATURESFROMVERSION)' == '{currentChangeWaveShouldUltimatelyResolveTo}'\">" +
                                 $"<Message Text='Hello World!'/>" +
                                 $"</Target>" +
                                 $"</Project>";

            TransientTestFile file = testEnvironment.CreateFile("proj.csproj", projectFile);

            ProjectCollection collection = new ProjectCollection();
            MockLogger        log        = new MockLogger(_output);

            collection.RegisterLogger(log);

            Project p = collection.LoadProject(file.Path);

            p.Build().ShouldBeTrue();

            log.FullLog.Contains("Hello World!").ShouldBe(isThisWaveEnabled);

            if (warningCodesLogShouldContain != null)
            {
                log.WarningCount.ShouldBe(warningCodesLogShouldContain.Length);
                log.AssertLogContains(warningCodesLogShouldContain);
            }

            ChangeWaves.ResetStateForTests();
        }
        void CreateAndBuildProjectForImportFromExtensionsPath(string mainProjectPath, string extnPathPropertyName, string[] extnDirs, Action <string[]> setExtensionsPath,
                                                              Action <Project, MockLogger> action)
        {
            try {
                var projColln = new ProjectCollection();
                projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader(extnPathPropertyName, extnDirs));
                var logger = new MockLogger();
                projColln.RegisterLogger(logger);
                var project = projColln.LoadProject(mainProjectPath);

                action(project, logger);
            } finally {
                if (mainProjectPath != null)
                {
                    FileUtilities.DeleteNoThrow(mainProjectPath);
                }

                if (extnDirs != null)
                {
                    foreach (var extnDir in extnDirs)
                    {
                        FileUtilities.DeleteDirectoryNoThrow(extnDir, recursive: true);
                    }
                }
            }
        }
Ejemplo n.º 25
0
        public void AutoIncludeItems()
        {
            foreach (var item in _project.BuildTasks.ProjectNames)
            {
                string projectName = Handlebars.Compile(item)(new { _project.ProjectName });

                var templates = _project.BuildTasks.Templates.ToList().Where(r => r.Output.Folder.Contains(item)).ToList();

                foreach (var buildK in templates)
                {
                    string path = Path.Combine(_project.OutputPath, projectName, projectName + ".csproj").Replace("\\", "/").Replace("//", "/");

                    if (!File.Exists(path))
                    {
                        continue;
                    }

                    ProjectCollection pc = new ProjectCollection();

                    var poj = pc.LoadProject(path, "15.0");

                    poj.AddItem("Compile", Path.Combine(
                                    Handlebars.Compile(buildK.Output.Folder)(new { ProjectName = item }),
                                    Handlebars.Compile(buildK.Output.Name)(new { _project.TableName })
                                    )
                                );

                    poj.Build();
                    poj.Save();
                }
            }
        }
Ejemplo n.º 26
0
        private void PublishSite(Dictionary <string, string> properties)
        {
            var logFile = Path.GetTempFileName();

            try
            {
                bool success;
                using (var projects = new ProjectCollection(properties))
                {
                    projects.RegisterLogger(new FileLogger {
                        Parameters = @"logfile=" + logFile, Verbosity = LoggerVerbosity.Quiet
                    });
                    projects.OnlyLogCriticalEvents = true;
                    var project = projects.LoadProject(ProjectPath);
                    success = project.Build();
                }

                if (!success)
                {
                    Console.WriteLine(File.ReadAllText(logFile));
                    throw new ApplicationException("Build failed.");
                }
            }
            finally
            {
                if (File.Exists(logFile))
                {
                    File.Delete(logFile);
                }
            }
        }
        public void ExpandExtensionsPathFallback()
        {
            string extnTargetsFileContentTemplate = @"
                <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                    <Target Name='FromExtn'>
                        <Message Text='Running FromExtn'/>
                    </Target>
                    <Import Project='$(MSBuildExtensionsPath)\\foo\\extn.proj' Condition=""Exists('$(MSBuildExtensionsPath)\foo\extn.proj')"" />
                </Project>";

            var configFileContents = @"
                 <configuration>
                   <configSections>
                     <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
                   </configSections>
                   <msbuildToolsets default=""14.1"">
                     <toolset toolsVersion=""14.1"">
                       <property name=""MSBuildToolsPath"" value="".""/>
                       <property name=""MSBuildBinPath"" value="".""/>
                       <projectImportSearchPaths>
                         <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
                           <property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" />
                         </searchPaths>
                       </projectImportSearchPaths>
                      </toolset>
                   </msbuildToolsets>
                 </configuration>";

            string extnDir1        = null;
            string mainProjectPath = null;

            try
            {
                extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
                                                             extnTargetsFileContentTemplate);

                mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj",
                                                                                      GetMainTargetFileContent());

                ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
                var reader = GetStandardConfigurationReader();

                var projectCollection = new ProjectCollection(new Dictionary <string, string> {
                    ["FallbackExpandDir1"] = extnDir1
                });

                projectCollection.ResetToolsetsForTests(reader);
                var logger = new MockLogger();
                projectCollection.RegisterLogger(logger);

                var project = projectCollection.LoadProject(mainProjectPath);
                Assert.True(project.Build("Main"));
                logger.AssertLogContains("Running FromExtn");
            }
            finally
            {
                FileUtilities.DeleteNoThrow(mainProjectPath);
                FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
            }
        }
Ejemplo n.º 28
0
        public static Project GetProject(string projectPath, ConsoleLogger logger)
        {
            var projectCollection = new ProjectCollection();

            projectCollection.RegisterLogger(logger);
            return(projectCollection.LoadProject(projectPath));
        }
Ejemplo n.º 29
0
        public IEnumerable <RuntimeLibrary> GetRuntimeLibraries(string projectFilePath)
        {
            Logger.WriteDebug("Reading project file.");

            projectFilePath = Path.GetFullPath(projectFilePath.ToPlatformSpecificPath());

            Logger.WriteDebug($"xxxxx1 1");

            Environment.SetEnvironmentVariable(MSBuildFinder.MSBuildEnvironmentVariableName, MSBuildFinder.Find());

            Logger.WriteDebug($"xxxxx1 2");

            ProjectCollection projectCollection = new ProjectCollection();

            Logger.WriteDebug($"xxxxx1 3");

            Project project = projectCollection.LoadProject(projectFilePath);

            Logger.WriteDebug($"xxxxx1 4");

            List <RuntimeLibrary> runtimeLibraries = new List <RuntimeLibrary>();

            Logger.WriteDebug($"xxxxx1 5");

            runtimeLibraries.AddRange(GetProjectReferences(projectFilePath, projectCollection, project));
            Logger.WriteDebug($"xxxxx1 6");
            runtimeLibraries.AddRange(GetNugetReferences(projectFilePath, project));
            Logger.WriteDebug($"xxxxx1 7");
            return(runtimeLibraries);
        }
        private static bool BuildProject(string projectPath)
        {
            // Uncomment for logging
            //var logPath = Path.Combine(Path.GetDirectoryName(projectPath), "build.log");

            //.Net 4 Microsoft.Build.Evaluation.Project and ProjectCollection
            var engine = new ProjectCollection();


            /* Uncomment for logging
             * // Instantiate a new FileLogger to generate build log
             * var logger = new Microsoft.Build.Logging.FileLogger();
             *
             * // Set the logfile parameter to indicate the log destination
             * logger.Parameters = @"logfile=" + logPath;
             * // Register the logger with the engine
             * engine.RegisterLogger(logger);
             */
            // Build a project file
            bool success = engine.LoadProject(projectPath).Build();
            //Uncomment for logging
            //Unregister all loggers to close the log file
            //engine.UnregisterAllLoggers();

            //if fails, put the log file into the assert statement
            string txt = "Finished!";

            /* Uncomment for logging
             * if (!success && File.Exists(logPath))
             *  txt = File.ReadAllText(logPath);
             */
            Console.WriteLine(txt);

            return(success);
        }