Beispiel #1
0
        public void CheckReferences(string projectPath, IEnumerable <string> references, string framework)
        {
            using var projectCollection = new ProjectCollection();
            var project = new MSBuildProject(Path.Combine(_projectPath, projectPath),
                                             new Dictionary <string, string>(),
                                             null,
                                             projectCollection);
            var targetFrameworksValue = project.GetProperty("TargetFrameworks")?.EvaluatedValue ?? project.GetPropertyValue("TargetFramework");

            foreach (var targetFramework in targetFrameworksValue.Split(";", StringSplitOptions.RemoveEmptyEntries).Select(framework => framework.Trim()))
            {
                project.SetGlobalProperty("TargetFramework", targetFramework);
                project.ReevaluateIfNecessary();

                var items          = project.GetItems("ProjectReference");
                var referenceItems = items.Select(item => item.EvaluatedInclude).Select(NormalizePaths);

                if (targetFramework == framework)
                {
                    Assert.All(references, reference => Assert.Contains(reference, referenceItems));
                    Assert.All(references, reference => Assert.Equal("slnmerge", items.FirstOrDefault(item => NormalizePaths(item.EvaluatedInclude) == reference)?.GetMetadataValue("Origin")));
                }
                else
                {
                    Assert.All(references, reference => Assert.DoesNotContain(reference, referenceItems));
                }
            }
        }
        //
        // Set Ice Home and force projects to re evaluate changes in the imported project
        //
        public static void SetIceHome(List <IVsProject> projects, string iceHome, string iceVersion, string iceIntVersion, string iceVersionMM)
        {
            foreach (IVsProject p in projects)
            {
                if (DTEUtil.IsIceBuilderEnabled(p) != IceBuilderProjectType.None)
                {
                    Microsoft.Build.Evaluation.Project project = LoadedProject(ProjectUtil.GetProjectFullPath(p), DTEUtil.IsCppProject(p), true);
                    ResolvedImport import = project.Imports.FirstOrDefault(i => i.ImportedProject.FullPath.EndsWith("IceBuilder.Common.props"));

                    if (import.ImportedProject != null)
                    {
                        ProjectPropertyGroupElement group = import.ImportedProject.PropertyGroups.FirstOrDefault(
                            g => g.Label.Equals("IceHome", StringComparison.CurrentCultureIgnoreCase));
                        if (group != null)
                        {
                            group.SetProperty(Package.IceHomeValue, iceHome);
                            group.SetProperty(Package.IceVersionValue, iceVersion);
                            group.SetProperty(Package.IceIntVersionValue, iceIntVersion);
                            group.SetProperty(Package.IceVersionMMValue, iceVersionMM);
                            project.ReevaluateIfNecessary();
                        }
                    }
                }
            }
        }
Beispiel #3
0
        public static void AddImportStatement(this MsBuildProject buildProject, string targetsPath, ProjectImportLocation location)
        {
            // adds an <Import> element to this project file if it doesn't already exist.
            if (buildProject.Xml.Imports == null ||
                buildProject.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
            {
                ProjectImportElement pie = buildProject.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);
                    buildProject.Xml.InsertBeforeChild(pie, buildProject.Xml.FirstChild);
                }
                else
                {
                    // the import might get added into an ImportGroup. In this case,
                    // we remove it from the ImportGroup and add it at the end of the
                    // project.
                    if (pie.Parent.GetType() == typeof(ProjectImportGroupElement))
                    {
                        pie.Parent.RemoveChild(pie);
                        buildProject.Xml.AppendChild(pie);
                    }
                }

                NuGet.MSBuildProjectUtility.AddEnsureImportedTarget(buildProject, targetsPath);
                buildProject.ReevaluateIfNecessary();
            }
        }
Beispiel #4
0
        private async Task ReevaluateLoadedConfiguredProjects(CancellationToken cancellationToken, ProjectWriteLockReleaser access)
        {
            foreach (var configuredProject in _unconfiguredProject.LoadedConfiguredProjects)
            {
                try {
                    MsBuildProject jsproj = await access.GetProjectAsync(configuredProject, cancellationToken);

                    jsproj.ReevaluateIfNecessary();
                } catch (Exception ex) {
                    Debug.Fail("We were unable to mark a configuration as dirty" + ex.Message, ex.StackTrace);
                }
            }
        }
