internal static MSBuildFile GetFile(FileInfo file) { using (ProjectCollection loadedProjects = new ProjectCollection()) { Project currentProject = loadedProjects.GetLoadedProjects(file.FullName).FirstOrDefault(); if (currentProject != null) { loadedProjects.UnloadProject(currentProject); } loadedProjects.LoadProject(file.FullName); currentProject = loadedProjects.GetLoadedProjects(file.FullName).FirstOrDefault(); MSBuildFile m = new MSBuildFile(currentProject); if (currentProject.Targets != null) { SortedDictionary <string, ProjectTargetInstance> sortedTargets = new SortedDictionary <string, ProjectTargetInstance>(currentProject.Targets); foreach (var t in sortedTargets) { ProjectTargetInstance pti = t.Value; m.Targets.Add(new MSBuildTarget(pti, currentProject, m)); } } foreach (var us in currentProject.Xml.UsingTasks) { m.Usings.Add(new MSBuildUsing(currentProject, us)); } foreach (ResolvedImport import in currentProject.Imports) { m.Imports.Add(new MSBuildImport(import)); } foreach (var property in currentProject.Properties) { m.Properties.Add(new MSBuildProperties(property)); } if (currentProject.AllEvaluatedItems != null) { foreach (var item in currentProject.AllEvaluatedItems) { m.Items.Add(new MSBuildItems(item.ItemType, item.UnevaluatedInclude, item.EvaluatedInclude, item.IsImported)); } } return(m); } }
public void GetLoadedProjectsWithoutFullPath() { string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' />"; var xml = XmlReader.Create(new StringReader(project_xml)); var root = ProjectRootElement.Create(xml); string path = Path.GetFullPath("foo.xml"); var pc = new ProjectCollection(); pc.LoadProject(XmlReader.Create(new StringReader(project_xml), null, path)); Assert.AreEqual(0, pc.GetLoadedProjects(path).Count, "#1"); // huh? Assert.AreEqual(0, pc.LoadedProjects.Count, "#1.1"); new Project(root, null, null, pc); Assert.AreEqual(0, pc.GetLoadedProjects(path).Count, "#2"); // huh? }
internal void UnloadProject(string file) { lock (unsavedProjects) { unsavedProjects.Remove(file); } RunSTA(delegate { // Unloading projects modifies the collection, so copy it var loadedProjects = engine.GetLoadedProjects(file).ToArray(); if (loadedProjects.Length == 0) { return; } var rootElement = loadedProjects[0].Xml; foreach (var p in loadedProjects) { engine.UnloadProject(p); } // Try to unload the projects' XML from the cache // This could fail if something else is referencing the xml somehow. // But not a big deal, it's just a cache. engine.TryUnloadProject(rootElement); }); }
/// <summary> /// Recursively execute the specified action on the current project and /// projects referenced by the current project. /// </summary> /// <param name="action">The action to be executed.</param> /// <param name="alreadyAppliedProjects">The collection of projects that have been processed. /// It is used to avoid processing the same project more than once.</param> private void RecursivelyApply(Action <ProjectFactory> action, ProjectCollection alreadyAppliedProjects) { action(this); foreach (var item in _project.GetItems(ProjectReferenceItemType)) { string fullPath = item.GetMetadataValue("FullPath"); if (!string.IsNullOrEmpty(fullPath) && !NuspecFileExists(fullPath) && alreadyAppliedProjects.GetLoadedProjects(fullPath).IsEmpty()) { var project = new Project( fullPath, globalProperties: null, toolsVersion: null, projectCollection: alreadyAppliedProjects); var referencedProject = new ProjectFactory(project); referencedProject.Logger = _logger; referencedProject.IncludeSymbols = IncludeSymbols; referencedProject.Build = Build; referencedProject.IncludeReferencedProjects = IncludeReferencedProjects; referencedProject.ProjectProperties = ProjectProperties; referencedProject.TargetFramework = TargetFramework; referencedProject.BuildProject(); referencedProject.RecursivelyApply(action, alreadyAppliedProjects); } } }
private static Project GetProject(string path, ProjectCollection projectCollection) { var projects = projectCollection.GetLoadedProjects(path); foreach (var proj in projects) { if (proj.GetPropertyValue("DesignTimeBuild") == "true") { return(proj); } } var xml = ProjectRootElement.Open(path, projectCollection); var globalProps = new Dictionary <string, string>() { ["DesignTimeBuild"] = "true", // Isolate the project from post-restore side effects ["ExcludeRestorePackageImports"] = "true", }; var project = new Project(xml, globalProps, toolsVersion: "15.0", projectCollection: projectCollection) { IsBuildEnabled = false }; return(project); }
private Project GetMsBuildProject(string projectPath) { var canonicalProjectPath = GetCanonicalPath(projectPath); var existing = _projectCollection.GetLoadedProjects(canonicalProjectPath).SingleOrDefault(); return(existing ?? new Project(canonicalProjectPath, _globalMsBuildProperties, null, _projectCollection)); }
internal void UnloadProject(string file) { lock (unsavedProjects) unsavedProjects.Remove(file); RunSTA(delegate { foreach (var engine in engines.Values) { //unloading projects modifies the collection, so copy it var projects = engine.GetLoadedProjects(file).ToArray(); if (projects.Length == 0) { return; } var rootElement = projects[0].Xml; foreach (var p in projects) { engine.UnloadProject(p); } //try to unload the projects' XML from the cache try { engine.UnloadProject(rootElement); } catch (InvalidOperationException) { // This could fail if something else is referencing the xml somehow. // But not a big deal, it's just a cache. } } }); }
public static Microsoft.Build.Evaluation.Project LoadedProject(String path, bool cpp, bool cached) { Microsoft.Build.Evaluation.Project project = null; ProjectCollection collection = cpp ? cppProjectColletion : ProjectCollection.GlobalProjectCollection; ICollection <Microsoft.Build.Evaluation.Project> projects = collection.GetLoadedProjects(path); if (projects.Count == 0) { project = collection.LoadProject(path); } else { project = projects.First(); if (cpp && !cached) { // // That is required to get C++ project properties re-evaluated // with Visual Studio 2013 and Visual Studio 2015 // collection.UnloadProject(project); collection.UnloadAllProjects(); project = collection.LoadProject(path); } } return(project); }
private static Project GetProject(string path, ProjectCollection projectCollection, bool policyDesignBuild) { var projects = projectCollection.GetLoadedProjects(path); foreach (var proj in projects) { if (proj.GetPropertyValue("DesignTimeBuild") == "true") { return(proj); } } var xml = ProjectRootElement.Open(path, projectCollection); var globalProps = new Dictionary <string, string>() { ["DesignTimeBuild"] = "true", }; if (policyDesignBuild) { globalProps["PolicyDesignTimeBuild"] = "true"; } var project = new Project( xml, globalProps, toolsVersion: "Current", // TODO: This is the breaking changes, from MSBuild 16, this property is Current instead of 15.0 projectCollection: projectCollection) { IsBuildEnabled = false }; return(project); }
Project ConfigureProject(string file, string configuration, string platform) { var p = engine.GetLoadedProjects(file).FirstOrDefault(); if (p == null) { var content = buildEngine.GetUnsavedProjectContent(file); if (content == null) { p = engine.LoadProject(file); } else { p = engine.LoadProject(new XmlTextReader(new StringReader(content))); p.FullPath = file; } } p.SetProperty("Configuration", configuration); if (!string.IsNullOrEmpty(platform)) { p.SetProperty("Platform", platform); } else { p.SetProperty("Platform", ""); } return(p); }
Project ConfigureProject(string file, string configuration, string platform, string slnConfigContents) { var p = engine.GetLoadedProjects(file).FirstOrDefault(); if (p == null) { var content = buildEngine.GetUnsavedProjectContent(file); if (content == null) { p = engine.LoadProject(file); } else { Environment.CurrentDirectory = Path.GetDirectoryName(file); p = engine.LoadProject(new XmlTextReader(new StringReader(content))); p.FullPath = file; } } p.SetProperty("CurrentSolutionConfigurationContents", slnConfigContents); p.SetProperty("Configuration", configuration); if (!string.IsNullOrEmpty(platform)) { p.SetProperty("Platform", platform); } else { p.SetProperty("Platform", ""); } return(p); }
public static Project LoadedProject(string path, bool cached) { Project project = null; bool cpp = path.EndsWith(".vcxproj"); ProjectCollection collection = cpp ? cppProjectColletion : ProjectCollection.GlobalProjectCollection; project = collection.GetLoadedProjects(path).FirstOrDefault(); if (project == null) { project = collection.LoadProject(path); } else { if (cpp && !cached) { // // That is required to get C++ project properties re-evaluated // with Visual Studio 2013 and Visual Studio 2015 // collection.UnloadProject(project); collection.UnloadAllProjects(); project = collection.LoadProject(path); } } return(project); }
private static Project GetProject(string path, ProjectCollection projectCollection, bool policyDesignBuild) { var projects = projectCollection.GetLoadedProjects(path); foreach (var proj in projects) { if (proj.GetPropertyValue("DesignTimeBuild") == "true") { return(proj); } } var xml = ProjectRootElement.Open(path, projectCollection); var globalProps = new Dictionary <string, string>() { ["DesignTimeBuild"] = "true", }; if (policyDesignBuild) { globalProps["PolicyDesignTimeBuild"] = "true"; } var project = new Project(xml, globalProps, toolsVersion: "15.0", projectCollection: projectCollection) { IsBuildEnabled = false }; return(project); }
public void GetLoadedProjectsSuccess() { string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' />"; var xml = XmlReader.Create(new StringReader(project_xml)); var root = ProjectRootElement.Create(xml); string path = Path.GetFullPath("foo.xml"); var pc = new ProjectCollection(); var proj = new Project(root, null, null, pc); // this order also matters for test; It sets FullPath after Project.ctor(), and should still work. root.FullPath = "foo.xml"; Assert.AreEqual(1, pc.GetLoadedProjects(path).Count, "#1"); // wow ok... Assert.AreEqual(proj, pc.GetLoadedProjects(path).First(), "#2"); }
public void GetLoadedProjectsSuccess2() { string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' />"; string path = Path.GetFullPath("GetLoadedProjectsSuccess2.xml"); var pc = new ProjectCollection(); using (var fs = File.CreateText(path)) fs.Write(project_xml); try { var proj = pc.LoadProject(path); Assert.AreEqual(1, pc.GetLoadedProjects(path).Count, "#1"); // ok... LoadProject (with filename) adds it to the collection. Assert.AreEqual(proj, pc.GetLoadedProjects(path).First(), "#2"); } finally { File.Delete(path); } }
public void GetLoadedProjectsForProjectInstance() { string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' />"; var xml = XmlReader.Create(new StringReader(project_xml)); var root = ProjectRootElement.Create(xml); string path = Path.GetFullPath("foo.xml"); var pc = new ProjectCollection(); root.FullPath = "foo.xml"; new ProjectInstance(root, null, null, pc); Assert.AreEqual(0, pc.GetLoadedProjects(path).Count, "#1"); // so, ProjectInstance does not actually load Project... }
private void LoadFile(FileInfo file) { try { using (ProjectCollection loadedProjects = new ProjectCollection()) { this.proj = loadedProjects.GetLoadedProjects(file.FullName).FirstOrDefault(); if (this.proj != null) { loadedProjects.UnloadProject(this.proj); } loadedProjects.LoadProject(file.FullName); this.proj = loadedProjects.GetLoadedProjects(file.FullName).FirstOrDefault(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Parsing Text", MessageBoxButton.OK, MessageBoxImage.Error); } }
private static string GetFrameworkIdentifier(IProjectPoco x, string solutionDirectory) { using (var pc = new ProjectCollection()) { pc.SetGlobalProperty("SolutionDir", solutionDirectory); pc.LoadProject(x.ProjectFilePath.FullPath); var project = pc.GetLoadedProjects(x.ProjectFilePath.FullPath) .First(); var result = project.GetPropertyValue(TARGET_FRAMEWORK_MONIKER_NAME); pc.UnloadAllProjects(); return(result); } }
Project ConfigureProject(string file, string configuration, string platform, string slnConfigContents) { var p = engine.GetLoadedProjects(file).FirstOrDefault(); if (p == null) { var projectDir = Path.GetDirectoryName(file); // HACK: workaround to MSBuild bug #53019. We need to ensure that $(BaseIntermediateOutputPath) exists before // loading the project. if (!string.IsNullOrEmpty(projectDir)) { Directory.CreateDirectory(Path.Combine(projectDir, "obj")); } var content = buildEngine.GetUnsavedProjectContent(file); if (content == null) { p = engine.LoadProject(file); } else { if (!string.IsNullOrEmpty(projectDir) && Directory.Exists(projectDir)) { Environment.CurrentDirectory = projectDir; } var projectRootElement = ProjectRootElement.Create(new XmlTextReader(new StringReader(content))); projectRootElement.FullPath = file; // Use the engine's default tools version to load the project. We want to build with the latest // tools version. string toolsVersion = engine.DefaultToolsVersion; p = new Project(projectRootElement, engine.GlobalProperties, toolsVersion, engine); } } p.SetGlobalProperty("CurrentSolutionConfigurationContents", slnConfigContents); p.SetGlobalProperty("Configuration", configuration); if (!string.IsNullOrEmpty(platform)) { p.SetGlobalProperty("Platform", platform); } else { p.RemoveGlobalProperty("Platform"); } p.ReevaluateIfNecessary(); return(p); }
private Project GetReferencedProject(string projectPath) { ProjectCollection projects = ProjectCollection.GlobalProjectCollection; ICollection <Project> loadedProjects = projects.GetLoadedProjects(projectPath); Project project = loadedProjects.FirstOrDefault(); if (project == null) { project = new Project(projectPath); } return(project); }
private void UpdateState() { collection.UnloadAllProjects(); collection.LoadProject(path); var csproj = collection.GetLoadedProjects(path).FirstOrDefault(); var isWebProject = csproj.Xml.Sdk == "Microsoft.NET.Sdk.Web"; // Special project type which include UserSecrets in SDK. var packageExists = csproj.Items .Where(x => x.ItemType == "PackageReference") .Where(x => x.EvaluatedInclude == requiredPackage) .Any(); this.userSecretId = csproj.GetPropertyValue(propertyKey); // subcommand if (isWebProject) { this.subCommand = new WebProjectCommand(dte, csproj.Xml.Sdk); } else if (!packageExists) { this.subCommand = new MissingPackageCommand(dte, requiredPackage); } else { this.subCommand = null; } // state if (isWebProject) { Current = State.UserSecretsByWeb; } if (string.IsNullOrWhiteSpace(this.userSecretId)) { Current = State.UserSecretsEntryNotExists; } else if (!File.Exists(GetUserSecretFilePath(userSecretId))) { Current = State.UserSecretFileNotExists; } else { Current = State.UserSecretFileOpenable; } }
public Project Load(FileInfo file) { List <Project> loaded = _projectCollection.GetLoadedProjects(file.FullName).ToList(); if (loaded.Any()) { return(loaded.First()); } Project project = Project.FromFile(file.FullName, new ProjectOptions { LoadSettings = ProjectLoadSettings.IgnoreMissingImports, ProjectCollection = _projectCollection }); return(project); }
/// <summary> /// Adds referenced projects that have corresponding nuspec files as dependencies. /// </summary> /// <param name="dependencies">The dependencies collection where the new dependencies /// are added into.</param> private void AddProjectReferenceDependencies(Dictionary <string, PackageDependency> dependencies) { var processedProjects = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var projectsToProcess = new Queue <Project>(); using (var projectCollection = new ProjectCollection()) { projectsToProcess.Enqueue(_project); while (projectsToProcess.Count > 0) { var project = projectsToProcess.Dequeue(); processedProjects.Add(project.FullPath); foreach (var projectReference in project.GetItems(ProjectReferenceItemType)) { string fullPath = projectReference.GetMetadataValue("FullPath"); if (string.IsNullOrEmpty(fullPath) || processedProjects.Contains(fullPath)) { continue; } var loadedProjects = projectCollection.GetLoadedProjects(fullPath); var referencedProject = loadedProjects.Count > 0 ? loadedProjects.First() : new Project( fullPath, globalProperties: null, toolsVersion: null, projectCollection: projectCollection); if (NuspecFileExists(fullPath)) { var dependency = CreateDependencyFromProject(referencedProject); dependencies[dependency.Id] = dependency; } else { projectsToProcess.Enqueue(referencedProject); } } } } }
/// <summary> /// Initializes the in memory project. Sets BuildEnabled on the project to true. /// </summary> /// <param name="engine">The build engine to use to create a build project.</param> /// <param name="fullProjectPath">The full path of the project.</param> /// <returns>A loaded msbuild project.</returns> internal static Microsoft.Build.Evaluation.Project InitializeMsBuildProject(ProjectCollection buildEngine, string fullProjectPath) { ArgumentNotNullOrEmpty("fullProjectPath", fullProjectPath); // Call GetFullPath to expand any relative path passed into this method. fullProjectPath = CommonUtils.NormalizePath(fullProjectPath); // Check if the project already has been loaded with the fullProjectPath. If yes return the build project associated to it. var loadedProject = new List <Microsoft.Build.Evaluation.Project>(buildEngine.GetLoadedProjects(fullProjectPath)); Microsoft.Build.Evaluation.Project buildProject = loadedProject != null && loadedProject.Count > 0 && loadedProject[0] != null ? loadedProject[0] : null; if (buildProject == null) { buildProject = buildEngine.LoadProject(fullProjectPath); } return(buildProject); }
Project ConfigureProject(string file, string configuration, string platform) { var p = engine.GetLoadedProjects(file).FirstOrDefault(); if (p == null) { p = engine.LoadProject(file); } p.SetProperty("Configuration", configuration); if (!string.IsNullOrEmpty(platform)) { p.SetProperty("Platform", platform); } else { p.SetProperty("Platform", ""); } return(p); }
Project ConfigureProject(string file, string configuration, string platform) { var p = engine.GetLoadedProjects(file).FirstOrDefault(); if (p == null) { var content = buildEngine.GetUnsavedProjectContent(file); if (content == null) { p = engine.LoadProject(file); } else { p = engine.LoadProject(new XmlTextReader(new StringReader(content))); p.FullPath = file; } if (!string.IsNullOrEmpty(solutionFile)) { p.SetProperty("SolutionPath", Path.GetFullPath(solutionFile)); p.SetProperty("SolutionName", Path.GetFileNameWithoutExtension(solutionFile)); p.SetProperty("SolutionFilename", Path.GetFileName(solutionFile)); p.SetProperty("SolutionDir", Path.GetDirectoryName(solutionFile) + Path.DirectorySeparatorChar); } ; } p.SetProperty("Configuration", configuration); if (!string.IsNullOrEmpty(platform)) { p.SetProperty("Platform", platform); } else { p.SetProperty("Platform", ""); } return(p); }
/// <summary> /// Gets only locally load projects, excluding external /// </summary> public static IReadOnlyCollection <Project> GetLocalProjects(ProjectCollection collection, string projectFile = null) { return((IReadOnlyCollection <Project>)collection.GetLoadedProjects(false, projectFile)); }
public static void VerifyProjectCollectionLinks(this ProjectCollection collection, string path, int expectedLocal, int expectedLinks) => VerifyProjectCollectionLinks(collection.GetLoadedProjects(path), expectedLocal, expectedLinks);
public Project LoadProject(string filePath) { ICollection <Project> loadedProjects = _projectCollection.GetLoadedProjects(filePath); return(HasProjects(loadedProjects) ? GetFirstProject(loadedProjects) : OpenProject(filePath)); }
Project ConfigureProject(string file, string configuration, string platform, string slnConfigContents) { var p = engine.GetLoadedProjects(file).FirstOrDefault(); if (p == null) { var projectDir = Path.GetDirectoryName(file); // HACK: workaround to MSBuild bug #53019. We need to ensure that $(BaseIntermediateOutputPath) exists before // loading the project. if (!string.IsNullOrEmpty(projectDir)) { Directory.CreateDirectory(Path.Combine(projectDir, "obj")); } var content = buildEngine.GetUnsavedProjectContent(file); if (content == null) { p = engine.LoadProject(file); } else { if (!string.IsNullOrEmpty(projectDir) && Directory.Exists(projectDir)) { Environment.CurrentDirectory = projectDir; } var projectRootElement = ProjectRootElement.Create(new XmlTextReader(new StringReader(content))); projectRootElement.FullPath = file; // Use the engine's default tools version to load the project. We want to build with the latest // tools version. string toolsVersion = engine.DefaultToolsVersion; p = new Project(projectRootElement, engine.GlobalProperties, toolsVersion, engine); } } bool reevaluate = false; if (p.GetPropertyValue("Configuration") != configuration || (p.GetPropertyValue("Platform") ?? "") != (platform ?? "")) { p.SetGlobalProperty("Configuration", configuration); if (!string.IsNullOrEmpty(platform)) { p.SetGlobalProperty("Platform", platform); } else { p.RemoveGlobalProperty("Platform"); } reevaluate = true; } // The CurrentSolutionConfigurationContents property only needs to be set once // for the project actually being built // If a build session was started, that property is already set at engine level if (!buildEngine.BuildOperationStarted && this.file == file && p.GetPropertyValue("CurrentSolutionConfigurationContents") != slnConfigContents) { p.SetGlobalProperty("CurrentSolutionConfigurationContents", slnConfigContents); reevaluate = true; } if (reevaluate) { p.ReevaluateIfNecessary(); } return(p); }