public void Dispose() { _buildManager.Dispose(); _projectCollection.Dispose(); _env.Dispose(); EvaluationContext.TestOnlyHookOnCreate = null; }
/// <summary> /// Cleaning cached variables. /// </summary> public static void ClearCache() { if (_allProjects != null) { _allProjects.Dispose(); _allProjects = null; } }
/// <summary> /// Override of IDisposable.Dispose to handle implementation details of dispose /// </summary> public void Dispose() { GC.SuppressFinalize(this); if (_projectCollection != null) { _projectCollection.Dispose(); } }
private void GenerateProjectFile() { var projectExtension = Path.GetExtension(ProjectFilePath); if (!File.Exists(ProjectFilePath) || ".dll".Equals(projectExtension, StringComparison.OrdinalIgnoreCase) || ".winmd".Equals(projectExtension, StringComparison.OrdinalIgnoreCase)) { return; } ProjectCollection projectCollection = null; try { var title = Path.GetFileName(ProjectFilePath); var destinationFileName = Path.Combine(ProjectDestinationFolder, title) + ".html"; AddDeclaredSymbolToRedirectMap(SymbolIDToListOfLocationsMap, SymbolIdService.GetId(title), title, 0); // ProjectCollection caches the environment variables it reads at startup // and doesn't re-get them later. We need a new project collection to read // the latest set of environment variables. projectCollection = new ProjectCollection(); this.msbuildProject = new Project( ProjectFilePath, null, null, projectCollection, ProjectLoadSettings.IgnoreMissingImports); var msbuildSupport = new MSBuildSupport(this); msbuildSupport.Generate(ProjectFilePath, destinationFileName, msbuildProject, true); GenerateXmlFiles(msbuildProject); GenerateXamlFiles(msbuildProject); GenerateResxFiles(msbuildProject); GenerateTypeScriptFiles(msbuildProject); OtherFiles.Add(title); } catch (Exception ex) { Log.Exception("Exception during Project file generation: " + ProjectFilePath + "\r\n" + ex.ToString()); } finally { if (projectCollection != null) { projectCollection.UnloadAllProjects(); projectCollection.Dispose(); } } }
private void ClearLoadedProjects() { ClearPreviousProjects(); _allAnalyzeResults.Clear(); if (_projectCollection != null) { _projectCollection.UnloadAllProjects(); _projectCollection.Dispose(); } _projectCollection = new ProjectCollection(); IsLoaded = false; ShowPreviousProjectCommand.RaiseCanExecuteChanged(); AllSolutions.Clear(); AllProjects.Clear(); }
public void Dispose() { _projectCollection.Dispose(); }
public void Dispose() { _workspace?.Dispose(); _workspace = null; ProjectCollection.Dispose(); }
/// <summary> /// Recursively loads and evaluates MSBuild projects. /// </summary> /// <param name="entryProjects">An <see cref="IEnumerable{ProjectGraphEntryPoint}" /> containing the entry projects to load.</param> /// <returns>An <see cref="ICollection{ProjectWithInnerNodes}" /> object containing projects and their inner nodes if they are targeting multiple frameworks.</returns> private ICollection <ProjectWithInnerNodes> LoadProjects(IEnumerable <ProjectGraphEntryPoint> entryProjects) { var loggers = new List <Microsoft.Build.Framework.ILogger> { LoggingQueue }; // Get user specified parameters for a binary logger string binlogParameters = Environment.GetEnvironmentVariable("RESTORE_TASK_BINLOG_PARAMETERS"); // Attach the binary logger if Debug or binlog parameters were specified if (Debug || !string.IsNullOrWhiteSpace(binlogParameters)) { loggers.Add(new BinaryLogger { // Default the binlog parameters if only the debug option was specified Parameters = binlogParameters ?? "LogFile=nuget.binlog" }); } var projects = new ConcurrentDictionary <string, ProjectWithInnerNodes>(StringComparer.OrdinalIgnoreCase); var projectCollection = new ProjectCollection( globalProperties: null, // Attach a logger for evaluation only if the Debug option is set loggers: loggers, remoteLoggers: null, toolsetDefinitionLocations: ToolsetDefinitionLocations.Default, // Having more than 1 node spins up multiple msbuild.exe instances to run builds in parallel // However, these targets complete so quickly that the added overhead makes it take longer maxNodeCount: 1, onlyLogCriticalEvents: false, // Loading projects as readonly makes parsing a little faster since comments and whitespace can be ignored loadProjectsReadOnly: true); var failedBuildSubmissions = new ConcurrentBag <BuildSubmission>(); try { var sw = Stopwatch.StartNew(); var evaluationContext = EvaluationContext.Create(EvaluationContext.SharingPolicy.Shared); ProjectGraph projectGraph; int buildCount = 0; var buildParameters = new BuildParameters(projectCollection) { // Use the same loggers as the project collection Loggers = projectCollection.Loggers, LogTaskInputs = Debug }; // BeginBuild starts a queue which accepts build requests and applies the build parameters to all of them BuildManager.DefaultBuildManager.BeginBuild(buildParameters); try { // Create a ProjectGraph object and pass a factory method which creates a ProjectInstance projectGraph = new ProjectGraph(entryProjects, projectCollection, (path, properties, collection) => { var projectOptions = new ProjectOptions { EvaluationContext = evaluationContext, GlobalProperties = properties, // Ignore bad imports to maximize the chances of being able to load the project and restore LoadSettings = ProjectLoadSettings.IgnoreEmptyImports | ProjectLoadSettings.IgnoreInvalidImports | ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.DoNotEvaluateElementsWithFalseCondition, ProjectCollection = collection }; // Create a Project object which does the evaluation var project = Project.FromFile(path, projectOptions); // Create a ProjectInstance object which is what this factory needs to return var projectInstance = project.CreateProjectInstance(ProjectInstanceSettings.None, evaluationContext); if (!projectInstance.Targets.ContainsKey("_IsProjectRestoreSupported") || properties.TryGetValue("TargetFramework", out var targetFramework) && string.IsNullOrWhiteSpace(targetFramework)) { // In rare cases, users can set an empty TargetFramework value in a project-to-project reference. Static Graph will respect that // but NuGet does not need to do anything with that instance of the project since the actual project is still loaded correctly // with its actual TargetFramework. return(projectInstance); } // If the project supports restore, queue up a build of the 3 targets needed for restore BuildManager.DefaultBuildManager .PendBuildRequest( new BuildRequestData( projectInstance, TargetsToBuild, hostServices: null, // Suppresses an error that a target does not exist because it may or may not contain the targets that we're running BuildRequestDataFlags.SkipNonexistentTargets)) .ExecuteAsync( callback: buildSubmission => { // If the build failed, add its result to the list to be processed later if (buildSubmission.BuildResult.OverallResult == BuildResultCode.Failure) { failedBuildSubmissions.Add(buildSubmission); } }, context: null); Interlocked.Increment(ref buildCount); // Add the project instance to the list, if its an inner node for a multi-targeting project it will be added to the inner collection projects.AddOrUpdate( path, key => new ProjectWithInnerNodes(targetFramework, new MSBuildProjectInstance(projectInstance)), (_, item) => item.Add(targetFramework, new MSBuildProjectInstance(projectInstance))); return(projectInstance); }); } finally { // EndBuild blocks until all builds are complete BuildManager.DefaultBuildManager.EndBuild(); } sw.Stop(); MSBuildLogger.LogInformation(string.Format(CultureInfo.CurrentCulture, Strings.ProjectEvaluationSummary, projectGraph.ProjectNodes.Count, sw.ElapsedMilliseconds, buildCount, failedBuildSubmissions.Count)); if (failedBuildSubmissions.Any()) { // Return null if any builds failed, they will have logged errors return(null); } } catch (Exception e) { LoggingQueue.TaskLoggingHelper.LogErrorFromException(e, showStackTrace: true); return(null); } finally { projectCollection.Dispose(); } // Just return the projects not the whole dictionary as it was just used to group the projects together return(projects.Values); }
/// <inheritdoc cref="IDisposable.Dispose" /> public void Dispose() { (_logger as IDisposable)?.Dispose(); _projectCollection?.Dispose(); }
public void Dispose() { _projectCollection.UnloadAllProjects(); _projectCollection.Dispose(); }
internal static void LoadPlugins() { Plugins.Clear(); string[] directories = Directory.GetDirectories(Utilities.Utilities.ApplicationPath + "\\Plugins"); foreach (string directory in directories) { try { string[] projectFiles = Directory.GetFiles(directory, "*.csproj", SearchOption.AllDirectories); if (projectFiles.Length > 1) { Logging.Write( "[{0}] Multiple projects detected. Please have only one .csproj file in the main plugin directory.", directory); continue; } string s = projectFiles[0]; var globalProperties = new Dictionary <string, string> { { "Configuration", "Release" }, { "Platform", "x86" } }; var pc = new ProjectCollection(globalProperties); pc.RegisterLogger(new BasicFileLogger()); try { Project loadProject = pc.LoadProject(s, "4.0"); bool successfulBuild = loadProject.Build(); if (successfulBuild) { ProjectProperty pp = loadProject.GetProperty("OutputPath"); ProjectProperty name = loadProject.GetProperty("AssemblyName"); ProjectProperty type = loadProject.GetProperty("OutputType"); if (name != null && pp != null && type != null) { if (type.EvaluatedValue.Equals("Library")) { string file = loadProject.DirectoryPath + "\\" + pp.EvaluatedValue + name.EvaluatedValue + ".dll"; Assembly asm = Assembly.LoadFile(file); Type[] types = asm.GetTypes(); foreach (Type t in types) { if (t.IsClass && typeof(IPlugin).IsAssignableFrom(t)) { var temp = (IPlugin)Activator.CreateInstance(t); if (!Plugins.ContainsKey(temp.Name)) { Plugins.Add(temp.Name, new PluginContainer(temp)); try { temp.OnLoad(); } catch (Exception ex) { Logging.Write("Error loading plugin: {0}", temp.Name); Logging.Log(ex); } } } } } else { Logging.Write("[{0}] Output Type is not \"Library\" Please change this setting.", directory); } } else { Logging.Write(Resources.PluginError, directory); } } } catch (Exception ex) { Logging.Write(ex.Message); } pc.Dispose(); } catch (Exception ex) { Logging.Log(ex); Logging.Write(Resources.PluginError, directory); } } }