Beispiel #5
0
        private static string GetPropertyValueFrom(string projectFile, string propertyName, string solutionDir, string configurationName)
        {
            using (var projectCollection = new ProjectCollection())
            {
                var p = new Project(projectFile, null, null, projectCollection, ProjectLoadSettings.Default);

                p.SetProperty("Configuration", configurationName);
                p.SetProperty("SolutionDir", solutionDir);
                p.SetGlobalProperty("SolutionDir", solutionDir);
                p.ReevaluateIfNecessary();
                return(p.Properties.Where(x => x.Name == propertyName).Select(x => x.EvaluatedValue).SingleOrDefault());
            }
        }
        public static void RemoveImportStatement(this MsBuildProject buildProject, string targetsPath)
        {
            if (buildProject.Xml.Imports != null)
            {
                // search for this import statement and remove it
                var importElement = buildProject.Xml.Imports.FirstOrDefault(
                    import => targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase));

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

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

                if (importElement != null)
                {
                    importElement.Parent.RemoveChild(importElement);
                    RemoveEnsureImportedTarget(msBuildProject, targetsPath);
                    msBuildProject.ReevaluateIfNecessary();
                }
            }
        }
Beispiel #9
0
        public bool TryGetOutputDirectory(string configuration, string platform, out DirectoryInfo outputDirectory)
        {
            _evaluatedProject.SetGlobalProperty("Configuration", configuration);
            _evaluatedProject.SetGlobalProperty("Platform", platform);
            _evaluatedProject.ReevaluateIfNecessary();

            var outputPathProperty = _evaluatedProject.GetProperty("OutputPath");

            if (outputPathProperty != null)
            {
                var absolutePath = Path.Combine(Directory.FullName, outputPathProperty.EvaluatedValue);
                outputDirectory = new DirectoryInfo(absolutePath);
                return(true);
            }

            outputDirectory = null;
            return(false);
        }
        public void SpecialCharactersInMetadataValueEvaluation()
        {
            Microsoft.Build.Evaluation.Project project = new Microsoft.Build.Evaluation.Project();
            var metadata = new Dictionary <string, string>
            {
                { "EscapedSemicolon", "%3B" },  // Microsoft.Build.Internal.Utilities.Escape(";")
                { "EscapedDollarSign", "%24" }, // Microsoft.Build.Internal.Utilities.Escape("$")
            };

            Microsoft.Build.Evaluation.ProjectItem item = project.AddItem(
                "None",
                "MetadataTests",
                metadata).Single();

            SpecialCharactersInMetadataValueTests(item);
            project.ReevaluateIfNecessary();
            SpecialCharactersInMetadataValueTests(item);
        }
Beispiel #11
0
        private async Task FileSystemChanged(MsBuildFileSystemWatcher.Changeset changeset)
        {
            _log.ApplyProjectChangesStarted();

            if (_unloadCancellationToken.IsCancellationRequested)
            {
                return;
            }

            try {
                using (var access = await _projectLockService.WriteLockAsync(_unloadCancellationToken)) {
                    await access.CheckoutAsync(_inMemoryImportFullPath);

                    _temporaryAddedItemGroup.RemoveAllChildren();

                    await RemoveFiles(changeset.RemovedFiles, access);
                    await RemoveDirectories(changeset.RemovedDirectories, access);

                    await RenameFiles(changeset.RenamedFiles, access);
                    await RenameDirectories(changeset.RenamedDirectories, access);

                    AddDirectories(changeset.AddedDirectories);
                    AddFiles(changeset.AddedFiles);

                    _log.MsBuildAfterChangesApplied(_inMemoryImport);

                    foreach (var configuredProject in _unconfiguredProject.LoadedConfiguredProjects)
                    {
                        try {
                            MsBuildProject project =
                                await access.GetProjectAsync(configuredProject, _unloadCancellationToken);

                            project.ReevaluateIfNecessary();
                        } catch (Exception ex) {
                            Trace.Fail("Unable to mark a configuration as dirty" + ex.Message, ex.StackTrace);
                        }
                    }
                }
            } catch (Exception ex) {
                Trace.Fail("Unable to handle file system change:" + ex.Message, ex.StackTrace);
            }

            _log.ApplyProjectChangesFinished();
        }
        internal static void AddImportStatement(MicrosoftBuildEvaluationProject msBuildProject, string targetsPath, ImportLocation location)
        {
            if (msBuildProject.Xml.Imports == null ||
                msBuildProject.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
            {
                ProjectImportElement pie = msBuildProject.Xml.AddImport(targetsPath);
                pie.Condition = "Exists('" + targetsPath + "')";
                if (location == ImportLocation.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);
                    msBuildProject.Xml.InsertBeforeChild(pie, msBuildProject.Xml.FirstChild);
                }

                AddEnsureImportedTarget(msBuildProject, targetsPath);
                msBuildProject.ReevaluateIfNecessary();
            }
        }
        public static void AddImportStatement(this MsBuildProject buildProject, string targetsPath, ProjectImportLocation location)
        {
            // adds an <Import> element to this project file if it doesn't already exist.
            if (buildProject.Xml.Imports == null ||
                buildProject.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
            {
                ProjectImportElement pie = buildProject.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);
                    buildProject.Xml.InsertBeforeChild(pie, buildProject.Xml.FirstChild);
                }

                buildProject.ReevaluateIfNecessary();
            }
        }
