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)); } } }
public static bool ThreadSafeSetGlobalProperty(this Microsoft.Build.Evaluation.Project thisp, string propertyName, string propertyValue) { lock (thisp) { return(thisp.SetGlobalProperty(propertyName, propertyValue)); } }
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); }
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 void when_getting_targets_then_does_not_include_initial_targets() { var eval = new Project("IntrospectTests.targets"); eval.SetGlobalProperty("UseCompiledTasks", "true"); var project = BuildManager.DefaultBuildManager.GetProjectInstanceForBuild(eval); IDictionary<string, TargetResult> outputs; var result = project.Build(new string[0], new[] { logger }, out outputs); Assert.True(result); Assert.True(outputs.ContainsKey("Build")); Assert.True(!outputs["Build"].Items.Select(t => t.ItemSpec).Contains("Startup")); }
public void when_introspecting_then_retrieves_current_target() { var eval = new Project("IntrospectTests.targets"); eval.SetGlobalProperty("UseCompiledTasks", "true"); var project = BuildManager.DefaultBuildManager.GetProjectInstanceForBuild(eval); IDictionary<string, TargetResult> outputs; var result = project.Build(new [] { "IntrospectTargets" }, new[] { logger }, out outputs); Assert.True(result); Assert.True(outputs.ContainsKey("IntrospectTargets")); Assert.Equal(1, outputs["IntrospectTargets"].Items.Length); var target = outputs["IntrospectTargets"].Items[0]; Assert.Equal("IntrospectTargets", target.ItemSpec); }
public void when_introspecting_then_retrieves_dynamic_value() { var eval = new Project("IntrospectTests.targets"); eval.SetGlobalProperty("UseCompiledTasks", "true"); var project = BuildManager.DefaultBuildManager.GetProjectInstanceForBuild(eval); IDictionary<string, TargetResult> outputs; project.SetProperty("PropertyName", "MSBuildRuntimeVersion"); var result = project.Build(new [] { "GetDynamicValue" }, new[] { logger }, out outputs); Assert.True(result); Assert.True(outputs.ContainsKey("GetDynamicValue")); Assert.Equal(1, outputs["GetDynamicValue"].Items.Length); var target = outputs["GetDynamicValue"].Items[0]; var expected = project.GetPropertyValue("MSBuildRuntimeVersion"); Assert.Equal(expected, target.ItemSpec); }
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); }
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"]); }
/// <summary> /// Define variables for project context from all user-variables /// </summary> /// <param name="project"></param> protected void defVariables(Project project) { foreach(TUserVariable uvar in uvariable.Variables) { if(uvar.status != TUserVariable.StatusType.Started) { project.SetGlobalProperty(uvar.ident, getUVariableValue(uvar.ident)); continue; } if(uvar.prev != null && ((TUserVariable)uvar.prev).unevaluated != null) { TUserVariable prev = (TUserVariable)uvar.prev; project.SetGlobalProperty(uvar.ident, (prev.evaluated == null)? prev.unevaluated : prev.evaluated); } } }
private void SetGlobalProperty(Microsoft.Build.Evaluation.Project msbuildProject, string propertyName, string propertyValue) { msbuildProject.SetGlobalProperty(propertyName, propertyValue); }
public void TwoProjectsDistinguishedByGlobalPropertiesOnly_ProjectOverridesProjectCollection() { Project project = new Project(); project.FullPath = "c:\\1"; // Set a global property on the project collection -- this should be passed on to all // loaded projects. ProjectCollection.GlobalProjectCollection.SetGlobalProperty("Configuration", "Debug"); Assert.Equal("Debug", project.GlobalProperties["Configuration"]); // Differentiate this project from the one below project.SetGlobalProperty("MyProperty", "MyValue"); // now create a global properties dictionary to pass to a new project Dictionary<string, string> project2Globals = new Dictionary<string, string>(); project2Globals.Add("Configuration", "Release"); project2Globals.Add("Platform", "Win32"); Project project2 = ProjectCollection.GlobalProjectCollection.LoadProject("c:\\1", project2Globals, null); Assert.Equal("Release", project2.GlobalProperties["Configuration"]); // Setting a global property on the project collection overrides all contained projects, // whether they were initially loaded with the global project collection's value or not. ProjectCollection.GlobalProjectCollection.SetGlobalProperty("Platform", "X64"); Assert.Equal("X64", project.GlobalProperties["Platform"]); Assert.Equal("X64", project2.GlobalProperties["Platform"]); // But setting a global property on the project directly should override that. project2.SetGlobalProperty("Platform", "Itanium"); Assert.Equal("Itanium", project2.GlobalProperties["Platform"]); // Now set global properties such that the two projects have an identical set. ProjectCollection.GlobalProjectCollection.SetGlobalProperty("Configuration", "Debug2"); ProjectCollection.GlobalProjectCollection.SetGlobalProperty("Platform", "X86"); bool exceptionCaught = false; try { // This will make it identical, so we should get a throw here. ProjectCollection.GlobalProjectCollection.SetGlobalProperty("MyProperty", "MyValue2"); } catch (InvalidOperationException) { exceptionCaught = true; } Assert.True(exceptionCaught); // "Should have caused the two projects to be identical, causing an exception to be thrown" }
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 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 ChangeGlobalPropertyAfterReevaluation2() { Project project = new Project(); project.SetGlobalProperty("p", "v1"); project.ReevaluateIfNecessary(); project.SetProperty("p", "v2"); }
public void ProjectXmlChangedEvent() { ProjectCollection collection = new ProjectCollection(); ProjectRootElement pre = null; bool dirtyRaised = false; collection.ProjectXmlChanged += (sender, e) => { Assert.Same(collection, sender); Assert.Same(pre, e.ProjectXml); this.TestOutput.WriteLine(e.Reason ?? String.Empty); dirtyRaised = true; }; Assert.False(dirtyRaised); // Ensure that the event is raised even when DisableMarkDirty is set. collection.DisableMarkDirty = true; // Create a new PRE but don't change the template. dirtyRaised = false; pre = ProjectRootElement.Create(collection); Assert.False(dirtyRaised); // Change PRE prior to setting a filename and thus associating the PRE with the ProjectCollection. dirtyRaised = false; pre.AppendChild(pre.CreatePropertyGroupElement()); Assert.False(dirtyRaised); // Associate with the ProjectCollection dirtyRaised = false; pre.FullPath = FileUtilities.GetTemporaryFile(); Assert.True(dirtyRaised); // Now try dirtying again and see that the event is raised this time. dirtyRaised = false; pre.AppendChild(pre.CreatePropertyGroupElement()); Assert.True(dirtyRaised); // Make sure that project collection global properties don't raise this event. dirtyRaised = false; collection.SetGlobalProperty("a", "b"); Assert.False(dirtyRaised); // Change GlobalProperties on a project to see that that doesn't propagate as an XML change. dirtyRaised = false; var project = new Project(pre); project.SetGlobalProperty("q", "s"); Assert.False(dirtyRaised); // Change XML via the Project to verify the event is raised. dirtyRaised = false; project.SetProperty("z", "y"); Assert.True(dirtyRaised); }
public void when_introspecting_then_retrieves_properties() { var eval = new Project("IntrospectTests.targets"); eval.SetGlobalProperty("UseCompiledTasks", "true"); var project = BuildManager.DefaultBuildManager.GetProjectInstanceForBuild(eval); IDictionary<string, TargetResult> outputs; var result = project.Build(new [] { "IntrospectProperties" }, new[] { logger }, out outputs); Assert.True(result); Assert.True(outputs.ContainsKey("IntrospectProperties")); Assert.Equal(1, outputs["IntrospectProperties"].Items.Length); var target = outputs["IntrospectProperties"].Items[0]; var metadata = new HashSet<string>(target.MetadataNames.OfType<string>()); Assert.True(metadata.Contains("MSBuildBinPath")); Assert.Equal("Bar", target.GetMetadata("Foo")); }
public void RemovingGlobalPropertiesOnCollectionUpdatesProjects2() { ProjectCollection collection = new ProjectCollection(); collection.SetGlobalProperty("g1", "v1"); Project project1 = new Project(collection); project1.FullPath = "c:\\y"; // load into collection project1.SetGlobalProperty("g1", "v0"); // mask collection property Helpers.ClearDirtyFlag(project1.Xml); collection.RemoveGlobalProperty("g1"); // should modify the project Assert.Equal(0, project1.GlobalProperties.Count); Assert.Equal(true, project1.IsDirty); }
public void SettingGlobalPropertiesOnCollectionUpdatesProjects2() { ProjectCollection collection = new ProjectCollection(); Project project1 = new Project(collection); project1.FullPath = "c:\\y"; // load into collection project1.SetGlobalProperty("g1", "v0"); Helpers.ClearDirtyFlag(project1.Xml); collection.SetGlobalProperty("g1", "v1"); collection.SetGlobalProperty("g2", "v2"); Assert.Equal(2, project1.GlobalProperties.Count); Assert.Equal("v1", project1.GlobalProperties["g1"]); Assert.Equal("v2", project1.GlobalProperties["g2"]); // Got overwritten Assert.Equal(true, project1.IsDirty); }
public void ChangingGlobalPropertiesUpdatesCollection() { ProjectCollection collection = new ProjectCollection(); Project project = new Project(collection); project.FullPath = "c:\\x"; // load into collection project.SetGlobalProperty("p", "v1"); // should update collection Dictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties.Add("p", "v1"); Project newProject = collection.LoadProject("c:\\x", globalProperties, null); Assert.Equal(true, Object.ReferenceEquals(project, newProject)); }
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")); }
public void ChangeGlobalPropertyAfterReevaluation2() { Assert.Throws<InvalidOperationException>(() => { Project project = new Project(); project.SetGlobalProperty("p", "v1"); project.ReevaluateIfNecessary(); project.SetProperty("p", "v2"); } ); }
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)); }
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"]); }
/// <param name="project">Uses GlobalProjectCollection if null.</param> /// <param name="name"></param> /// <param name="val"></param> /// <returns>Returns true if the value changes, otherwise returns false.</returns> protected virtual bool setGlobalProperty(Project project, string name, string val) { if(project == null) { ProjectCollection.GlobalProjectCollection.SetGlobalProperty(name, val); return true; } return project.SetGlobalProperty(name, val); }
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")); }
public void ProjectChangedEvent() { ProjectCollection collection = new ProjectCollection(); ProjectRootElement pre = null; Project project = null; bool dirtyRaised = false; collection.ProjectChanged += (sender, e) => { Assert.Same(collection, sender); Assert.Same(project, e.Project); dirtyRaised = true; }; Assert.False(dirtyRaised); pre = ProjectRootElement.Create(collection); project = new Project(pre, null, null, collection); // all these should still pass with disableMarkDirty set collection.DisableMarkDirty = true; project.DisableMarkDirty = true; dirtyRaised = false; pre.AppendChild(pre.CreatePropertyGroupElement()); Assert.False(dirtyRaised); // "Dirtying the XML directly should not result in a ProjectChanged event." // No events should be raised before we associate a filename with the PRE dirtyRaised = false; project.SetGlobalProperty("someGlobal", "someValue"); Assert.False(dirtyRaised); dirtyRaised = false; project.SetProperty("someProp", "someValue"); Assert.False(dirtyRaised); pre.FullPath = FileUtilities.GetTemporaryFile(); dirtyRaised = false; project.SetGlobalProperty("someGlobal", "someValue2"); Assert.True(dirtyRaised); dirtyRaised = false; project.RemoveGlobalProperty("someGlobal"); Assert.True(dirtyRaised); dirtyRaised = false; collection.SetGlobalProperty("somePCglobal", "someValue"); Assert.True(dirtyRaised); dirtyRaised = false; project.SetProperty("someProp", "someValue2"); Assert.True(dirtyRaised); }