本文整理汇总了C#中Microsoft.Build.Evaluation.ProjectCollection.UnloadProject方法的典型用法代码示例。如果您正苦于以下问题:C# ProjectCollection.UnloadProject方法的具体用法?C# ProjectCollection.UnloadProject怎么用?C# ProjectCollection.UnloadProject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Build.Evaluation.ProjectCollection
的用法示例。
在下文中一共展示了ProjectCollection.UnloadProject方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetFile
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;
}
}
示例2: foreach
//.........这里部分代码省略.........
Microsoft.Build.Evaluation.ToolsetDefinitionLocations.ConfigurationFile | Microsoft.Build.Evaluation.ToolsetDefinitionLocations.Registry,
cpuCount,
onlyLogCriticalEvents
);
if (debugger)
{
// Debugging is not currently fully supported so we don't want to open
// public API for it. Also, we want to have a way to make it work when running inside VS.
// So use an environment variable. The undocumented /debug switch is just an easy way to set it.
Environment.SetEnvironmentVariable("MSBUILDDEBUGGING", "1");
}
if (toolsVersion != null && !projectCollection.ContainsToolset(toolsVersion))
{
ThrowInvalidToolsVersionInitializationException(projectCollection.Toolsets, toolsVersion);
}
// If the user has requested that the schema be validated, do that here.
if (needToValidateProject && !FileUtilities.IsSolutionFilename(projectFile))
{
Microsoft.Build.Evaluation.Project project = projectCollection.LoadProject(projectFile, globalProperties, toolsVersion);
Microsoft.Build.Evaluation.Toolset toolset = projectCollection.GetToolset((toolsVersion == null) ? project.ToolsVersion : toolsVersion);
if (toolset == null)
{
ThrowInvalidToolsVersionInitializationException(projectCollection.Toolsets, project.ToolsVersion);
}
ProjectSchemaValidationHandler.VerifyProjectSchema(projectFile, schemaFile, toolset.ToolsPath);
// If there are schema validation errors, an InitializationException is thrown, so if we get here,
// we can safely assume that the project successfully validated.
projectCollection.UnloadProject(project);
}
if (preprocessWriter != null && !FileUtilities.IsSolutionFilename(projectFile))
{
Project project = projectCollection.LoadProject(projectFile, globalProperties, toolsVersion);
project.SaveLogicalProject(preprocessWriter);
projectCollection.UnloadProject(project);
success = true;
}
else
{
BuildRequestData request = new BuildRequestData(projectFile, globalProperties, toolsVersion, targets, null);
BuildParameters parameters = new BuildParameters(projectCollection);
// By default we log synchronously to the console for compatibility with previous versions,
// but it is slightly slower
if (!String.Equals(Environment.GetEnvironmentVariable("MSBUILDLOGASYNC"), "1", StringComparison.Ordinal))
{
parameters.UseSynchronousLogging = true;
}
parameters.EnableNodeReuse = enableNodeReuse;
parameters.NodeExeLocation = Assembly.GetExecutingAssembly().Location;
parameters.MaxNodeCount = cpuCount;
parameters.Loggers = projectCollection.Loggers;
parameters.ForwardingLoggers = remoteLoggerRecords;
parameters.ToolsetDefinitionLocations = Microsoft.Build.Evaluation.ToolsetDefinitionLocations.ConfigurationFile | Microsoft.Build.Evaluation.ToolsetDefinitionLocations.Registry;
parameters.DetailedSummary = detailedSummary;
parameters.LogTaskInputs = logTaskInputs;
示例3: ConcurrentProjectOpenAndCloseThroughProject
public void ConcurrentProjectOpenAndCloseThroughProject()
{
int iterations = 500;
string[] paths = ObjectModelHelpers.GetTempFiles(iterations);
try
{
Project[] projects = new Project[iterations];
for (int i = 0; i < iterations; i++)
{
CreatePREWithSubstantialContent().Save(paths[i]);
}
var collection = new ProjectCollection();
int counter = 0;
int remaining = iterations;
var done = new ManualResetEvent(false);
for (int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
var current = Interlocked.Increment(ref counter) - 1;
projects[current] = collection.LoadProject(paths[current]);
if (Interlocked.Decrement(ref remaining) == 0)
{
done.Set();
}
});
}
done.WaitOne();
Assert.AreEqual(iterations, collection.LoadedProjects.Count);
counter = 0;
remaining = iterations;
done.Reset();
for (int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
var current = Interlocked.Increment(ref counter) - 1;
var pre = projects[current].Xml;
collection.UnloadProject(projects[current]);
collection.UnloadProject(pre);
if (Interlocked.Decrement(ref remaining) == 0)
{
done.Set();
}
});
}
done.WaitOne();
Assert.AreEqual(0, collection.LoadedProjects.Count);
}
finally
{
for (int i = 0; i < iterations; i++)
{
File.Delete(paths[i]);
}
}
}
示例4: RemovingFilesRemovesEntries
public void RemovingFilesRemovesEntries()
{
string content = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
<ItemGroup>Content</ItemGroup>
</Project>
");
string path = FileUtilities.GetTemporaryFile();
try
{
File.WriteAllText(path, content);
ProjectStringCache cache = new ProjectStringCache();
ProjectCollection collection = new ProjectCollection();
int entryCount;
ProjectRootElement pre1 = ProjectRootElement.Create(collection);
pre1.XmlDocument.StringCache = cache;
pre1.FullPath = path;
pre1.XmlDocument.Load(path);
entryCount = cache.Count;
Assert.IsTrue(entryCount > 0);
ProjectRootElement pre2 = ProjectRootElement.Create(collection);
pre2.XmlDocument.StringCache = cache;
pre2.FullPath = path;
pre2.XmlDocument.Load(path);
// Entry count should not have changed
Assert.AreEqual(entryCount, cache.Count);
string itemGroupContent = cache.Get("Content");
Assert.IsNotNull(itemGroupContent);
XmlNodeList nodes1 = pre1.XmlDocument.GetElementsByTagName("ItemGroup");
XmlNodeList nodes2 = pre2.XmlDocument.GetElementsByTagName("ItemGroup");
Assert.AreEqual(1, nodes1.Count);
Assert.AreEqual(1, nodes2.Count);
XmlNode node1 = nodes1[0];
XmlNode node2 = nodes2[0];
Assert.IsNotNull(node1);
Assert.IsNotNull(node2);
Assert.AreNotSame(node1, node2);
Assert.AreSame(node1.Value, node2.Value);
// Now remove one document
collection.UnloadProject(pre1);
// We should still be able to get Content
itemGroupContent = cache.Get("Content");
Assert.IsNotNull(itemGroupContent);
// Now remove the second document
collection.UnloadProject(pre2);
// Now we should not be able to get Content
itemGroupContent = cache.Get("Content");
Assert.IsNull(itemGroupContent);
// And there should be no entries
Assert.AreEqual(0, cache.Count);
}
finally
{
File.Delete(path);
}
}
示例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: SaveToNewNameAndUnload
public void SaveToNewNameAndUnload()
{
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);
ProjectCollection collection = new ProjectCollection();
Project project2 = collection.LoadProject(file1);
project2.Save(file2);
collection.UnloadProject(project2);
}
finally
{
File.Delete(file1);
File.Delete(file2);
}
}
示例7: 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.");
}
}
示例8: LoadFile
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);
}
}
示例9: ReinitializeMsBuildProject
/// <summary>
/// Loads a project file for the file. If the build project exists and it was loaded with a different file then it is unloaded first.
/// </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>
/// <param name="exitingBuildProject">An Existing build project that will be reloaded.</param>
/// <returns>A loaded msbuild project.</returns>
internal static Microsoft.Build.Evaluation.Project ReinitializeMsBuildProject(ProjectCollection buildEngine, string fullProjectPath, Microsoft.Build.Evaluation.Project exitingBuildProject)
{
// If we have a build project that has been loaded with another file unload it.
try
{
if (exitingBuildProject != null && exitingBuildProject.ProjectCollection != null && !CommonUtils.IsSamePath(exitingBuildProject.FullPath, fullProjectPath))
{
buildEngine.UnloadProject(exitingBuildProject);
}
}
// We catch Invalid operation exception because if the project was unloaded while we touch the ParentEngine the msbuild API throws.
// Is there a way to figure out that a project was unloaded?
catch (InvalidOperationException)
{
}
return InitializeMsBuildProject(buildEngine, fullProjectPath);
}
示例10: Execute
/// <summary>
/// Executes the task.
/// </summary>
/// <returns>True if the task executed successfully; otherwise, false.</returns>
public bool Execute()
{
var fullPath = SourceProjectPath;
var basePath = Path.GetDirectoryName( fullPath );
var regex = CreateRegularExpressionForAssemblyInfo();
using ( var projectCollection = new ProjectCollection() )
{
var project = projectCollection.LoadProject( fullPath );
try
{
// note: the reason we open the project and examine the items rather than just emumerate the
// file system is that the process would miss linked files. we should be able to assemble the
// assembly attributes from all assembly info files, even they are linked files or imported
// from a source that cannot be evaluated by looking at the file system alone.
var assemblyInfos = from item in project.GetItems( "Compile" )
let include = item.EvaluatedInclude
where regex.IsMatch( include )
let itemPath = Path.GetFullPath( Path.Combine( basePath, include ) )
let code = File.ReadAllText( itemPath )
select CSharpSyntaxTree.ParseText( code );
var references = new[] { MetadataReference.CreateFromFile( typeof( object ).Assembly.Location ) };
var compilation = CSharpCompilation.Create( project.GetPropertyValue( "AssemblyName" ), assemblyInfos, references );
var attributes = compilation.Assembly.GetAttributes().ToArray();
IsValid = true;
PopulateMetadataFromAttributes( attributes );
}
finally
{
projectCollection.UnloadProject( project );
}
}
return IsValid;
}