Beispiel #14
0
        internal static void AddImportStatement(MicrosoftBuildEvaluationProject msBuildProject, string targetsPath, ImportLocation location)
        {
            if (msBuildProject.Xml.Imports == null ||
                msBuildProject.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
            {
                ProjectImportElement pie = msBuildProject.Xml.AddImport(targetsPath);
                pie.Condition = "Exists('" + targetsPath + "')";
                if (location == ImportLocation.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);
                    msBuildProject.Xml.InsertBeforeChild(pie, msBuildProject.Xml.FirstChild);
                }

                AddEnsureImportedTarget(msBuildProject, targetsPath);
                msBuildProject.ReevaluateIfNecessary();
            }
        }
        //
        // Set Ice Home and force projects to re evaluate changes in the imported project
        //
        public static void SetIceHome(List <EnvDTE.Project> projects, String iceHome, String iceVersion, String iceIntVersion, String iceVersionMM)
        {
            foreach (EnvDTE.Project p in projects)
            {
                Microsoft.Build.Evaluation.Project project = MSBuildUtils.LoadedProject(p.FullName);
                ResolvedImport import = project.Imports.FirstOrDefault(i => i.ImportedProject.FullPath.EndsWith("IceBuilder.Common.props"));

                if (import.ImportedProject != null)
                {
                    ProjectPropertyGroupElement group = import.ImportedProject.PropertyGroups.FirstOrDefault(g => g.Label.Equals("IceHome"));
                    if (group != null)
                    {
                        group.SetProperty(Package.IceHomeValue, iceHome);
                        group.SetProperty(Package.IceVersionValue, iceVersion);
                        group.SetProperty(Package.IceIntVersionValue, iceIntVersion);
                        group.SetProperty(Package.IceVersionMMValue, iceVersionMM);
                        project.ReevaluateIfNecessary();
                    }
                }
            }
        }
Beispiel #16
0
        public void ExternallyMarkDirty()
        {
            Project project = new Project();
            project.SetProperty("p", "v");
            project.ReevaluateIfNecessary();

            Assert.Equal(false, project.IsDirty);

            ProjectProperty property1 = project.GetProperty("p");

            project.MarkDirty();

            Assert.Equal(true, project.IsDirty);

            project.ReevaluateIfNecessary();

            Assert.Equal(false, project.IsDirty);

            ProjectProperty property2 = project.GetProperty("p");

            Assert.Equal(false, Object.ReferenceEquals(property1, property2)); // different object indicates reevaluation occurred
        }
Beispiel #17
0
        public void ImportedXmlModified()
        {
            string path = null;

            try
            {
                path = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                ProjectRootElement import = ProjectRootElement.Create(path);
                import.Save();

                Project project = new Project();
                int last = project.EvaluationCounter;

                project.Xml.AddImport(path);
                project.ReevaluateIfNecessary();
                Assert.NotEqual(project.EvaluationCounter, last);
                last = project.EvaluationCounter;

                project.ReevaluateIfNecessary();
                Assert.Equal(project.EvaluationCounter, last);

                import.AddProperty("p", "v");
                Assert.Equal(true, project.IsDirty);
                project.ReevaluateIfNecessary();
                Assert.NotEqual(project.EvaluationCounter, last);
                last = project.EvaluationCounter;
                Assert.Equal("v", project.GetPropertyValue("p"));

                project.ReevaluateIfNecessary();
                Assert.Equal(project.EvaluationCounter, last);
            }
            finally
            {
                File.Delete(path);
            }
        }
        /// <summary>
        /// This is used to create a Sandcastle Builder project from an existing MSBuild project instance
        /// </summary>
        /// <param name="existingProject">The existing project instance</param>
        /// <remarks>It is assumed that the project has been loaded, the property values are current, and that
        /// the configuration and platform have been set in the MSBuild project global properties in order to
        /// get the correct final values.</remarks>
        public SandcastleProject(Project existingProject) : this()
        {
            // Do not remove the project from the MSBuild project collection when this is disposed of since we
            // didn't create it.
            removeProjectWhenDisposed = false;

            msBuildProject = existingProject;
            msBuildProject.ReevaluateIfNecessary();

            this.UsingFinalValues = true;
            this.LoadProperties();
        }
