本文整理汇总了C#中Microsoft.Build.Evaluation.ProjectCollection.UnloadAllProjects方法的典型用法代码示例。如果您正苦于以下问题:C# ProjectCollection.UnloadAllProjects方法的具体用法?C# ProjectCollection.UnloadAllProjects怎么用?C# ProjectCollection.UnloadAllProjects使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Build.Evaluation.ProjectCollection
的用法示例。
在下文中一共展示了ProjectCollection.UnloadAllProjects方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateProjectFile
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);
GenerateXamlFiles(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();
}
}
}
示例2: DiscoverTests
/// <summary>
/// ITestDiscover, Given a list of test sources this method pulls out the test cases
/// </summary>
/// <param name="sources">List of test sources passed from client (Client can be VS or command line)</param>
/// <param name="discoveryContext">Context and runSettings for current run. Discoverer pulls out the tests based on current context</param>
/// <param name="logger">Used to relay messages to registered loggers</param>
/// <param name="discoverySink">Callback used to notify client upon discovery of test cases</param>
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink) {
ValidateArg.NotNull(sources, "sources");
ValidateArg.NotNull(discoverySink, "discoverySink");
ValidateArg.NotNull(logger, "logger");
using (var buildEngine = new MSBuild.ProjectCollection()) {
try {
// Load all the test containers passed in (.njsproj msbuild files)
foreach (string source in sources) {
buildEngine.LoadProject(source);
}
foreach (var proj in buildEngine.LoadedProjects) {
var projectHome = Path.GetFullPath(Path.Combine(proj.DirectoryPath, "."));
Dictionary<string, List<TestFileEntry>> testItems = new Dictionary<string,List<TestFileEntry>>(StringComparer.OrdinalIgnoreCase);
// Provide all files to the test analyzer
foreach (var item in proj.Items.Where(item => item.ItemType == "Compile" || item.ItemType == "TypeScriptCompile")) {
//Check to see if this is a TestCase
string value = item.GetMetadataValue("TestFramework");
if (!TestContainerDiscoverer.IsValidTestFramework(value)) {
continue;
}
string fileAbsolutePath = CommonUtils.GetAbsoluteFilePath(projectHome, item.EvaluatedInclude);
bool typeScriptTest = TypeScript.TypeScriptHelpers.IsTypeScriptFile(fileAbsolutePath);
if(typeScriptTest){
fileAbsolutePath = TypeScript.TypeScriptHelpers.GetTypeScriptBackedJavaScriptFile(proj,fileAbsolutePath);
} else if (!Path.GetExtension(fileAbsolutePath).Equals(".js", StringComparison.OrdinalIgnoreCase)) {
continue;
}
List<TestFileEntry> fileList;
if (!testItems.TryGetValue(value, out fileList)){
fileList = new List<TestFileEntry>();
testItems.Add(value, fileList);
}
fileList.Add(new TestFileEntry(fileAbsolutePath,typeScriptTest));
}
//Debug.Fail("Before Discover");
DiscoverTests(testItems, proj, discoverySink, logger);
}
} catch (Exception ex) {
logger.SendMessage(TestMessageLevel.Error, ex.Message);
throw;
} finally {
// Disposing buildEngine does not clear the document cache in
// VS 2013, so manually unload all projects before disposing.
buildEngine.UnloadAllProjects();
}
}
}
示例3: Build
//.........这里部分代码省略.........
using (var projectCollection = new ProjectCollection(globalProperties, loggers, ToolsetDefinitionLocations.Registry))
{
// The only way to communicate to msbuild is to create an xml file, and pass it to msbuild
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
var xmlTarget = new XElement(ns + "Target", new XAttribute("Name", "Build"));
var properties = "";
foreach (var projectPath in ProjectsPath)
{
Contract.Assert(projectPath != null);
xmlTarget.Add(new XElement(ns + "MSBuild",
new XAttribute("Projects", Path.Combine(this.SourceDirectory, projectPath)),
new XAttribute("Targets", "Rebuild"), // ensures the project will be rebuilt from scratch (is it needed?)
new XAttribute("UseResultsCache", "false"),
new XAttribute("UnloadProjectsOnCompletion", "true"),
new XAttribute("ContinueOnError", "true"),
new XAttribute("StopOnFirstFailure", "false"),
new XAttribute("Properties", properties)));
}
// create the project
var xmlProject = new XElement(ns + "Project", xmlTarget);
// now read the project
var project = projectCollection.LoadProject(xmlProject.CreateReader());
// create an instance of the project
var projectInstance = project.CreateProjectInstance();
// create the parameters for the build
var buildParameters = new BuildParameters(projectCollection);
buildParameters.EnableNodeReuse = false;
buildParameters.ResetCaches = true;
buildParameters.Loggers = overallLoggers;
buildParameters.MaxNodeCount = Environment.ProcessorCount;
// Ask a build on this project
var buildRequestData = new BuildRequestData(projectInstance, new string[] { "Build" });
// we need to create a new BuildManager each time, otherwise it wrongly caches project files
var buildManager = new BuildManager();
// now do the build!
var buildResult = buildManager.Build(buildParameters, buildRequestData);
ret = buildResult.OverallResult == BuildResultCode.Success;
#if WITH_LOG
logger.Shutdown();
#endif
// now cleanup - it seems it does not improve
projectCollection.UnregisterAllLoggers();
projectCollection.UnloadAllProjects();
}
#region Version using the default BuildManager (disabled)
#if false
// First version. It does not work, because msbuild keeps a cache of the projects, and so it compiles the new files with the old project
// The Log works
Microsoft.Build.Execution.BuildManager.DefaultBuildManager.ResetCaches(); // ensures MSBuild doesn't use cached version of project files (it handles very badly versions changing!), not sure it works
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
var xmlTarget = new XElement(ns + "Target", new XAttribute("Name", "Build"));
var properties = "";
properties += ";CodeContractsCacheDirectory=" + OutputDirectory;
properties += ";CodeContractsCacheAnalysisResults=true";
properties += ";CodeContractsCacheVersion=" + VersionId;
foreach (var projectPath in ProjectsPath)
{
Contract.Assume(projectPath != null);
xmlTarget.Add(new XElement(ns + "MSBuild",
new XAttribute("Projects", Path.Combine(this.WorkingDirectory, projectPath)),
new XAttribute("Targets", "Rebuild"), // ensures the project will be rebuilt from scratch (is it needed?)
new XAttribute("UseResultsCache", "false"),
new XAttribute("UnloadProjectsOnCompletion", "true"),
new XAttribute("ContinueOnError", "true"),
new XAttribute("StopOnFirstFailure", "false"),
new XAttribute("Properties", properties)));
}
var xmlProject = new XElement(ns + "Project", xmlTarget);
var project = new Project(xmlProject.CreateReader());
var logFileName = "build." + VersionId + ".log";
var logger = new Microsoft.Build.Logging.FileLogger();
logger.Parameters = "logfile=" + Path.Combine(OutputDirectory, logFileName);
ret = project.Build(logger);
#endif
#endregion
}
catch
{
ret = false;
}
return ret;
}
示例4: Generate
/// <summary>
/// Generates the solution file with the specified amount of space remaining relative
/// to MAX_PATH.
/// </summary>
/// <param name="solutionName">The solution name to be created</param>
/// <param name="pathSpaceRemaining">The amount of path space remaining, or -1 to generate normally</param>
/// <param name="toGenerate">The projects to be incldued in the generated solution</param>
/// <returns></returns>
public static SolutionFile Generate(string solutionName, int pathSpaceRemaining, params ISolutionElement[] toGenerate) {
List<MSBuild.Project> projects = new List<MSBuild.Project>();
var location = TestData.GetTempPath(randomSubPath: true);
if (pathSpaceRemaining >= 0) {
int targetPathLength = 260 - pathSpaceRemaining;
location = location + new string('X', targetPathLength - location.Length);
}
System.IO.Directory.CreateDirectory(location);
MSBuild.ProjectCollection collection = new MSBuild.ProjectCollection();
foreach (var project in toGenerate) {
projects.Add(project.Save(collection, location));
}
#if DEV10
StringBuilder slnFile = new StringBuilder("\r\nMicrosoft Visual Studio Solution File, Format Version 11.00\r\n\u0023 Visual Studio 2010\r\n");
#elif DEV11
StringBuilder slnFile = new StringBuilder("\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n\u0023 Visual Studio 2012\r\n");
#elif DEV12
StringBuilder slnFile = new StringBuilder("\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n\u0023 Visual Studio 2013\r\nVisualStudioVersion = 12.0.20827.3\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\n");
#elif DEV14
StringBuilder slnFile = new StringBuilder("\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n\u0023 Visual Studio 2015\r\nVisualStudioVersion = 14.0.22230.0\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\n");
#elif DEV15
StringBuilder slnFile = new StringBuilder("\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n\u0023 Visual Studio 2015\r\nVisualStudioVersion = 15.0.30000.0\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\n");
#else
#error Unsupported VS version
#endif
for (int i = 0; i < projects.Count; i++) {
if (toGenerate[i].Flags.HasFlag(SolutionElementFlags.ExcludeFromSolution)) {
continue;
}
var project = projects[i];
var projectTypeGuid = toGenerate[i].TypeGuid;
slnFile.AppendFormat(@"Project(""{0:B}"") = ""{1}"", ""{2}"", ""{3:B}""
EndProject
", projectTypeGuid,
project != null ? Path.GetFileNameWithoutExtension(project.FullPath) : toGenerate[i].Name,
project != null ? CommonUtils.GetRelativeFilePath(location, project.FullPath): toGenerate[i].Name,
project != null ? Guid.Parse(project.GetProperty("ProjectGuid").EvaluatedValue) : Guid.NewGuid());
}
slnFile.Append(@"Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
");
for (int i = 0; i < projects.Count; i++) {
if (toGenerate[i].Flags.HasFlag(SolutionElementFlags.ExcludeFromConfiguration)) {
continue;
}
var project = projects[i];
slnFile.AppendFormat(@" {0:B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0:B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0:B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0:B}.Release|Any CPU.Build.0 = Release|Any CPU
", Guid.Parse(project.GetProperty("ProjectGuid").EvaluatedValue));
}
slnFile.Append(@" EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
");
collection.UnloadAllProjects();
collection.Dispose();
var slnFilename = Path.Combine(location, solutionName + ".sln");
File.WriteAllText(slnFilename, slnFile.ToString(), Encoding.UTF8);
return new SolutionFile(slnFilename, toGenerate);
}
示例5: LoadUnloadAllReloadSaveToNewName
public void LoadUnloadAllReloadSaveToNewName()
{
string file1 = null;
string file2 = null;
try
{
file1 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
file2 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
Project project = new Project();
project.Save(file1);
project.ProjectCollection.UnloadProject(project);
ProjectCollection collection = new ProjectCollection();
Project project2 = collection.LoadProject(file1);
collection.UnloadAllProjects();
Project project3 = collection.LoadProject(file1);
project3.Save(file2); // should not crash
collection.UnloadProject(project3);
}
finally
{
File.Delete(file1);
File.Delete(file2);
}
}
示例6: VerifyImportedProjectRootElementsInheritExplicitLoadFlag
public void VerifyImportedProjectRootElementsInheritExplicitLoadFlag()
{
string contents1 = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<Import Project='{0}' />
<Target Name='test' />
</Project>
");
string contents2 = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<PropertyGroup>
<ImportedProperty>ImportedValue</ImportedProperty>
</PropertyGroup>
</Project>
");
using (TempFileCollection tfc = new TempFileCollection())
{
string importedProjectPath = FileUtilities.GetTemporaryFile();
string rootProjectPath = FileUtilities.GetTemporaryFile();
tfc.AddFile(importedProjectPath, false);
tfc.AddFile(rootProjectPath, false);
File.WriteAllText(importedProjectPath, contents2);
File.WriteAllText(rootProjectPath, String.Format(CultureInfo.InvariantCulture, contents1, importedProjectPath));
var projectCollection = new ProjectCollection();
// Run a simple build just to prove that nothing is left in the cache.
BuildRequestData data = new BuildRequestData(rootProjectPath, ReadOnlyEmptyDictionary<string, string>.Instance, null, new[] { "test" }, null);
_parameters.ResetCaches = true;
_parameters.ProjectRootElementCache = projectCollection.ProjectRootElementCache;
_buildManager.BeginBuild(_parameters);
BuildResult result = _buildManager.BuildRequest(data);
_buildManager.EndBuild();
_buildManager.ResetCaches();
// The semantic of TryOpen is to only retrieve the PRE if it is already in the weak cache.
Assert.IsNull(Microsoft.Build.Construction.ProjectRootElement.TryOpen(rootProjectPath, projectCollection), "The built project shouldn't be in the cache anymore.");
Assert.IsNull(Microsoft.Build.Construction.ProjectRootElement.TryOpen(importedProjectPath, projectCollection), "The built project's import shouldn't be in the cache anymore.");
Project project = projectCollection.LoadProject(rootProjectPath);
Microsoft.Build.Construction.ProjectRootElement preRoot, preImported;
Assert.IsNotNull(preRoot = Microsoft.Build.Construction.ProjectRootElement.TryOpen(rootProjectPath, projectCollection), "The root project file should be in the weak cache.");
Assert.IsNotNull(preImported = Microsoft.Build.Construction.ProjectRootElement.TryOpen(importedProjectPath, projectCollection), "The imported project file should be in the weak cache.");
Assert.IsTrue(preRoot.IsExplicitlyLoaded);
Assert.IsTrue(preImported.IsExplicitlyLoaded);
// Run a simple build just to prove that it doesn't impact what is in the cache.
data = new BuildRequestData(rootProjectPath, ReadOnlyEmptyDictionary<string, string>.Instance, null, new[] { "test" }, null);
_parameters.ResetCaches = true;
_parameters.ProjectRootElementCache = projectCollection.ProjectRootElementCache;
_buildManager.BeginBuild(_parameters);
result = _buildManager.BuildRequest(data);
_buildManager.EndBuild();
_buildManager.ResetCaches();
// Now make sure they are still in the weak cache. Since they were loaded explictly before the build, the build shouldn't have unloaded them from the cache.
Assert.AreSame(preRoot, Microsoft.Build.Construction.ProjectRootElement.TryOpen(rootProjectPath, projectCollection), "The root project file should be in the weak cache after a build.");
Assert.AreSame(preImported, Microsoft.Build.Construction.ProjectRootElement.TryOpen(importedProjectPath, projectCollection), "The imported project file should be in the weak cache after a build.");
Assert.IsTrue(preRoot.IsExplicitlyLoaded);
Assert.IsTrue(preImported.IsExplicitlyLoaded);
projectCollection.UnloadProject(project);
projectCollection.UnloadAllProjects();
Assert.IsNull(Microsoft.Build.Construction.ProjectRootElement.TryOpen(rootProjectPath, projectCollection), "The unloaded project shouldn't be in the cache anymore.");
Assert.IsNull(Microsoft.Build.Construction.ProjectRootElement.TryOpen(importedProjectPath, projectCollection), "The unloaded project's import shouldn't be in the cache anymore.");
}
}
示例7: GenerateProjectFile
public 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);
projectCollection = new ProjectCollection();
GenerateMsBuildProject(projectCollection);
ExtendGenerator.GenerateConfig(this, msbuildProject); // .config
if (Configuration.ProcessContent)
{
// process content files
GenerateXamlFiles(msbuildProject); // .xaml
GenerateTypeScriptFiles(msbuildProject); // .ts
ExtendGenerator.GenerateContentFiles(this, msbuildProject); // .md, .cshtml, .aspx, .xml, .xslt, .json, .sql
}
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();
}
}
}