public Project(Solution solution, string title, string fileName) { AssembliesResolved = false; ReferencedAssemblies = new List<string>(); CompilerSettings = new CompilerSettings(); ReferencedProjects = new List<string>(); Files = new List<File>(); Solution = solution; Title = title; FileName = Path.GetFullPath(fileName); ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); MsBuildProject = new Microsoft.Build.Evaluation.Project(fileName); AssemblyName = MsBuildProject.GetPropertyValue("AssemblyName"); CompilerSettings.AllowUnsafeBlocks = MsBuildProject.GetPropertyAsBoolean("AllowUnsafeBlocks"); CompilerSettings.CheckForOverflow = MsBuildProject.GetPropertyAsBoolean("CheckForOverflowUnderflow"); var defineConstants = MsBuildProject.GetPropertyValue("DefineConstants"); foreach (string symbol in defineConstants.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { CompilerSettings.ConditionalSymbols.Add(symbol.Trim()); } foreach (var sourceCodeFile in MsBuildProject.GetItems("Compile")) { Files.Add(new File(this, Path.Combine(MsBuildProject.DirectoryPath, sourceCodeFile.EvaluatedInclude))); } foreach (var projectReference in MsBuildProject.GetItems("ProjectReference")) { string referencedFileName = Path.GetFullPath(Path.Combine(MsBuildProject.DirectoryPath, projectReference.EvaluatedInclude)); ReferencedProjects.Add(referencedFileName); } }
private Compilation CreateCompilation(Project project) { var outputPath = project.GetProperty("OutputPath").EvaluatedValue; if (!Path.IsPathRooted(outputPath)) { outputPath = Path.Combine(Environment.CurrentDirectory, outputPath); } var searchPaths = ReadOnlyArray.OneOrZero(outputPath); var resolver = new DiskFileResolver(searchPaths, searchPaths, Environment.CurrentDirectory, arch => true, System.Globalization.CultureInfo.CurrentCulture); var metadataFileProvider = new MetadataFileProvider(); // just grab a list of references (if they're null, ignore) var list = project.GetItems("Reference").Select(item => { var include = item.EvaluatedInclude; var path = resolver.ResolveAssemblyName(include); if (path == null) return null; return metadataFileProvider.GetReference(path); }).Where(x => x != null); return Compilation.Create(project.GetPropertyValue("AssemblyName"), syntaxTrees: project.GetItems("Compile").Select(c => SyntaxTree.ParseFile(c.EvaluatedInclude)), references: list); }
public Project(Solution solution, string title, string fileName) { AssembliesResolved = false; ReferencedAssemblies = new List <string>(); CompilerSettings = new CompilerSettings(); ReferencedProjects = new List <string>(); Files = new List <File>(); Solution = solution; Title = title; FileName = Path.GetFullPath(fileName); ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); MsBuildProject = new Microsoft.Build.Evaluation.Project(fileName); AssemblyName = MsBuildProject.GetPropertyValue("AssemblyName"); CompilerSettings.AllowUnsafeBlocks = MsBuildProject.GetPropertyAsBoolean("AllowUnsafeBlocks"); CompilerSettings.CheckForOverflow = MsBuildProject.GetPropertyAsBoolean("CheckForOverflowUnderflow"); var defineConstants = MsBuildProject.GetPropertyValue("DefineConstants"); foreach (string symbol in defineConstants.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { CompilerSettings.ConditionalSymbols.Add(symbol.Trim()); } foreach (var sourceCodeFile in MsBuildProject.GetItems("Compile")) { Files.Add(new File(this, Path.Combine(MsBuildProject.DirectoryPath, sourceCodeFile.EvaluatedInclude))); } foreach (var projectReference in MsBuildProject.GetItems("ProjectReference")) { string referencedFileName = Path.GetFullPath(Path.Combine(MsBuildProject.DirectoryPath, projectReference.EvaluatedInclude)); ReferencedProjects.Add(referencedFileName); } }
public ProjectModel CreateProjectModel(Microsoft.Build.Evaluation.Project buildProject) { string projectPath = buildProject.ProjectFileLocation.File; string guidStr = buildProject.GetProperty("ProjectGuid")?.EvaluatedValue; Guid projectGuid = Guid.Empty; if (!string.IsNullOrEmpty(guidStr)) { projectGuid = new Guid(buildProject.GetProperty("ProjectGuid").EvaluatedValue); } string projectName = buildProject.GetProperty("AssemblyName").EvaluatedValue; var references = buildProject.GetItems("Reference").ToList(); bool isBsipa = buildProject.GetItems("Reference").Any(i => i.EvaluatedInclude.StartsWith("IPA.Loader")); var bsDirProp = buildProject.GetProperty("BeatSaberDir"); var projCap = Models.ProjectCapabilities.None; ProjectOptions projOptions = ProjectOptions.None; if (bsDirProp != null) { projCap |= Models.ProjectCapabilities.BeatSaberDir; projOptions |= ProjectOptions.BeatSaberDir; } var projectModel = new ProjectModel(projectGuid, projectName, projectPath, isBsipa, projOptions, projOptions, projCap); return(projectModel); }
private ISet <PackageReference> ParsePackageReferences() { var packageReferences = new HashSet <PackageReference>(); foreach (var item in _MsProject.GetItems(_PackageReferenceTagName)) { var version = item.GetMetadata(_VersionMetadataName); var packageReference = new PackageReference(item.EvaluatedInclude, version?.EvaluatedValue, version?.UnevaluatedValue); packageReferences.Add(packageReference); } return(packageReferences); }
public void SimpleImportAndSemanticValues () { string xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='test_imported.proj' /> </Project>"; string imported = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <A>x</A> <B>y</B> </PropertyGroup> <ItemGroup> <X Include=""included.txt"" /> </ItemGroup> </Project>"; using (var ts = File.CreateText (temp_file_name)) ts.Write (imported); try { var reader = XmlReader.Create (new StringReader (xml)); var root = ProjectRootElement.Create (reader); Assert.AreEqual (temp_file_name, root.Imports.First ().Project, "#1"); var proj = new Project (root); var prop = proj.GetProperty ("A"); Assert.IsNotNull (prop, "#2"); Assert.IsTrue (prop.IsImported, "#3"); var item = proj.GetItems ("X").FirstOrDefault (); Assert.IsNotNull (item, "#4"); Assert.AreEqual ("included.txt", item.EvaluatedInclude, "#5"); } finally { File.Delete (temp_file_name); } }
private IEnumerable<Project> SortProject(Project project) { if (!visited.Contains(project)) { visited.Add(project); foreach (var reference in project.GetItems("Reference")) { //TODO: Get rid of hard-coded exclusions if (reference.EvaluatedInclude != "DevExpress.XtraRichEdit.v12.2.Extensions, Version=12.2.0.0, Culture=neutral, PublicKeyToken=79868b8147b5eae4, processorArchitecture=MSIL") { AssemblyName assemblyName = new AssemblyName(reference.EvaluatedInclude); string shortName = assemblyName.Name; Project referencedProject; if (projects.TryGetValue(shortName, out referencedProject)) { foreach (var sorted in SortProject(referencedProject)) yield return sorted; } else if (excludedProjects.Contains(shortName)) { excludedProjects.Add(shortName); yield break; } else if (shortName.StartsWith("DevExpress", StringComparison.OrdinalIgnoreCase)) unknownReferences.Add(shortName); } } yield return project; } }
public static ICollection <ProjectItem> ThreadSafeGetItems(this Microsoft.Build.Evaluation.Project thisp, string itemType) { lock (thisp) { return(thisp.GetItems(itemType)); } }
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)); } } }
/// <summary> /// Open a code snippet file by finding the one containing the given ID /// </summary> /// <param name="currentProject">The current project used to find files</param> /// <param name="id">The ID of the snippet to search for in the code snippet files</param> /// <returns>True if opened, false if not</returns> private bool OpenCodeSnippetFile(MSBuildProject currentProject, string id) { ThreadHelper.ThrowIfNotOnUIThread(); string projectPath = Path.GetDirectoryName(currentProject.FullPath), filePath; int pos = id.IndexOf(','); // If it's a combined ID, find the first one if (pos != -1) { id = id.Substring(0, pos); } foreach (var snippetFile in currentProject.GetItems("CodeSnippets")) { var link = snippetFile.Metadata.FirstOrDefault(m => m.Name == "Link"); if (link == null) { filePath = Path.Combine(projectPath, snippetFile.EvaluatedInclude); } else { filePath = Path.Combine(projectPath, link.EvaluatedValue); } if (File.Exists(filePath)) { // The file content may not be current if the file is open for editing but I can't be // bothered to add the code to go look for the open editor and get it from there yet. var doc = XDocument.Load(filePath); if (doc.Descendants("item").Any(t => t.Attribute("id").Value == id)) { var item = currentSolution.FindProjectItem(snippetFile.EvaluatedInclude); if (item != null) { var window = item.Open(); if (window != null) { window.Activate(); if (window.Selection is TextSelection selection) { selection.FindText(id); } return(true); } } } } } return(false); }
/// <summary> /// Open a code snippet file by finding the one containing the given ID /// </summary> /// <param name="currentProject">The current project used to find files</param> /// <param name="id">The ID of the snippet to search for in the code snippet files</param> /// <returns>True if opened, false if not</returns> private bool OpenCodeSnippetFile(MSBuildProject currentProject, string id) { string projectPath = Path.GetDirectoryName(currentProject.FullPath), filePath; int pos = id.IndexOf(','); // If it's a combined ID, find the first one if (pos != -1) { id = id.Substring(0, pos); } foreach (var snippetFile in currentProject.GetItems("CodeSnippets")) { var link = snippetFile.Metadata.FirstOrDefault(m => m.Name == "Link"); if (link == null) { filePath = Path.Combine(projectPath, snippetFile.EvaluatedInclude); } else { filePath = Path.Combine(projectPath, link.EvaluatedValue); } if (File.Exists(filePath)) { // TODO: Can it find an open code snippet editor for the file if there is one and search its // content instead. var doc = XDocument.Load(filePath); if (doc.Descendants("item").Any(t => t.Attribute("id").Value == id)) { var item = currentSolution.FindProjectItem(snippetFile.EvaluatedInclude); if (item != null) { var window = item.Open(); if (window != null) { window.Activate(); var selection = window.Selection as TextSelection; if (selection != null) { selection.FindText(id); } return(true); } } } } } return(false); }
/// <summary> /// Open a token file by finding the one containing the given ID /// </summary> /// <param name="currentProject">The current project used to find files</param> /// <param name="id">The ID of the token to search for in the token files</param> /// <returns>True if opened, false if not</returns> private bool OpenTokenFile(MSBuildProject currentProject, string id) { ThreadHelper.ThrowIfNotOnUIThread(); string projectPath = Path.GetDirectoryName(currentProject.FullPath), filePath; foreach (var contentLayoutFile in currentProject.GetItems("Tokens")) { var link = contentLayoutFile.Metadata.FirstOrDefault(m => m.Name == "Link"); if (link == null) { filePath = Path.Combine(projectPath, contentLayoutFile.EvaluatedInclude); } else { filePath = Path.Combine(projectPath, link.EvaluatedValue); } if (File.Exists(filePath)) { // The file content may not be current if the file is open for editing but I can't be // bothered to add the code to go look for the open editor and get it from there yet. var doc = XDocument.Load(filePath); if (doc.Descendants("item").Any(t => t.Attribute("id").Value == id)) { var item = currentSolution.FindProjectItem(contentLayoutFile.EvaluatedInclude); if (item != null) { // Bit of a hack. The token editor is a custom editor and I couldn't find a way // to get to it from the window. So, set the ID and the token editor pane will // select this as the default token when the editor is opened. However, if already // open, it won't have any effect. try { tokenId = id; var window = item.Open(); if (window != null) { window.Activate(); return(true); } } finally { tokenId = null; } } } } } return(false); }
public void CheckNotReferenced(string projectPath, IEnumerable <string> references) { using var projectCollection = new ProjectCollection(); var project = new MSBuildProject(Path.Combine(_projectPath, projectPath), new Dictionary <string, string>(), null, projectCollection); var items = project.GetItems("ProjectReference"); var actualReferences = items.Select(item => item.EvaluatedInclude).Select(NormalizePaths).ToList(); Assert.All(references, reference => Assert.DoesNotContain(reference, actualReferences)); }
public static async Task PackageContainsContentItemsAsync(Project nuProj) { var package = await nuProj.GetPackageAsync(); foreach (var contentItem in nuProj.GetItems("Content")) { var expectedPath = GetExpectedPackagePathForContent(contentItem); Assert.NotNull(package.GetFile(expectedPath)); } }
private ArrayList GetProjectReferences(string slnFilePath, ref string csprojFilePath) { ArrayList refList = new ArrayList(); csprojFilePath = FindProject(slnFilePath, slnFilePath.Substring(slnFilePath.LastIndexOf(@"\") + 1)); // Load the csproj file using msbuild and get the list of added references. // We need this list to generate the list of pe files. _BE.Project prj = new _BE.Project(csprojFilePath); char[] splitChar = { ',' }; foreach (_BE.ProjectItem item in prj.GetItems("Reference")) { string[] referenceItem = item.EvaluatedInclude.Split(splitChar, StringSplitOptions.RemoveEmptyEntries); if (!refList.Contains(referenceItem[0].Trim())) { refList.Add(referenceItem[0].Trim()); } if (item.HasMetadata("HintPath")) { string hint = item.GetMetadataValue("HintPath"); RecurseProjDep(hint, ref refList); } else { string output = Environment.GetEnvironmentVariable("BUILD_TREE_CLIENT") + "\\dll\\" + referenceItem[0] + ".dll"; if (File.Exists(output)) { RecurseProjDep(output, ref refList); } } } // Set the assembly name. m_assemblyName = prj.GetPropertyValue("AssemblyName"); // Determine if the test is a desktop test. string value = prj.GetPropertyValue("ProjectTypeGuids"); m_currentAppType = string.IsNullOrEmpty(value) ? TestType.Desktop:TestType.Device; // Determine the desktop app if this is a device-desktop test. foreach (_BE.ProjectItem item in prj.Items) { if (item.ItemType.ToLower().Contains("content")) { m_desktopXmlFile = item.EvaluatedInclude; m_currentAppType = TestType.DeviceDesktop; } } return(refList); }
public void CheckReferences(string projectPath, IEnumerable <string> references) { using var projectCollection = new ProjectCollection(); var project = new MSBuildProject(Path.Combine(_projectPath, projectPath), new Dictionary <string, string>(), null, projectCollection, ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.IgnoreInvalidImports); var items = project.GetItems("ProjectReference"); var actualReferences = items.Select(item => item.EvaluatedInclude).Select(NormalizePaths).ToList(); Assert.All(actualReferences, reference => Assert.Equal(1, actualReferences.Count(r => r == reference))); Assert.All(references, reference => Assert.Contains(reference, actualReferences)); Assert.All(references, reference => Assert.Equal("slnmerge", items.FirstOrDefault(item => NormalizePaths(item.EvaluatedInclude) == reference)?.GetMetadataValue("Origin"))); }
public void SetUnevaluatedValue() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemGroup> <i Include='i1'> <m1>v1</m1> <m2>v%253</m2> </i> </ItemGroup> </Project> "); ProjectRootElement projectXml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Project project = new Project(projectXml); Assert.AreEqual(false, project.IsDirty); Helpers.GetFirst(project.GetItems("i")).SetMetadataValue("m1", "v2"); Helpers.GetFirst(project.GetItems("i")).SetMetadataValue("m2", "v%214"); Assert.AreEqual(true, project.IsDirty); StringWriter writer = new StringWriter(); projectXml.Save(writer); string expected = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemGroup> <i Include='i1'> <m1>v2</m1> <m2>v%214</m2> </i> </ItemGroup> </Project> "); Helpers.CompareProjectXml(expected, writer.ToString()); Assert.AreEqual("v!4", Helpers.GetFirst(project.GetItems("i")).GetMetadataValue("m2")); }
public void MoveLinkedNode() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "MovedLinkedFile" + projectType.CodeExtension); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); solution.ExecuteCommand("Edit.Cut"); var folderNode = solution.FindItem("LinkedFiles", "MoveToFolder"); AutomationWrapper.Select(folderNode); solution.ExecuteCommand("Edit.Paste"); // item should have moved var movedLinkedFile = solution.WaitForItem("LinkedFiles", "MoveToFolder", "MovedLinkedFile" + projectType.CodeExtension); Assert.IsNotNull(movedLinkedFile, "movedLinkedFile"); // file should be at the same location Assert.IsTrue(File.Exists(Path.Combine(solution.SolutionDirectory, "MovedLinkedFile" + projectType.CodeExtension))); Assert.IsFalse(File.Exists(Path.Combine(solution.SolutionDirectory, "MoveToFolder\\MovedLinkedFile" + projectType.CodeExtension))); // now move it back AutomationWrapper.Select(movedLinkedFile); solution.ExecuteCommand("Edit.Cut"); var originalFolder = solution.FindItem("LinkedFiles"); AutomationWrapper.Select(originalFolder); solution.ExecuteCommand("Edit.Paste"); var movedLinkedFilePaste = solution.WaitForItem("LinkedFiles", "MovedLinkedFile" + projectType.CodeExtension); Assert.IsNotNull(movedLinkedFilePaste, "movedLinkedFilePaste"); // and make sure we didn't mess up the path in the project file MSBuild.Project buildProject = new MSBuild.Project(solution.GetProject("LinkedFiles").FullName); bool found = false; foreach (var item in buildProject.GetItems("Compile")) { if (item.UnevaluatedInclude == "..\\MovedLinkedFile" + projectType.CodeExtension) { found = true; break; } } Assert.IsTrue(found); } } }
private bool IsDocumentGenerated(ITaskItem documentItem) { if (_documents == null) { _documents = new Dictionary <string, ProjectItem>(); foreach (var item in _loadedProject.GetItems(ItemNames.Compile)) { _documents[GetAbsolutePathRelativeToProject(item.EvaluatedInclude)] = item; } } return(!_documents.ContainsKey(GetAbsolutePathRelativeToProject(documentItem.ItemSpec))); }
public static IEnumerable <string> GetNamespaces(this Project project) { const string namespacePattern = @"@?[a-z_A-Z]\w*(?:\.@?[a-z_A-Z]\w*)+"; var namespaceRegex = new Regex(namespacePattern); return(project .GetItems("Content") .Select(content => Path.Combine(project.DirectoryPath, content.EvaluatedInclude)) .Where(File.Exists) .SelectMany(File.ReadLines) .SelectMany(line => namespaceRegex.Matches(line).Cast <Match>()) .Select(match => match.Value)); }
private bool AddAssemblyReferences(ProjectRootElement inMemoryProject, Microsoft.Build.Evaluation.Project originalProject) { foreach (Microsoft.Build.Evaluation.ProjectItem item in originalProject.GetItems("Reference")) { ProjectItemElement condition = inMemoryProject.AddItem(item.ItemType, item.UnevaluatedInclude); condition.Condition = item.Xml.Condition; foreach (ProjectMetadata metadatum in item.Metadata) { condition.AddMetadata(metadatum.Name, metadatum.EvaluatedValue); } } return(true); }
public void SetMetadata() { ProjectRootElement xml = ProjectRootElement.Create(); xml.AddProperty("p", "v"); xml.AddItemDefinitionGroup().AddItemDefinition("i").AddMetadata("m", "m0"); xml.AddItem("i", "i1"); Project project = new Project(xml); ProjectMetadata metadatum = project.ItemDefinitions["i"].GetMetadata("m"); metadatum.UnevaluatedValue = "$(p)"; Assert.Equal("v", Helpers.GetFirst(project.GetItems("i")).GetMetadataValue("m")); }
internal override IEnumerable <Dictionary <string, string> > GetInterpreters() { return(Project.GetItems(MSBuildConstants.InterpreterItem).Select( interp => new Dictionary <string, string>() { { "EvaluatedInclude", interp.EvaluatedInclude }, { MSBuildConstants.IdKey, interp.GetMetadataValue(MSBuildConstants.IdKey) }, { MSBuildConstants.VersionKey, interp.GetMetadataValue(MSBuildConstants.VersionKey) }, { MSBuildConstants.DescriptionKey, interp.GetMetadataValue(MSBuildConstants.DescriptionKey) }, { MSBuildConstants.InterpreterPathKey, interp.GetMetadataValue(MSBuildConstants.InterpreterPathKey) }, { MSBuildConstants.WindowsPathKey, interp.GetMetadataValue(MSBuildConstants.WindowsPathKey) }, { MSBuildConstants.PathEnvVarKey, interp.GetMetadataValue(MSBuildConstants.PathEnvVarKey) }, { MSBuildConstants.ArchitectureKey, interp.GetMetadataValue(MSBuildConstants.ArchitectureKey) } } )); }
public void SpecialCharactersInMetadataValueConstruction() { string projectString = ObjectModelHelpers.CleanupFileContents(@"<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <ItemGroup> <None Include='MetadataTests'> <EscapedSemicolon>%3B</EscapedSemicolon> <EscapedDollarSign>%24</EscapedDollarSign> </None> </ItemGroup> </Project>"); System.Xml.XmlReader reader = new System.Xml.XmlTextReader(new StringReader(projectString)); Microsoft.Build.Evaluation.Project project = new Microsoft.Build.Evaluation.Project(reader); Microsoft.Build.Evaluation.ProjectItem item = project.GetItems("None").Single(); SpecialCharactersInMetadataValueTests(item); }
static IEnumerable<Project> GetProjectReferences(Project project) { foreach (var reference in project.GetItems("ProjectReference")) { var referenced = new Project( Path.Combine(Path.GetDirectoryName(project.FullPath), reference.EvaluatedInclude), project.GlobalProperties, project.ToolsVersion, new ProjectCollection(project.GlobalProperties)); yield return referenced; foreach (var transitive in GetProjectReferences(referenced)) { yield return transitive; } } }
private static int ModifyPackagePaths(MsBuild.Project project, IReadOnlyCollection <IVsPackageMetadata> packages, string slnDir, ModifyPackagePathDelegate modifyPackagePath) { const string pathAttributeName = "HintPath"; var projectDirPath = project.DirectoryPath; var result = 0; foreach (var reference in project.GetItems("Reference").Where(r => r.HasMetadata(pathAttributeName))) { var metadata = reference.GetMetadata(pathAttributeName); var newPath = modifyPackagePath(metadata.EvaluatedValue, metadata.UnevaluatedValue, packages, slnDir, projectDirPath); result += SetIfNew("reference", x => metadata.UnevaluatedValue = x, newPath, metadata.UnevaluatedValue); } foreach (var import in project.Imports) { var unevaluatedOldPath = import.ImportingElement.Project; var evaluatedOldPath = import.ImportedProject.FullPath; var newPath = modifyPackagePath(evaluatedOldPath, unevaluatedOldPath, packages, slnDir, projectDirPath); result += SetIfNew("import path", x => import.ImportingElement.Project = x, newPath, unevaluatedOldPath); var oldCondition = import.ImportingElement.Condition; var newCondition = GetNewImportCondition(oldCondition, evaluatedOldPath, unevaluatedOldPath, packages, slnDir, projectDirPath, modifyPackagePath); result += SetIfNew("import condition", x => import.ImportingElement.Condition = x, newCondition, oldCondition); } var errors = project.Xml.Targets .Where(x => x.Name == "EnsureNuGetPackageBuildImports") .SelectMany(t => t.Children) .OfType <ProjectTaskElement>() .Where(x => x.Name == "Error"); foreach (var error in errors) { var oldCondition = error.Condition; var newCondition = GetNewErrorCondition(oldCondition, packages, slnDir, projectDirPath, modifyPackagePath, project); result += SetIfNew("error condition", x => error.Condition = x, newCondition, oldCondition); var oldText = error.GetParameter("Text"); var newText = GetNewErrorText(oldText, packages, slnDir, projectDirPath, modifyPackagePath, project); result += SetIfNew("error text", x => error.SetParameter("Text", x), newText, oldText); } return(result); }
internal static IEnumerable <Tuple <ProjectItem, AssemblyName> > GetAssemblyReferences(this MsBuildProject project) { foreach (ProjectItem referenceProjectItem in project.GetItems(ReferenceProjectItem)) { AssemblyName assemblyName = null; try { assemblyName = new AssemblyName(referenceProjectItem.EvaluatedInclude); } catch { // Swallow any exceptions we might get because of malformed assembly names } // We can't yield from within the try so we do it out here if everything was successful if (assemblyName != null) { yield return(Tuple.Create(referenceProjectItem, assemblyName)); } } }
public void AddItem_EscapedItemInclude() { Project project = new Project(); project.AddItem("i", "i%281%29"); string expected = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <ItemGroup> <i Include=""i%281%29"" /> </ItemGroup> </Project>"); Helpers.VerifyAssertProjectContent(expected, project.Xml); List<ProjectItem> items = Helpers.MakeList(project.Items); Assert.Equal(1, items.Count); Assert.Equal("i", items[0].ItemType); Assert.Equal("i(1)", items[0].EvaluatedInclude); Assert.Equal("i(1)", Helpers.GetFirst(project.GetItems("i")).EvaluatedInclude); Assert.Equal("i(1)", Helpers.MakeList(project.CreateProjectInstance().GetItems("i"))[0].EvaluatedInclude); }
private IProjectContent AddCompileFilesToProject(Project msbuildProject, IProjectContent pc) { foreach (var item in msbuildProject.GetItems("Compile")) { var filepath = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude); if (File.Exists(filepath)) { var file = new CSharpFile(this, filepath); Files.Add(file); } } pc = pc.AddOrUpdateFiles(Files.Select(f => f.UnresolvedTypeSystemForFile)); return pc; }
/// <summary> /// Gets the test item from the project. /// </summary> /// <param name="project">The project.</param> /// <returns>The item.</returns> private ProjectItem GetProjectItem(Project project) { IEnumerable<ProjectItem> items = project.GetItems(ItemType).Where(pi => !pi.IsImported); Assert.IsTrue(items.Count() == 1, "Wrong number of items in the project."); ProjectItem item = items.First(); Assert.AreEqual(null, item.Xml.ContainingProject.FullPath, "Item was not found in the project."); // null because XML is in-memory return item; }
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); } }
public void CanGetCorrectListOfItemsWithSemicolonsInThem2() { string projectString = @" <Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <MyUserMacro>foo;bar</MyUserMacro> </PropertyGroup> <ItemGroup> <CrazyList Include=""a"" /> <CrazyList Include=""b%3bc"" /> <CrazyList Include=""$(MyUserMacro)"" /> </ItemGroup> </Project>"; System.Xml.XmlReader reader = new System.Xml.XmlTextReader(new StringReader(projectString)); Project project = new Project(reader); IEnumerable<ProjectItem> items = project.GetItems("CrazyList"); Assert.Equal(4, items.Count()); Assert.Equal(items.ElementAt(0).EvaluatedInclude, "a"); Assert.Equal(items.ElementAt(1).EvaluatedInclude, "b;c"); Assert.Equal(items.ElementAt(2).EvaluatedInclude, "foo"); Assert.Equal(items.ElementAt(3).EvaluatedInclude, "bar"); }
/// <summary> /// Given a project and an item type, gets the items of that type, and renames an item /// with the old evaluated include to have the new evaluated include instead. /// </summary> /// <param name="project"></param> /// <param name="itemType"></param> /// <param name="oldEvaluatedInclude"></param> /// <param name="newEvaluatedInclude"></param> internal static IEnumerable<ProjectItem> ModifyItemOfTypeInProject(Project project, string itemType, string oldEvaluatedInclude, string newEvaluatedInclude) { IEnumerable<ProjectItem> itemsToMatch = project.GetItems(itemType); List<ProjectItem> matchingItems = new List<ProjectItem>(); foreach (ProjectItem item in itemsToMatch) { if (String.Equals(item.EvaluatedInclude, oldEvaluatedInclude, StringComparison.OrdinalIgnoreCase)) { matchingItems.Add(item); } } for (int i = 0; i < matchingItems.Count; i++) { matchingItems[i].Rename(newEvaluatedInclude); } return matchingItems; }
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); }
public void TransformsUseCorrectDirectory_DirectoryNameItemFunction() { string file = null; string projectFileContent = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace'> <ItemGroup> <IntermediateAssembly Include='obj\i386\foo.dll'/> <BuiltProjectOutputGroupKeyOutput Include=""@(IntermediateAssembly->DirectoryName())""/> </ItemGroup> </Project>"); ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent))); try { file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); xml.FullPath = file; Project project = new Project(xml); ProjectInstance projectInstance = new ProjectInstance(xml); // Should be the full path to the directory Assert.Equal(Path.Combine(Path.GetTempPath() /* remove c:\ */, @"obj\i386"), project.GetItems("BuiltProjectOutputGroupKeyOutput").First().EvaluatedInclude); Assert.Equal(Path.Combine(Path.GetTempPath() /* remove c:\ */, @"obj\i386"), projectInstance.GetItems("BuiltProjectOutputGroupKeyOutput").First().EvaluatedInclude); } finally { File.Delete(file); } }
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 static ILookup <PackageReference, KeyValuePair <string, string> > GetDirectPackageAssemblies(this Project project) { return(project.GetItems("Reference").ToLookup(r => r.GetPackageReference(), r => r.GetAssemblyName())); }
public static IEnumerable <ProjectItem> GetProjectReferences(this Project project) { return(project.GetItems("ProjectReference")); }
/// <summary> /// Call to find interpreters in the associated project. Separated from /// the constructor to allow exceptions to be handled without causing /// the project node to be invalid. /// </summary> /// <exception cref="InvalidDataException"> /// One or more interpreters failed to load. The error message should be /// presented to the user, but can otherwise be ignored. /// </exception> public void DiscoverInterpreters() { // <Interpreter Include="InterpreterDirectory"> // <Id>guid</Id> // <BaseInterpreter>guid</BaseInterpreter> // <Version>...</Version> // <InterpreterPath>...</InterpreterPath> // <WindowsInterpreterPath>...</WindowsInterpreterPath> // <LibraryPath>...</LibraryPath> // <PathEnvironmentVariable>...</PathEnvironmentVariable> // <Description>...</Description> // </Interpreter> var errors = new StringBuilder(); errors.AppendLine("Some project interpreters failed to load:"); bool anyChange = false, anyError = false; var projectHome = CommonUtils.GetAbsoluteDirectoryPath(_project.DirectoryPath, _project.GetPropertyValue("ProjectHome")); var factories = new Dictionary <IPythonInterpreterFactory, FactoryInfo>(); foreach (var item in _project.GetItems(InterpreterItem)) { IPythonInterpreterFactory fact; Guid id, baseId; // Errors in these options are fatal, so we set anyError and // continue with the next entry. var dir = item.EvaluatedInclude; if (!CommonUtils.IsValidPath(dir)) { errors.AppendLine(string.Format("Interpreter has invalid path: {0}", dir ?? "(null)")); anyError = true; continue; } dir = CommonUtils.GetAbsoluteDirectoryPath(projectHome, dir); var value = item.GetMetadataValue(IdKey); if (string.IsNullOrEmpty(value) || !Guid.TryParse(value, out id)) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, IdKey, value)); anyError = true; continue; } if (factories.Keys.Any(f => f.Id == id)) { errors.AppendLine(string.Format("Interpreter {0} has a non-unique id: {1}", dir, id)); continue; } var verStr = item.GetMetadataValue(VersionKey); Version ver; if (string.IsNullOrEmpty(verStr) || !Version.TryParse(verStr, out ver)) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, VersionKey, verStr)); anyError = true; continue; } // The rest of the options are non-fatal. We create an instance // of NotFoundError with an amended description, which will // allow the user to remove the entry from the project file // later. bool hasError = false; var description = item.GetMetadataValue(DescriptionKey); if (string.IsNullOrEmpty(description)) { description = CommonUtils.CreateFriendlyDirectoryPath(projectHome, dir); } value = item.GetMetadataValue(BaseInterpreterKey); PythonInterpreterFactoryWithDatabase baseInterp = null; if (!string.IsNullOrEmpty(value) && Guid.TryParse(value, out baseId)) { // It's a valid GUID, so find a suitable base. If we // don't find one now, we'll try and figure it out from // the pyvenv.cfg/orig-prefix.txt files later. // Using an empty GUID will always go straight to the // later lookup. if (baseId != Guid.Empty) { baseInterp = _service.FindInterpreter(baseId, ver) as PythonInterpreterFactoryWithDatabase; } } var path = item.GetMetadataValue(InterpreterPathKey); if (!CommonUtils.IsValidPath(path)) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, InterpreterPathKey, path)); hasError = true; } else if (!hasError) { path = CommonUtils.GetAbsoluteFilePath(dir, path); } var winPath = item.GetMetadataValue(WindowsPathKey); if (!CommonUtils.IsValidPath(winPath)) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, WindowsPathKey, winPath)); hasError = true; } else if (!hasError) { winPath = CommonUtils.GetAbsoluteFilePath(dir, winPath); } var libPath = item.GetMetadataValue(LibraryPathKey); if (string.IsNullOrEmpty(libPath)) { libPath = "lib"; } if (!CommonUtils.IsValidPath(libPath)) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, LibraryPathKey, libPath)); hasError = true; } else if (!hasError) { libPath = CommonUtils.GetAbsoluteDirectoryPath(dir, libPath); } var pathVar = item.GetMetadataValue(PathEnvVarKey); if (string.IsNullOrEmpty(pathVar)) { if (baseInterp != null) { pathVar = baseInterp.Configuration.PathEnvironmentVariable; } else { pathVar = "PYTHONPATH"; } } string arch = null; if (baseInterp == null) { arch = item.GetMetadataValue(ArchitectureKey); if (string.IsNullOrEmpty(arch)) { arch = "x86"; } } if (baseInterp == null && !hasError) { // Only thing missing is the base interpreter, so let's try // to find it using paths baseInterp = DerivedInterpreterFactory.FindBaseInterpreterFromVirtualEnv(dir, libPath, _service) as PythonInterpreterFactoryWithDatabase; if (baseInterp == null) { errors.AppendLine(string.Format("Interpreter {0} has invalid value for '{1}': {2}", dir, BaseInterpreterKey, value ?? "(null)")); hasError = true; } } if (hasError) { fact = new NotFoundInterpreterFactory( id, ver, string.Format("{0} (unavailable)", description), Directory.Exists(dir) ? dir : null ); } else if (baseInterp != null) { MigrateOldDerivedInterpreterFactoryDatabase(id, baseInterp.Configuration.Version, dir); fact = new DerivedInterpreterFactory( baseInterp, new InterpreterFactoryCreationOptions { LanguageVersion = baseInterp.Configuration.Version, Id = id, Description = description, InterpreterPath = path, WindowInterpreterPath = winPath, LibraryPath = libPath, PrefixPath = dir, PathEnvironmentVariableName = pathVar, Architecture = baseInterp.Configuration.Architecture, WatchLibraryForNewModules = true } ); } else { fact = InterpreterFactoryCreator.CreateInterpreterFactory(new InterpreterFactoryCreationOptions { LanguageVersion = ver, Id = id, Description = description, InterpreterPath = path, WindowInterpreterPath = winPath, LibraryPath = libPath, PrefixPath = dir, PathEnvironmentVariableName = pathVar, ArchitectureString = arch, WatchLibraryForNewModules = true }); } var existing = FindInterpreter(id, ver); if (existing != null && existing.IsEqual(fact)) { factories[existing] = new FactoryInfo(item, factories[existing].Owned); var disposable = fact as IDisposable; if (disposable != null) { disposable.Dispose(); } } else { _rootPaths[id] = dir; factories[fact] = new FactoryInfo(item, true); anyChange = true; } } // <InterpreterReference Include="{guid};{version}" /> foreach (var item in _project.GetItems(InterpreterReferenceItem)) { var match = InterpreterReferencePath.Match(item.EvaluatedInclude); if (match == null || !match.Success || !match.Groups.Cast <Group>().All(g => g.Success)) { errors.AppendLine(string.Format("Interpreter reference has invalid path: {0}", item.EvaluatedInclude)); anyError = true; continue; } Guid id; var value = match.Groups["id"]; if (string.IsNullOrEmpty(value.Value) || !Guid.TryParse(value.Value, out id)) { errors.AppendLine(string.Format("Interpreter reference has invalid id: {0}", value.Value ?? "(null)")); anyError = true; continue; } Version ver; value = match.Groups["version"]; if (string.IsNullOrEmpty(value.Value) || !Version.TryParse(value.Value, out ver)) { errors.AppendLine(string.Format("Interpreter reference has invalid version: {0}", value.Value ?? "(null)")); anyError = true; continue; } bool owned = false; var fact = _service.FindInterpreter(id, ver); if (fact == null) { owned = true; fact = new NotFoundInterpreterFactory(id, ver); } var existing = FindInterpreter(id, ver); if (existing != null) { factories[existing] = new FactoryInfo(item, factories[existing].Owned); if (owned) { ((PythonInterpreterFactoryWithDatabase)fact).Dispose(); } } else { factories[fact] = new FactoryInfo(item, owned); anyChange = true; } } if (anyChange || _factories == null || factories.Count != _factories.Count) { // Lock here mainly to ensure that any searches complete before // we trigger the changed event. lock (_factoriesLock) { _factories = factories; } OnInterpreterFactoriesChanged(); UpdateActiveInterpreter(); } if (anyError) { throw new InvalidDataException(errors.ToString()); } }
public void BasicFromXmlFollowImport() { string importContent = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace'> <PropertyGroup> <p2>v3</p2> </PropertyGroup> <ItemGroup> <i Include='i4'/> </ItemGroup> <Target Name='t2'> <task/> </Target> </Project>"); string importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.targets", importContent); string projectFileContent = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace'> <PropertyGroup Condition=""'$(Configuration)'=='Foo'""> <p>v1</p> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)'!='Foo'""> <p>v2</p> </PropertyGroup> <PropertyGroup> <p2>X$(p)</p2> </PropertyGroup> <ItemGroup> <i Condition=""'$(Configuration)'=='Foo'"" Include='i0'/> <i Include='i1'/> <i Include='$(p)X;i3'/> </ItemGroup> <Target Name='t'> <task/> </Target> <Import Project='{0}'/> </Project>"); projectFileContent = String.Format(projectFileContent, importPath); ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent))); Project project = new Project(xml); Assert.Equal("v3", project.GetPropertyValue("p2")); List<ProjectItem> items = Helpers.MakeList(project.GetItems("i")); Assert.Equal(4, items.Count); Assert.Equal("i1", items[0].EvaluatedInclude); Assert.Equal("v2X", items[1].EvaluatedInclude); Assert.Equal("i3", items[2].EvaluatedInclude); Assert.Equal("i4", items[3].EvaluatedInclude); IList<ResolvedImport> imports = project.Imports; Assert.Equal(1, imports.Count); Assert.Equal(true, Object.ReferenceEquals(imports.First().ImportingElement, xml.Imports.ElementAt(0))); // We can take advantage of the fact that we will get the same ProjectRootElement from the cache if we try to // open it with a path; get that and then compare it to what project.Imports gave us. Assert.Equal(true, Object.ReferenceEquals(imports.First().ImportedProject, ProjectRootElement.Open(importPath))); // Test the logical project iterator List<ProjectElement> logicalElements = new List<ProjectElement>(project.GetLogicalProject()); Assert.Equal(18, logicalElements.Count); ObjectModelHelpers.DeleteTempProjectDirectory(); }
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 TransformsUseCorrectDirectory_Basic_NotSaved() { 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); ProjectInstance projectInstance = new ProjectInstance(xml); Assert.Equal(Path.Combine(Environment.CurrentDirectory, @"obj\i386\foo.dll"), project.GetItems("BuiltProjectOutputGroupKeyOutput").First().EvaluatedInclude); Assert.Equal(Path.Combine(Environment.CurrentDirectory, @"obj\i386\foo.dll"), projectInstance.GetItems("BuiltProjectOutputGroupKeyOutput").First().EvaluatedInclude); }
public void ChooseEvaluateConditionOnlyOnce() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <Choose> <When Condition=""'$(p)' != ''""> <ItemGroup> <i Include='i1' /> </ItemGroup> </When> </Choose> <PropertyGroup> <p>v</p> </PropertyGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); Assert.Equal(0, project.GetItems("i").Count()); }
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 ChooseSeesItemDefinitions() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <Choose> <When Condition='true'> <ItemGroup> <i Include='i1'> <m>%(m);m1</m> </i> </ItemGroup> </When> </Choose> <ItemDefinitionGroup> <i> <m>m0</m> </i> </ItemDefinitionGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); Assert.Equal("m0;m1", project.GetItems("i").ElementAt(0).GetMetadataValue("m")); }
public void EvaluationOrderPropertiesPrecedesItems () { string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <Bar Include='$(Foo)' /> </ItemGroup> <PropertyGroup> <Foo Condition=""'A;B'=='A;B'"">'A;B'</Foo> </PropertyGroup> </Project>"; var xml = XmlReader.Create (new StringReader (project_xml)); var root = ProjectRootElement.Create (xml); var proj = new Project (root); // at this state property is parsed without error i.e. Condition evaluates fine. var prop = proj.GetProperty ("Foo"); Assert.AreEqual ("'A;B'", prop.EvaluatedValue, "#1"); var items = proj.GetItems ("Bar"); Assert.AreEqual ("'A", items.First ().EvaluatedInclude, "#2"); Assert.AreEqual ("$(Foo)", items.First ().UnevaluatedInclude, "#3"); Assert.AreEqual (2, items.Count, "#4"); Assert.AreEqual ("B'", items.Last ().EvaluatedInclude, "#5"); Assert.AreEqual ("$(Foo)", items.Last ().UnevaluatedInclude, "#6"); Assert.IsTrue (items.First ().Xml == items.Last ().Xml, "#7"); }
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 SpecialCharactersInMetadataValueConstruction() { string projectString = @" <Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <None Include='MetadataTests'> <EscapedSemicolon>%3B</EscapedSemicolon> <EscapedDollarSign>%24</EscapedDollarSign> </None> </ItemGroup> </Project>"; System.Xml.XmlReader reader = new System.Xml.XmlTextReader(new StringReader(projectString)); Project project = new Project(reader); ProjectItem item = project.GetItems("None").Single(); EscapingInProjectsHelper.SpecialCharactersInMetadataValueTests(item); }
public void RemoveSeveralItemsOfVariousTypes() { string projectOriginalContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' DefaultTargets='Build' xmlns='msbuildnamespace'> <ItemGroup> <i Include='i1' /> <j Include='j1' /> <j Include='j2' /> <k Include='k1' /> </ItemGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(projectOriginalContents))); List<ProjectItem> list = new List<ProjectItem>() { project.GetItems("i").FirstOrDefault(), project.GetItems("j").FirstOrDefault() }; project.RemoveItems(list); Assert.Equal(2, project.Items.Count()); }
public void Condition () { string xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemDefinitionGroup> <I Condition='{0}'> <DefinedMetadata>X</DefinedMetadata> </I> </ItemDefinitionGroup> <ItemGroup> <I Include='foo' /> </ItemGroup> </Project>"; var reader = XmlReader.Create (new StringReader (string.Format (xml, "True"))); var root = ProjectRootElement.Create (reader); var proj = new Project (root); var i = proj.GetItems ("I").First (); Assert.AreEqual ("X", i.GetMetadataValue ("DefinedMetadata"), "#1"); reader = XmlReader.Create (new StringReader (string.Format (xml, "False"))); root = ProjectRootElement.Create (reader); proj = new Project (root); i = proj.GetItems ("I").First (); Assert.AreEqual (string.Empty, i.GetMetadataValue ("DefinedMetadata"), "#2"); }
public void RemoveSeveralItemsExpandExpression() { string projectOriginalContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' DefaultTargets='Build' xmlns='msbuildnamespace'> <ItemGroup> <i Include='i1;i2' /> <j Include='@(i);j2' /> </ItemGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(projectOriginalContents))); project.RemoveItems(project.GetItems("j").Take(2)); Assert.Equal(3, project.Items.Count()); StringWriter writer = new StringWriter(); project.Save(writer); string projectExpectedContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' DefaultTargets='Build' xmlns='msbuildnamespace'> <ItemGroup> <i Include='i1;i2' /> <j Include='j2' /> </ItemGroup> </Project> "); Helpers.CompareProjectXml(projectExpectedContents, writer.ToString()); }
/// <summary> /// Gets the test item from the import. /// </summary> /// <param name="project">The project.</param> /// <returns>The item.</returns> private ProjectItem GetImportedItem(Project project) { IEnumerable<ProjectItem> items = project.GetItems(ItemType).Where(pi => pi.IsImported); Assert.IsTrue(items.Count() == 1, "Wrong number of items in the import."); ProjectItem item = items.First(); Assert.AreEqual(importFilename, item.Xml.ContainingProject.FullPath, "Item was not found in the imported project."); return item; }
public void RemoveZombiedItem() { string projectOriginalContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' DefaultTargets='Build' xmlns='msbuildnamespace'> <ItemGroup> <i Include='i1' /> </ItemGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(projectOriginalContents))); ProjectItem item = project.GetItems("i").FirstOrDefault(); project.RemoveItems(new List<ProjectItem>() { item }); project.RemoveItems(new List<ProjectItem>() { item }); Assert.Equal(0, project.Items.Count()); }
private static IProjectContent AddAllProjectReferences(Project msbuildProject, IProjectContent pc) { foreach (var item in msbuildProject.GetItems("ProjectReference")) { var referencedFileName = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude); referencedFileName = Path.GetFullPath(referencedFileName); pc = pc.AddAssemblyReferences(new[] {new ProjectReference(referencedFileName)}); } return pc; }
public void RelativePathsInItemsInTargetsFilesAreRelativeToProjectFile() { string directory = null; try { directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); string subdirectory = Path.Combine(directory, "sub"); Directory.CreateDirectory(subdirectory); string projectPath = Path.Combine(subdirectory, "a.proj"); string targetsPath = Path.Combine(directory, "b.targets"); ProjectRootElement targetsXml = ProjectRootElement.Create(targetsPath); targetsXml.AddItem("i", @"..\*"); targetsXml.Save(); ProjectRootElement projectXml = ProjectRootElement.Create(projectPath); projectXml.AddImport(@"..\b.targets"); projectXml.Save(); Project project = new Project(projectPath); IEnumerable<ProjectItem> items = project.GetItems("i"); Assert.Equal(@"..\*", Helpers.GetFirst(items).UnevaluatedInclude); Assert.Equal(@"..\b.targets", Helpers.GetFirst(items).EvaluatedInclude); } finally { Directory.Delete(directory, true); } }
/// <summary> /// Check the items and properties from the sample project /// </summary> private void VerifyContentOfSampleProject(Project project) { Assert.Equal("v2", project.GetProperty("p").UnevaluatedValue); Assert.Equal("Xv2", project.GetProperty("p2").EvaluatedValue); Assert.Equal("X$(p)", project.GetProperty("p2").UnevaluatedValue); IList<ProjectItem> items = Helpers.MakeList(project.GetItems("i")); Assert.Equal(3, items.Count); Assert.Equal("i1", items[0].EvaluatedInclude); Assert.Equal("v2X", items[1].EvaluatedInclude); Assert.Equal("$(p)X;i3", items[1].UnevaluatedInclude); Assert.Equal("i3", items[2].EvaluatedInclude); }
public ICollection <ProjectItem> GetItems(string itemType) => _project.GetItems(itemType);