Beispiel #19
0
        public static async Task <Project> CreateAsync(string filepath, Solution parent, IOutputWriter outputWriter)
        {
            filepath = Path.GetFullPath(filepath, Path.GetDirectoryName(parent.Filepath));

            if (!File.Exists(filepath))
            {
                throw new FileReadException(FileReadExceptionType.Csproj, filepath, parent.Filepath);
            }

            using var projectCollection = new ProjectCollection();
            var msbuildProject   = new Microsoft.Build.Evaluation.Project(filepath, new Dictionary <string, string>(), null, projectCollection, ProjectLoadSettings.IgnoreInvalidImports | ProjectLoadSettings.IgnoreMissingImports);
            var usingSdk         = msbuildProject.Properties.FirstOrDefault(prop => prop.Name == "UsingMicrosoftNETSdk")?.EvaluatedValue.Equals("true", StringComparison.InvariantCultureIgnoreCase) ?? false;
            var targetFrameworks = Array.Empty <string>();

            if (usingSdk)
            {
                targetFrameworks = msbuildProject.GetProperty("TargetFrameworks") switch
                {
                    ProjectProperty pp => pp.EvaluatedValue.Split(';', StringSplitOptions.RemoveEmptyEntries).Select(val => val.Trim()).ToArray(),
                    null => new[] { msbuildProject.GetPropertyValue("TargetFramework") }
                };
            }
            else
            {
                targetFrameworks = new[] {
                    msbuildProject.GetPropertyValue("TargetFrameworkVersion")
                    .Replace("v", "net")
                    .Replace(".", "")
                };
            }

            var packageReferences = new Dictionary <string, Reference>();
            var projectReferences = new Dictionary <string, Reference>();

            foreach (var targetFramework in targetFrameworks)
            {
                msbuildProject.SetGlobalProperty("TargetFramework", targetFramework);
                msbuildProject.ReevaluateIfNecessary();

                foreach (var include in GetItems(msbuildProject, "PackageReference"))
                {
                    if (!packageReferences.TryGetValue(include, out var reference))
                    {
                        reference = new Reference
                        {
                            Include = include
                        };
                        packageReferences.Add(include, reference);
                    }

                    reference.Frameworks.Add(targetFramework);
                }

                foreach (var item in msbuildProject.GetItems("ProjectReference"))
                {
                    var include = ConvertPathSeparators(item.EvaluatedInclude);

                    if (!projectReferences.TryGetValue(include, out var reference))
                    {
                        reference = new Reference
                        {
                            Include = include,
                            Origin  = item.GetMetadataValue("Origin")
                        };
                        projectReferences.Add(include, reference);
                    }

                    reference.Frameworks.Add(targetFramework);
                }
            }

            var packageId = await GetPackageId(filepath, msbuildProject);

            return(new Project(filepath, packageId, packageReferences.Values.ToList(), projectReferences.Values.ToList(), targetFrameworks, outputWriter, parent, !usingSdk));
        }
Beispiel #20
0
        public void DoubleImportIndirectIgnored()
        {
            string file = null;
            string file2 = null;
            string file3 = null;

            try
            {
                ProjectCollection collection = new ProjectCollection();
                MockLogger logger = new MockLogger();
                collection.RegisterLogger(logger);

                file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                file2 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                file3 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();

                Project project = new Project(collection);
                project.Xml.AddImport(file2);
                project.Xml.AddImport(file3);
                project.Save(file);

                Project project2 = new Project(collection);
                project.Xml.AddImport(file3);
                project2.Save(file2);

                Project project3 = new Project(collection);
                project3.Save(file3);

                project.ReevaluateIfNecessary();

                logger.AssertLogContains("MSB4011"); // duplicate import
            }
            finally
            {
                File.Delete(file);
                File.Delete(file2);
                File.Delete(file3);
            }
        }
Beispiel #21
0
        public void ItemsByEvaluatedIncludeReevaluation()
        {
            Project project = new Project();
            project.Xml.AddItem("i", "i1");
            project.ReevaluateIfNecessary();

            List<ProjectItem> items = Helpers.MakeList(project.GetItemsByEvaluatedInclude("i1"));
            Assert.Equal(1, items.Count);

            project.Xml.AddItem("j", "i1");
            project.ReevaluateIfNecessary();

            items = Helpers.MakeList(project.GetItemsByEvaluatedInclude("i1"));
            Assert.Equal(2, items.Count);
        }
Beispiel #22
0
        public void ChangeEnvironmentProperty()
        {
            Project project = new Project();
            project.SetProperty("computername", "v1");

            Assert.Equal("v1", project.GetPropertyValue("computername"));
            Assert.Equal(true, project.IsDirty);

            project.ReevaluateIfNecessary();

            Assert.Equal("v1", project.GetPropertyValue("computername"));
        }
