public static bool ThreadSafeRemoveItem(this Microsoft.Build.Evaluation.Project thisp, ProjectItem item) { lock (thisp) { try { if (thisp != item.Project) { ICollection <ProjectItem> foundItem = thisp.GetItemsByEvaluatedInclude(item.EvaluatedInclude); if (foundItem == null || foundItem.Count != 1) { Trace.WriteLine("Attempt to remove item with wrong project evaluated include returned with more than one item or null item"); return(false); } return(thisp.RemoveItem(foundItem.FirstOrDefault())); } return(thisp.RemoveItem(item)); } catch (Exception) { return(false); } } }
public void LinkToFile(Project project, BuildAction buildAction, string includeValue, string projectTargetPath) { if(projectTargetPath.StartsWith("\\")) throw new Exception("project target path cannot begin with a backslash"); var matchingProjectItemByTargetPath = (from t in project.Items where t.HasMetadata("Link") && t.GetMetadataValue("Link") == projectTargetPath select t).SingleOrDefault(); if (matchingProjectItemByTargetPath != null) project.RemoveItem(matchingProjectItemByTargetPath); var buildActionName = Enum.GetName(typeof(BuildAction), buildAction); project.AddItem(buildActionName, includeValue, new[] {new KeyValuePair<string, string>("Link", projectTargetPath)}); }
public void RemoveItemOutdatedByUpdate() { string projectOriginalContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' DefaultTargets='Build' xmlns='msbuildnamespace'> <ItemGroup> <Compile Include='a.cs' /> </ItemGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(projectOriginalContents))); ProjectItem itemToRemove = Helpers.GetFirst(project.GetItems("Compile")); itemToRemove.UnevaluatedInclude = "b.cs"; project.RemoveItem(itemToRemove); // should not throw Assert.Equal(0, Helpers.MakeList(project.Items).Count); }
public void ItemsByEvaluatedIncludeDirectRemove() { Project project = new Project(); ProjectItem item1 = project.AddItem("i", "i1;j1")[0]; project.RemoveItem(item1); List<ProjectItem> items = Helpers.MakeList(project.GetItemsByEvaluatedInclude("i1")); Assert.Equal(0, items.Count); }
public void ItemsByEvaluatedIncludeAndExpansion() { List<string> filePaths = new List<string>(); string testFileRoot = null; try { int count = 0; testFileRoot = Path.Combine(Path.GetTempPath(), "foodir"); Directory.CreateDirectory(testFileRoot); int maxFiles = 2; for (int i = 0; i < maxFiles; i++) { string fileName = String.Format("foo{0}.foo", i); string filePath = Path.Combine(testFileRoot, fileName); File.WriteAllText(filePath, String.Empty); filePaths.Add(filePath); } ProjectRootElement projectConstruction = ProjectRootElement.Create(); projectConstruction.AddItem("foo", Path.Combine(testFileRoot, "*.foo")); count = Helpers.Count(projectConstruction.Items); Assert.Equal(1, count); // "Construction Model" Project project = new Project(projectConstruction); count = Helpers.Count(project.GetItems("foo")); Assert.Equal(2, count); // "Evaluation Model, Before Removal" ProjectItem itemToRemove = null; // Get the first item from IEnumerable Collection. foreach (ProjectItem item in project.Items) { itemToRemove = item; break; } project.RemoveItem(itemToRemove); count = Helpers.Count(project.GetItems("foo")); Assert.Equal(1, count); // "Evaluation Model, After Removal" ProjectInstance projectInstance = project.CreateProjectInstance(); count = Helpers.Count(projectInstance.Items); Assert.Equal(1, count); // "Instance Model" // Ensure XML has been updated accordingly on the Evaluation model (projectInstance doesn't back onto XML) Assert.False(project.Xml.RawXml.Contains(itemToRemove.Xml.Include)); Assert.False(project.Xml.RawXml.Contains("*.foo")); } finally { foreach (string filePathToRemove in filePaths) { File.Delete(filePathToRemove); } Directory.Delete(testFileRoot); } }
public void RemoveItem_IncludingFromIgnoringConditionList() { XmlReader content = XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <ItemGroup Condition=""false""> <i Include=""i1"" /> </ItemGroup> </Project>"))); Project project = new Project(content); Assert.Equal(0, Helpers.MakeList(project.GetItems("i")).Count); List<ProjectItem> itemsIgnoringCondition = Helpers.MakeList(project.GetItemsIgnoringCondition("i")); Assert.Equal(1, itemsIgnoringCondition.Count); ProjectItem item = itemsIgnoringCondition[0]; Assert.Equal("i1", item.EvaluatedInclude); bool result = project.RemoveItem(item); Assert.Equal(false, result); // false as it was not in the regular items collection itemsIgnoringCondition = Helpers.MakeList(project.GetItemsIgnoringCondition("i")); Assert.Equal(0, itemsIgnoringCondition.Count); }
public void RemoveItem_OriginatingWithWildcard() { string[] paths = null; try { paths = Helpers.CreateFiles("i1.xxx", "i2.xxx"); string directory = Path.GetDirectoryName(paths[0]); string wildcard = Path.Combine(directory, "*.xxx;"); Project project = new Project(); ProjectItemElement itemElement = project.Xml.AddItem("i", wildcard); itemElement.AddMetadata("m", "m1"); project.ReevaluateIfNecessary(); ProjectItem item = Helpers.GetFirst(project.Items); project.RemoveItem(item); string expected = String.Format( ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <ItemGroup> <i Include=""{0}""> <m>m1</m> </i> </ItemGroup> </Project>" ), Path.Combine(directory, "i2.xxx")); Helpers.VerifyAssertProjectContent(expected, project.Xml); } finally { Helpers.DeleteFiles(paths); } }
public void RemoveItem_OriginatingWithSemicolon() { Project project = new Project(); project.Xml.AddItem("i", "i1;i2"); project.ReevaluateIfNecessary(); project.RemoveItem(Helpers.GetFirst(project.GetItems("i"))); string expected = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <ItemGroup> <i Include=""i2"" /> </ItemGroup> </Project>"); Helpers.VerifyAssertProjectContent(expected, project.Xml); }
internal void RemoveProjectReferences() { var projects = GetProjects(); var thisProject = projects.FirstOrDefault(c => c.GuidString == "{7AAC4FDB-1C6A-453F-8126-D2E89BC1B6D9}"); if (thisProject == null) throw new Exception("Cannot find Generator Project, operation failed."); var gen = new Project(thisProject.AbsolutePath); gen.GetItems("ProjectReference").ForEach( c => gen.RemoveItem(c) ); gen.Save(); ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); }
public void RemoveItem() { Project project = new Project(); project.AddItem("i", "i1"); project.ReevaluateIfNecessary(); project.RemoveItem(Helpers.GetFirst(project.GetItems("i"))); string expected = ObjectModelHelpers.CleanupFileContents(@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"" />"); Helpers.VerifyAssertProjectContent(expected, project.Xml); Assert.Equal(0, Helpers.Count(project.Items)); Assert.Equal(0, Helpers.MakeList(project.CreateProjectInstance().GetItems("i")).Count); }
/// <summary> /// Removes an interpreter factory from the project. This function will /// modify the project, but does not handle source control. /// </summary> /// <param name="factory"> /// The id of the factory to remove. The function returns silently if /// the factory is not known by this provider. /// </param> public void RemoveInterpreterFactory(IPythonInterpreterFactory factory) { if (factory == null) { throw new ArgumentNullException("factory"); } if (!_factories.ContainsKey(factory)) { return; } string rootPath; if (_rootPaths.TryGetValue(factory.Id, out rootPath)) { _rootPaths.Remove(factory.Id); foreach (var item in _project.GetItems(InterpreterItem)) { Guid itemId; if (Guid.TryParse(item.GetMetadataValue(IdKey), out itemId) && factory.Id == itemId) { _project.RemoveItem(item); _project.MarkDirty(); break; } } } else { foreach (var item in _project.GetItems(InterpreterReferenceItem)) { Guid itemId; Version itemVer; var match = InterpreterReferencePath.Match(item.EvaluatedInclude); if (match != null && match.Success && match.Groups.Cast <Group>().All(g => g.Success) && Guid.TryParse(match.Groups["id"].Value, out itemId) && Version.TryParse(match.Groups["version"].Value, out itemVer) && factory.Id == itemId && factory.Configuration.Version == itemVer) { _project.RemoveItem(item); _project.MarkDirty(); break; } } } bool raiseEvent; FactoryInfo factInfo; lock (_factoriesLock) { raiseEvent = _factories.TryGetValue(factory, out factInfo) && _factories.Remove(factory); } if (factInfo != null && factInfo.Owned && factory is IDisposable) { ((IDisposable)factory).Dispose(); } UpdateActiveInterpreter(); if (raiseEvent) { OnInterpreterFactoriesChanged(); } }
public void ProjectRemoveItemFormatting() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Compile Include=""Class1.cs"" /> <Compile Include=""Class2.cs""/> <Compile Include=""Program.cs""/> </ItemGroup> </Project>"); ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)), ProjectCollection.GlobalProjectCollection, preserveFormatting: true); Project project = new Project(xml); var itemToRemove = project.GetItems("Compile").Single(item => item.EvaluatedInclude == "Class2.cs"); project.RemoveItem(itemToRemove); StringWriter writer = new StringWriter(); project.Save(writer); string expected = ObjectModelHelpers.CleanupFileContents(@"<?xml version=""1.0"" encoding=""utf-16""?> <Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <Compile Include=""Class1.cs"" /> <Compile Include=""Program.cs"" /> </ItemGroup> </Project>"); string actual = writer.ToString(); VerifyAssertLineByLine(expected, actual); }
private static void ReplaceReference(Project project, ProjectItem item, string reference, string path) { project.RemoveItem(item); project.AddItem("Reference", reference, new[] { new KeyValuePair <string, string>("HintPath", Path.Combine(path, reference + ".dll")) }); }
public void NormalizePaths(bool addImports) { List <_BE.ProjectItem> removeItems = new List <_BE.ProjectItem>(); foreach (_BE.ProjectItem folderItem in m_project.GetItems("Folder")) { string path = folderItem.Xml.Include; if (!path.Equals(GetRelativePath(path), StringComparison.OrdinalIgnoreCase)) { removeItems.Add(folderItem); continue; } if (!Directory.Exists(path)) { removeItems.Add(folderItem); continue; } } foreach (string groupName in ProjectEx.FileGroups) { List <MyImportItems> importItems = new List <MyImportItems>(); foreach (_BE.ProjectItem buildItem in m_project.GetItems(groupName)) { string projectRelativePath = GetRelativePath(buildItem.Xml.Include); // The path has to be an absolute path to somewhere // outside the project directory. if (projectRelativePath == null) { string origPath = Path.Combine(Path.GetDirectoryName(m_origProjPath), buildItem.EvaluatedInclude); if (File.Exists(origPath)) { projectRelativePath = buildItem.Xml.Include; externalFiles.Add(buildItem.Xml.Include, origPath); } else if (File.Exists(BuildTaskUtility.ExpandEnvironmentVariables(buildItem.Xml.Include))) { projectRelativePath = Path.GetFileName(buildItem.Xml.Include); externalFiles.Add( projectRelativePath, BuildTaskUtility.ExpandEnvironmentVariables(buildItem.Xml.Include)); } else if (!buildItem.IsImported) { // since the file doesn't even exist // remove it from the project removeItems.Add(buildItem); continue; } else { // This is an imported item // it can't be removed, so // ignore it. if (Task != null) { Task.Log.LogWarning("Ignoring missing imported build item, \"{0}, {1}\"", buildItem.ItemType, buildItem.Xml.Include); } continue; } } if (!buildItem.IsImported) { // Reset the path to the file relative to // the project buildItem.Xml.Include = projectRelativePath; } else if (addImports) { MyImportItems newItem = new MyImportItems(); newItem.name = buildItem.ItemType; newItem.include = projectRelativePath; newItem.meta = new Dictionary <string, string>(); foreach (_BE.ProjectMetadata meta in buildItem.Metadata) { newItem.meta.Add(meta.Name, meta.UnevaluatedValue); } importItems.Add(newItem); } } foreach (MyImportItems importItem in importItems) { m_project.AddItem(importItem.name, importItem.include, importItem.meta); } } foreach (_BE.ProjectItem removeItem in removeItems) { Task.Log.LogWarning("Removing missing build item, \"{0}, {1}\"", removeItem.ItemType, removeItem.Xml.Include); m_project.RemoveItem(removeItem); } }
private static bool UpgradeCSharpConfiguration(EnvDTE.Project dteProject, Microsoft.Build.Evaluation.Project project, OldConfiguration cfg) { ProjectPropertyGroupElement propertyGroup = project.Xml.PropertyGroups.FirstOrDefault(g => g.Label.Equals("IceBuilder")); if (propertyGroup == null) { propertyGroup = project.Xml.AddPropertyGroup(); propertyGroup.Label = "IceBuilder"; } if (!string.IsNullOrEmpty(cfg.OutputDir)) { propertyGroup.AddProperty(PropertyNames.OutputDir, cfg.OutputDir); } if (!string.IsNullOrEmpty(cfg.AdditionalOptions)) { propertyGroup.AddProperty(PropertyNames.AdditionalOptions, cfg.AdditionalOptions); } if (!string.IsNullOrEmpty(cfg.IncludeDirectories)) { propertyGroup.AddProperty(PropertyNames.IncludeDirectories, string.Format(@"{0};$(IceHome)\slice", cfg.IncludeDirectories)); } else { propertyGroup.AddProperty(PropertyNames.IncludeDirectories, @"$(IceHome)\slice"); } if (cfg.Stream) { propertyGroup.AddProperty(PropertyNames.Stream, "True"); } if (cfg.Checksum) { propertyGroup.AddProperty(PropertyNames.Checksum, "True"); } if (cfg.Ice) { propertyGroup.AddProperty(PropertyNames.AllowIcePrefix, "True"); } if (cfg.Tie) { propertyGroup.AddProperty(PropertyNames.Tie, "True"); } foreach (string assembly in Package.AssemblyNames) { VSLangProj80.Reference3 reference = ProjectUtil.FindAssemblyReference(dteProject, assembly) as VSLangProj80.Reference3; if (reference != null) { reference.SpecificVersion = false; } } List <ProjectItem> sliceItems = project.GetItems("None").Where(item => Path.GetExtension(item.UnevaluatedInclude).Equals(".ice")).ToList(); // // Default output directory has changed // if (string.IsNullOrEmpty(cfg.OutputDir)) { project.GetItems("Compile").Where( item => { return(sliceItems.FirstOrDefault( slice => { return slice.UnevaluatedInclude.Equals(Path.ChangeExtension(item.UnevaluatedInclude, ".ice")); }) != null); }) .ToList() .ForEach(item => project.RemoveItem(item)); } return(true); }
public void RemoveItem_OriginatingWithItemList() { XmlReader content = XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <ItemGroup> <h Include=""h1;h2""> <m>m1</m> </h> <i Include=""@(h)"" /> </ItemGroup> </Project>"))); Project project = new Project(content); project.RemoveItem(Helpers.GetFirst(project.GetItems("i"))); string expected = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <ItemGroup> <h Include=""h1;h2""> <m>m1</m> </h> <i Include=""h2""> <m>m1</m> </i> </ItemGroup> </Project>"); Helpers.VerifyAssertProjectContent(expected, project.Xml, false); }
private static bool UpgadeCppConfiguration(Microsoft.Build.Evaluation.Project project, OldConfiguration cfg) { ProjectPropertyGroupElement propertyGroup = project.Xml.PropertyGroups.FirstOrDefault(g => g.Label.Equals("IceBuilder")); if (propertyGroup == null) { propertyGroup = project.Xml.AddPropertyGroup(); propertyGroup.Label = "IceBuilder"; } if (!string.IsNullOrEmpty(cfg.OutputDir)) { propertyGroup.AddProperty(PropertyNames.OutputDir, cfg.OutputDir); } if (!string.IsNullOrEmpty(cfg.HeaderExt)) { propertyGroup.AddProperty(PropertyNames.HeaderExt, cfg.HeaderExt); } if (!string.IsNullOrEmpty(cfg.SourceExt)) { propertyGroup.AddProperty(PropertyNames.SourceExt, cfg.SourceExt); } if (!string.IsNullOrEmpty(cfg.AdditionalOptions)) { propertyGroup.AddProperty(PropertyNames.AdditionalOptions, cfg.AdditionalOptions); } if (!string.IsNullOrEmpty(cfg.IncludeDirectories)) { propertyGroup.AddProperty(PropertyNames.IncludeDirectories, string.Format("{0};$({1})", cfg.IncludeDirectories, PropertyNames.IncludeDirectories)); } if (cfg.Stream) { propertyGroup.AddProperty(PropertyNames.Stream, "True"); } if (cfg.Checksum) { propertyGroup.AddProperty(PropertyNames.Checksum, "True"); } if (cfg.Ice) { propertyGroup.AddProperty(PropertyNames.AllowIcePrefix, "True"); } if (!string.IsNullOrEmpty(cfg.DLLExport)) { propertyGroup.AddProperty(PropertyNames.DLLExport, cfg.DLLExport); } foreach (ProjectItemDefinitionGroupElement group in project.Xml.ItemDefinitionGroups) { // // Remove old property sheet from all configurations // IEnumerable <ProjectImportElement> imports = project.Xml.Imports.Where( p => p.Project.Equals("$(ALLUSERSPROFILE)\\ZeroC\\Ice.props")); if (imports != null) { foreach (ProjectImportElement import in imports) { import.Parent.RemoveChild(import); } } // // WinRT SDK old property sheet // imports = project.Xml.Imports.Where( p => p.Project.IndexOf("CommonConfiguration\\Neutral\\Ice.props") != -1); if (imports != null) { foreach (ProjectImportElement import in imports) { import.Parent.RemoveChild(import); } } foreach (ProjectItemDefinitionElement i in group.ItemDefinitions) { if (i.ItemType.Equals("ClCompile")) { if (!string.IsNullOrEmpty(cfg.OutputDir)) { ProjectMetadataElement metaData = i.Metadata.FirstOrDefault( e => e.Name.Equals("AdditionalIncludeDirectories")); if (metaData != null) { List <string> values = new List <string>(metaData.Value.Split(new char[] { ';' })); values.Remove(cfg.OutputDir); metaData.Value = string.Join(";", values); if (values.Count == 0 || (values.Count == 1 && values[0].Equals("%(AdditionalIncludeDirectories)"))) { i.RemoveChild(metaData); } else { if (!values.Contains("%(AdditionalIncludeDirectories)")) { values.Add("%(AdditionalIncludeDirectories)"); } metaData.Value = string.Join(";", values); } } } } else if (i.ItemType.Equals("Link")) { ProjectMetadataElement metaData = i.Metadata.FirstOrDefault( e => e.Name.Equals("AdditionalDependencies")); if (metaData != null) { List <string> values = new List <string>(metaData.Value.Split(new char[] { ';' })); foreach (string name in Package.CppLibNames) { values.Remove(string.Format("{0}.lib", name)); values.Remove(string.Format("{0}d.lib", name)); } if (values.Count == 0 || (values.Count == 1 && values[0].Equals("%(AdditionalDependencies)"))) { i.RemoveChild(metaData); } else { metaData.Value = string.Join(";", values); } } metaData = i.Metadata.FirstOrDefault(e => e.Name.Equals("AdditionalLibraryDirectories")); if (metaData != null) { if (metaData.Value.Equals("%(AdditionalLibraryDirectories)")) { i.RemoveChild(metaData); } } } } } List <ProjectItem> sliceItems = project.GetItems("None").Where(item => Path.GetExtension(item.UnevaluatedInclude).Equals(".ice")).ToList(); // // Default output directory has changed // if (string.IsNullOrEmpty(cfg.OutputDir)) { foreach (string itemType in new string[] { "ClInclude", "ClCompile" }) { project.GetItems(itemType).Where( item => { return(sliceItems.FirstOrDefault( slice => { return slice.UnevaluatedInclude.Equals(Path.ChangeExtension(item.UnevaluatedInclude, ".ice")); }) != null); }) .ToList() .ForEach(item => project.RemoveItem(item)); } } sliceItems.ForEach(item => { project.RemoveItem(item); project.AddItem("IceBuilder", item.UnevaluatedInclude); }); return(true); }
private static void ReplaceReference(Project project, ProjectItem item, string reference, string path) { project.RemoveItem(item); project.AddItem("Reference", reference, new[] { new KeyValuePair<string, string>("HintPath", Path.Combine(path, reference + ".dll")) }); }