Beispiel #23
0
        public void SkipEvaluation()
        {
            Project project = new Project();
            project.SetGlobalProperty("p", "v1");
            project.ReevaluateIfNecessary();
            Assert.Equal("v1", project.GetPropertyValue("p"));

            project.SkipEvaluation = true;
            ProjectPropertyElement propertyElement = project.Xml.AddProperty("p1", "v0");
            propertyElement.Condition = "'$(g)'=='v1'";
            project.SetGlobalProperty("g", "v1");
            project.ReevaluateIfNecessary();
            Assert.Equal(String.Empty, project.GetPropertyValue("p1"));

            project.SkipEvaluation = false;
            project.SetGlobalProperty("g", "v1");
            project.ReevaluateIfNecessary();
            Assert.Equal("v0", project.GetPropertyValue("p1"));
        }
Beispiel #24
0
        public void ChangeGlobalProperties()
        {
            Project project = new Project();
            ProjectPropertyElement propertyElement = project.Xml.AddProperty("p", "v0");
            propertyElement.Condition = "'$(g)'=='v1'";
            project.ReevaluateIfNecessary();
            Assert.Equal(String.Empty, project.GetPropertyValue("p"));

            Assert.Equal(true, project.SetGlobalProperty("g", "v1"));
            Assert.Equal(true, project.IsDirty);
            project.ReevaluateIfNecessary();
            Assert.Equal("v0", project.GetPropertyValue("p"));
            Assert.Equal("v1", project.GlobalProperties["g"]);
        }
Beispiel #25
0
        public void ItemsByEvaluatedInclude()
        {
            Project project = new Project();
            project.Xml.AddItem("i", "i1");
            project.Xml.AddItem("i", "i1");
            project.Xml.AddItem("j", "j1");
            project.Xml.AddItem("j", "i1");

            project.ReevaluateIfNecessary();

            List<ProjectItem> items = Helpers.MakeList(project.GetItemsByEvaluatedInclude("i1"));

            Assert.Equal(3, items.Count);
            foreach (ProjectItem item in items)
            {
                Assert.Equal("i1", item.EvaluatedInclude);
            }
        }
Beispiel #26
0
        public void ItemsByEvaluatedInclude_EvaluatedIncludeNeedsEscaping()
        {
            Project project = new Project();
            project.Xml.AddItem("i", "i%261");
            project.Xml.AddItem("j", "i%25261");
            project.Xml.AddItem("k", "j1");
            project.Xml.AddItem("l", "i&1");

            project.ReevaluateIfNecessary();

            List<ProjectItem> items = Helpers.MakeList(project.GetItemsByEvaluatedInclude("i&1"));

            Assert.Equal(2, items.Count);
            foreach (ProjectItem item in items)
            {
                Assert.Equal("i&1", item.EvaluatedInclude);
                Assert.True(
                    String.Equals(item.ItemType, "i", StringComparison.OrdinalIgnoreCase) ||
                    String.Equals(item.ItemType, "l", StringComparison.OrdinalIgnoreCase)
                    );
            }
        }
Beispiel #27
0
        public void ChangeGlobalPropertiesInitiallyFromProjectCollection()
        {
            Dictionary<string, string> initial = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            initial.Add("p0", "v0");
            initial.Add("p1", "v1");
            ProjectCollection collection = new ProjectCollection(initial, null, ToolsetDefinitionLocations.ConfigurationFile);
            Project project = new Project(collection);
            ProjectPropertyElement propertyElement = project.Xml.AddProperty("pp", "vv");
            propertyElement.Condition = "'$(p0)'=='v0' and '$(p1)'=='v1b'";
            project.ReevaluateIfNecessary();
            Assert.Equal(String.Empty, project.GetPropertyValue("pp"));

            project.SetGlobalProperty("p1", "v1b");
            Assert.Equal(true, project.IsDirty);
            project.ReevaluateIfNecessary();
            Assert.Equal("vv", project.GetPropertyValue("pp"));
            Assert.Equal("v0", collection.GlobalProperties["p0"]);
            Assert.Equal("v1", collection.GlobalProperties["p1"]);
        }
Beispiel #28
0
        public void ImportSelfIgnored()
        {
            string file = null;

            try
            {
                ProjectCollection collection = new ProjectCollection();
                MockLogger logger = new MockLogger();
                collection.RegisterLogger(logger);

                Project project = new Project(collection);
                project.Xml.AddImport("$(MSBuildProjectFullPath)");

                file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                project.Save(file);
                project.ReevaluateIfNecessary();

                logger.AssertLogContains("MSB4210"); // selfimport
            }
            finally
            {
                File.Delete(file);
            }
        }
Beispiel #29
0
        public void RemoveGlobalProperties()
        {
            Project project = new Project();
            ProjectPropertyElement propertyElement = project.Xml.AddProperty("p", "v0");
            propertyElement.Condition = "'$(g)'==''";
            project.SetGlobalProperty("g", "v1");
            project.ReevaluateIfNecessary();
            Assert.Equal(String.Empty, project.GetPropertyValue("p"));

            bool existed = project.RemoveGlobalProperty("g");
            Assert.Equal(true, existed);
            Assert.Equal(true, project.IsDirty);
            project.ReevaluateIfNecessary();
            Assert.Equal("v0", project.GetPropertyValue("p"));
            Assert.Equal(false, project.GlobalProperties.ContainsKey("g"));
        }
Beispiel #30
0
        public void TransformsUseCorrectDirectory_Basic()
        {
            string file = null;

            string projectFileContent = ObjectModelHelpers.CleanupFileContents(@"
                    <Project xmlns='msbuildnamespace'>
                        <ItemGroup>
                            <IntermediateAssembly Include='obj\i386\foo.dll'/>
                            <BuiltProjectOutputGroupKeyOutput Include=""@(IntermediateAssembly->'%(FullPath)')""/>
                        </ItemGroup>
                    </Project>");

            ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)));

            Project project = new Project(xml);

            try
            {
                file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                project.Save(file);
                project.ReevaluateIfNecessary();

                Assert.Equal(Path.Combine(Path.GetTempPath(), @"obj\i386\foo.dll"), project.GetItems("BuiltProjectOutputGroupKeyOutput").First().EvaluatedInclude);
            }
            finally
            {
                File.Delete(file);
            }
        }
        public void SettingItemExcludeDirties()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("i", "i1")[0];
            project.ReevaluateIfNecessary();

            item.Xml.Exclude = "i1";
            project.ReevaluateIfNecessary();

            Assert.Equal(0, Helpers.MakeList(project.Items).Count);
        }
Beispiel #32
0
        public void ChangeGlobalPropertyAfterReevaluation()
        {
            Project project = new Project();
            project.SetGlobalProperty("p", "v1");
            project.ReevaluateIfNecessary();
            project.SetGlobalProperty("p", "v2");

            Assert.Equal("v2", project.GetPropertyValue("p"));
            Assert.Equal(true, project.GetProperty("p").IsGlobalProperty);
        }
Beispiel #33
0
        /// <summary>
        /// Sets the value of the property.
        /// </summary>
        /// <param name="value">Property value to set.</param>
        /// <param name="configs">Optional list of configurations to set the property in;
        /// defaults to the project current configuration</param>
        /// <remarks>
        /// Before calling this method, the caller must ensure that the value is valid according to
        /// the <see cref="PropertyValidator"/> class, and that the project file is writable.
        /// In most cases the caller should also ensure that the new value is different from the
        /// existing value, to avoid dirtying the project file unnecessarily.
        /// </remarks>
        public void SetValue(string value, IList <ProjectConfig> configs)
        {
            WixHelperMethods.VerifyNonNullArgument(value, "value");

            value = value.Trim();

            MSBuild.Project buildProject = this.project.BuildProject;
            if (this.PerUser)
            {
                if (this.project.UserBuildProject == null)
                {
                    this.project.CreateUserBuildProject();
                }

                buildProject = this.project.UserBuildProject;
            }

            value = this.Escape(value);

            if (this.PerConfig)
            {
                if (configs == null || configs.Count == 0)
                {
                    configs = new ProjectConfig[] { this.project.CurrentConfig };
                }

                foreach (ProjectConfig config in configs)
                {
                    bool set = false;

                    // First see if there's an existing property group that matches our condition
                    foreach (ProjectPropertyGroupElement propGroup in buildProject.Xml.PropertyGroups)
                    {
                        // if there is, set it within that group
                        if (String.Equals(propGroup.Condition, config.Condition, StringComparison.Ordinal))
                        {
                            propGroup.SetProperty(this.propertyName, value);
                            set = true;
                            break;
                        }
                    }

                    // If not, add a new property group for the condition and set the property within it
                    if (!set)
                    {
                        ProjectPropertyGroupElement newPropGroup = buildProject.Xml.AddPropertyGroup();
                        newPropGroup.Condition = config.Condition;
                        newPropGroup.SetProperty(this.propertyName, value);
                        set = true;
                    }

                    buildProject.ReevaluateIfNecessary();
                }
            }
            else
            {
                if (this.EndOfProjectFile)
                {
                    List <ProjectPropertyGroupElement> propertyGroupsToDelete = new List <ProjectPropertyGroupElement>();

                    // First see if there's an existing property group with our property
                    foreach (ProjectPropertyGroupElement propGroup in buildProject.Xml.PropertyGroups)
                    {
                        List <ProjectPropertyElement> propertiesToDelete = new List <ProjectPropertyElement>();
                        if (!String.IsNullOrEmpty(propGroup.Condition))
                        {
                            continue;
                        }

                        foreach (ProjectPropertyElement property in propGroup.Properties)
                        {
                            // if there is, remove it so the new value is at the end of the file
                            if (String.IsNullOrEmpty(property.Condition) && String.Equals(property.Name, this.propertyName, StringComparison.OrdinalIgnoreCase))
                            {
                                propertiesToDelete.Add(property);
                            }
                        }

                        foreach (ProjectPropertyElement property in propertiesToDelete)
                        {
                            propGroup.RemoveChild(property);
                        }

                        if (propGroup.Count == 0)
                        {
                            propertyGroupsToDelete.Add(propGroup);
                        }
                    }

                    foreach (ProjectPropertyGroupElement propGroup in propertyGroupsToDelete)
                    {
                        buildProject.Xml.RemoveChild(propGroup);
                    }

                    ProjectPropertyGroupElement newPropGroup = buildProject.Xml.CreatePropertyGroupElement();
                    buildProject.Xml.AppendChild(newPropGroup);
                    newPropGroup.SetProperty(this.propertyName, value);
                }
                else
                {
                    buildProject.SetProperty(this.propertyName, value);
                }
            }

            this.project.InvalidatePropertyCache();
            this.project.SetProjectFileDirty(true);
        }
Beispiel #34
0
 public void ChangeGlobalPropertyAfterReevaluation2()
 {
     Assert.Throws<InvalidOperationException>(() =>
     {
         Project project = new Project();
         project.SetGlobalProperty("p", "v1");
         project.ReevaluateIfNecessary();
         project.SetProperty("p", "v2");
     }
    );
 }
        public void SetUnchangedValue()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("i", "i1")[0];
            item.SetMetadataValue("m", "m1");
            project.ReevaluateIfNecessary();

            item.SetMetadataValue("m", "m1");

            Assert.AreEqual(false, project.IsDirty);

            item.GetMetadata("m").UnevaluatedValue = "m1";

            Assert.AreEqual(false, project.IsDirty);
        }
Beispiel #36
0
        public void ChangeGlobalPropertiesPreexisting()
        {
            Dictionary<string, string> initial = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            initial.Add("p0", "v0");
            initial.Add("p1", "v1");
            Project project = new Project(ProjectRootElement.Create(), initial, null);
            ProjectPropertyElement propertyElement = project.Xml.AddProperty("pp", "vv");
            propertyElement.Condition = "'$(p0)'=='v0' and '$(p1)'=='v1b'";
            project.ReevaluateIfNecessary();
            Assert.Equal(String.Empty, project.GetPropertyValue("pp"));

            project.SetGlobalProperty("p1", "v1b");
            Assert.Equal(true, project.IsDirty);
            project.ReevaluateIfNecessary();
            Assert.Equal("vv", project.GetPropertyValue("pp"));
            Assert.Equal("v0", project.GlobalProperties["p0"]);
            Assert.Equal("v1b", project.GlobalProperties["p1"]);
        }
        public void Dirtying_ItemCondition()
        {
            XmlReader content = XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemGroup>
    <i Include=""i1"" />
  </ItemGroup>
</Project>")));

            Project project = new Project(content);
            ProjectItem item = Helpers.GetFirst(project.Items);

            item.Xml.Condition = "false";

            Assert.Equal(1, Helpers.Count(project.Items));

            project.ReevaluateIfNecessary();

            Assert.Equal(0, Helpers.Count(project.Items));
        }
Beispiel #38
0
        public void ChangeGlobalPropertiesSameValue()
        {
            Project project = new Project();
            project.SetGlobalProperty("g", "v1");
            Assert.Equal(true, project.IsDirty);
            project.ReevaluateIfNecessary();

            Assert.Equal(false, project.SetGlobalProperty("g", "v1"));
            Assert.Equal(false, project.IsDirty);
        }
        public void Dirtying_MetadataCondition()
        {
            XmlReader content = XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemGroup>
    <i Include=""i1"">
      <m>m1</m>
    </i>
  </ItemGroup>
</Project>")));

            Project project = new Project(content);
            ProjectMetadata metadatum = Helpers.GetFirst(project.Items).GetMetadata("m");

            metadatum.Xml.Condition = "false";

            Assert.Equal("m1", metadatum.EvaluatedValue);

            project.ReevaluateIfNecessary();
            metadatum = Helpers.GetFirst(project.Items).GetMetadata("m");

            Assert.Equal(null, metadatum);
        }
        public void SettingItemIncludeDirties()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("i", "i1")[0];
            project.ReevaluateIfNecessary();

            item.Xml.Include = "i2";
            project.ReevaluateIfNecessary();

            Assert.Equal("i2", Helpers.GetFirst(project.Items).EvaluatedInclude);
        }
Beispiel #41
0
        public void ProjectToolsVersion20NotPresent()
        {
            if (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version20) != null)
            {
                // "Requires 2.0 to NOT be installed"
                return;
            }

            Project project = new Project();
            project.Xml.ToolsVersion = "2.0";
            project.ReevaluateIfNecessary();

            Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.ToolsVersion);

            project.Xml.ToolsVersion = ObjectModelHelpers.MSBuildDefaultToolsVersion;

            Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.ToolsVersion);
        }
        public void SpecialCharactersInMetadataValueEvaluation()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("None", "MetadataTests", new Dictionary<string, string> {
                {"EscapedSemicolon", "%3B"}, //Microsoft.Build.Evaluation.ProjectCollection.Escape(";")
                {"EscapedDollarSign", "%24"}, //Microsoft.Build.Evaluation.ProjectCollection.Escape("$")
            }).Single();

            EscapingInProjectsHelper.SpecialCharactersInMetadataValueTests(item);
            project.ReevaluateIfNecessary();
            EscapingInProjectsHelper.SpecialCharactersInMetadataValueTests(item);
        }
Beispiel #43
0
        public void MSBuildToolsVersionProperty()
        {
            if (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version20) == null)
            {
                // "Requires 2.0 to be installed"
                return;
            }

            Project project = new Project();
            project.Xml.ToolsVersion = "2.0";
            project.ReevaluateIfNecessary();

            // ... and after all that, we end up defaulting to the current ToolsVersion instead.  There's a way 
            // to turn this behavior (new in Dev12) off, but it requires setting an environment variable and 
            // clearing some internal state to make sure that the update environment variable is picked up, so 
            // there's not a good way of doing it from these deliberately public OM only tests. 
            Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.GetPropertyValue("msbuildtoolsversion"));

            project.Xml.ToolsVersion = "4.0";

            // Still current
            Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.GetPropertyValue("msbuildtoolsversion"));

            project.ReevaluateIfNecessary();

            // Still current
            Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.GetPropertyValue("msbuildtoolsversion"));
        }
Beispiel #44
0
        public void TestRunPythonCommand() {
            var expectedSearchPath = string.Format("['{0}', '{1}']",
                TestData.GetPath(@"TestData").Replace("\\", "\\\\"),
                TestData.GetPath(@"TestData\HelloWorld").Replace("\\", "\\\\")
            );

            var proj = new Project(TestData.GetPath(@"TestData\Targets\Commands4.pyproj"));

            foreach (var version in PythonPaths.Versions) {
                var verStr = version.Version.ToVersion().ToString();
                proj.SetProperty("InterpreterId", version.Id.ToString("B"));
                proj.SetProperty("InterpreterVersion", verStr);
                proj.RemoveItems(proj.ItemsIgnoringCondition.Where(i => i.ItemType == "InterpreterReference").ToArray());
                proj.AddItem("InterpreterReference", string.Format("{0:B}\\{1}", version.Id, verStr));
                proj.Save();
                proj.ReevaluateIfNecessary();

                var log = new StringLogger(LoggerVerbosity.Minimal);
                Assert.IsTrue(proj.Build("CheckCode", new ILogger[] { new ConsoleLogger(LoggerVerbosity.Detailed), log }));
                
                Console.WriteLine();
                Console.WriteLine("Output from {0:B} {1}", version.Id, version.Version.ToVersion());
                foreach (var line in log.Lines) {
                    Console.WriteLine("* {0}", line.TrimEnd('\r', '\n'));
                }

                var logLines = log.Lines.Last().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                Assert.AreEqual(2, logLines.Length);
                Assert.AreEqual(version.Version.ToVersion().ToString(), logLines[0].Trim());
                Assert.AreEqual(expectedSearchPath, logLines[1].Trim());
            }
        }
Beispiel #45
0
        public void ReevaluationCounter()
        {
            Project project = new Project();
            int last = project.EvaluationCounter;

            project.ReevaluateIfNecessary();
            Assert.Equal(project.EvaluationCounter, last);
            last = project.EvaluationCounter;

            project.SetProperty("p", "v");
            project.ReevaluateIfNecessary();
            Assert.NotEqual(project.EvaluationCounter, last);
        }