本文整理汇总了C#中Microsoft.Build.Evaluation.Project类的典型用法代码示例。如果您正苦于以下问题:C# Microsoft.Build.Evaluation.Project类的具体用法?C# Microsoft.Build.Evaluation.Project怎么用?C# Microsoft.Build.Evaluation.Project使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Microsoft.Build.Evaluation.Project类属于命名空间,在下文中一共展示了Microsoft.Build.Evaluation.Project类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CSharpProject
public CSharpProject(Solution solution, string title, string fileName)
{
this.Solution = solution;
this.Title = title;
this.FileName = fileName;
var p = new Microsoft.Build.Evaluation.Project(fileName);
this.AssemblyName = p.GetPropertyValue("AssemblyName");
this.CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(p, "AllowUnsafeBlocks") ?? false;
this.CompilerSettings.CheckForOverflow = GetBoolProperty(p, "CheckForOverflowUnderflow") ?? false;
foreach (string symbol in p.GetPropertyValue("DefineConstants").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) {
this.CompilerSettings.ConditionalSymbols.Add(symbol.Trim());
}
foreach (var item in p.GetItems("Compile")) {
Files.Add(new CSharpFile(this, Path.Combine(p.DirectoryPath, item.EvaluatedInclude)));
}
List<IAssemblyReference> references = new List<IAssemblyReference>();
string mscorlib = FindAssembly(Program.AssemblySearchPaths, "mscorlib");
if (mscorlib != null) {
references.Add(Program.LoadAssembly(mscorlib));
} else {
Console.WriteLine("Could not find mscorlib");
}
bool hasSystemCore = false;
foreach (var item in p.GetItems("Reference")) {
string assemblyFileName = null;
if (item.HasMetadata("HintPath")) {
assemblyFileName = Path.Combine(p.DirectoryPath, item.GetMetadataValue("HintPath"));
if (!File.Exists(assemblyFileName))
assemblyFileName = null;
}
if (assemblyFileName == null) {
assemblyFileName = FindAssembly(Program.AssemblySearchPaths, item.EvaluatedInclude);
}
if (assemblyFileName != null) {
if (Path.GetFileName(assemblyFileName).Equals("System.Core.dll", StringComparison.OrdinalIgnoreCase))
hasSystemCore = true;
references.Add(Program.LoadAssembly(assemblyFileName));
} else {
Console.WriteLine("Could not find referenced assembly " + item.EvaluatedInclude);
}
}
if (!hasSystemCore && FindAssembly(Program.AssemblySearchPaths, "System.Core") != null)
references.Add(Program.LoadAssembly(FindAssembly(Program.AssemblySearchPaths, "System.Core")));
foreach (var item in p.GetItems("ProjectReference")) {
references.Add(new ProjectReference(solution, item.GetMetadataValue("Name")));
}
this.ProjectContent = new CSharpProjectContent()
.SetAssemblyName(this.AssemblyName)
.SetCompilerSettings(this.CompilerSettings)
.AddAssemblyReferences(references)
.UpdateProjectContent(null, Files.Select(f => f.ParsedFile));
}
示例2: AddEnsureImportedTarget
private static void AddEnsureImportedTarget(MsBuildProject buildProject, string targetsPath)
{
// get the target
var targetElement = buildProject.Xml.Targets.FirstOrDefault(
target => target.Name.Equals(targetName, StringComparison.OrdinalIgnoreCase));
// if the target does not exist, create the target
if (targetElement == null)
{
targetElement = buildProject.Xml.AddTarget(targetName);
// PrepareForBuild is used here because BeforeBuild does not work for VC++ projects.
targetElement.BeforeTargets = "PrepareForBuild";
var propertyGroup = targetElement.AddPropertyGroup();
propertyGroup.AddProperty("ErrorText", CommonResources.EnsureImportedMessage);
}
var errorTask = targetElement.AddTask("Error");
errorTask.Condition = "!Exists('" + targetsPath + "')";
var errorText = string.Format(
CultureInfo.InvariantCulture,
@"$([System.String]::Format('$(ErrorText)', '{0}'))",
targetsPath);
errorTask.SetParameter("Text", errorText);
}
示例3: CreateFromProject
public static ActionsModule CreateFromProject(string projectFile, string outputFile, LightningDevelopmentHandle lightningDevelopmentHandle)
{
var engine = new Microsoft.Build.Evaluation.Project(projectFile);
engine.Build();
return CreateFromDll(outputFile, lightningDevelopmentHandle);
}
示例4: BasicTests
public BasicTests(ITestOutputHelper logger)
{
this.logger = logger;
this.nuproj = Assets.FromTemplate()
.AssignNuProjDirectory()
.ToProject();
}
示例5: AddNewErrorWarningMessageElement
public void AddNewErrorWarningMessageElement()
{
MockLogger logger = new MockLogger();
/**
* <Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
* <Target Name=`Build`>
* </Target>
* </Project
*/
ProjectRootElement projectXml = ProjectRootElement.Create();
ProjectTargetElement target = projectXml.AddTarget("Build");
projectXml.DefaultTargets = "Build";
projectXml.ToolsVersion = ObjectModelHelpers.MSBuildDefaultToolsVersion;
SolutionProjectGenerator.AddErrorWarningMessageElement(target, XMakeElements.message, true, "SolutionVenusProjectNoClean");
SolutionProjectGenerator.AddErrorWarningMessageElement(target, XMakeElements.warning, true, "SolutionParseUnknownProjectType", "proj1.csproj");
SolutionProjectGenerator.AddErrorWarningMessageElement(target, XMakeElements.error, true, "SolutionInvalidSolutionConfiguration");
Project project = new Project(projectXml);
project.Build(logger);
string code = null;
string keyword = null;
string text = ResourceUtilities.FormatResourceString(out code, out keyword, "SolutionParseUnknownProjectType", "proj1.csproj");
// check the error event
Assert.AreEqual(1, logger.Warnings.Count);
BuildWarningEventArgs warning = logger.Warnings[0];
Assert.AreEqual(text, warning.Message);
Assert.AreEqual(code, warning.Code);
Assert.AreEqual(keyword, warning.HelpKeyword);
code = null;
keyword = null;
text = ResourceUtilities.FormatResourceString(out code, out keyword, "SolutionInvalidSolutionConfiguration");
// check the warning event
Assert.AreEqual(1, logger.Errors.Count);
BuildErrorEventArgs error = logger.Errors[0];
Assert.AreEqual(text, error.Message);
Assert.AreEqual(code, error.Code);
Assert.AreEqual(keyword, error.HelpKeyword);
code = null;
keyword = null;
text = ResourceUtilities.FormatResourceString(out code, out keyword, "SolutionVenusProjectNoClean");
// check the message event
Assert.IsTrue(logger.FullLog.Contains(text), "Log should contain the regular message");
}
示例6: AddFeatureFileLinkToIntelliSenseProject
private static void AddFeatureFileLinkToIntelliSenseProject(string featureFilePath, string featureDir, string pathToIntelliSenseProject)
{
_csProj = _csProj ?? GetUnloadedProject(pathToIntelliSenseProject);
featureFilePath = MakeLinkRelativeToIntelliSenseProject(featureFilePath, featureDir);
var featureFileLink = featureFilePath.Replace(@"..\", string.Empty);
if (!_csProj.Items.Any(item => item.GetMetadataValue("Link") == featureFileLink))
{
_csProj.AddItem("None", featureFilePath, new Dictionary<string, string> { { "Link", featureFileLink } });
_isDirtyCsProj = true;
}
}
示例7: Build
/// <summary>
/// Builds this project, using the default targets and the given loggers.
/// </summary>
/// <param name="loggers">An enumerator over all loggers to be used during the build.</param>
/// <returns>
/// Returns true on success; false otherwise.
/// </returns>
public bool Build(IEnumerable<ILogger> loggers)
{
var result = false;
this.SwapMSBuildTasks();
using (var reader = this.Document.CreateReader())
{
reader.MoveToContent();
var innerProject = new Microsoft.Build.Evaluation.Project(reader);
result = innerProject.Build(loggers.Prepend(this.Logger));
reader.Close();
}
return result;
}
示例8: AddFilesToCppProject
private static void AddFilesToCppProject(string pathToFile, string featureDir, string pathToCppProject)
{
_cppProj = _cppProj ?? GetUnloadedProject(pathToCppProject);
pathToFile = MakeFeatureDirRelativeToCppProject(pathToFile, featureDir);
string type = CppFileType(pathToFile);
if (!_cppProj.GetItems(type).Any(item => item.UnevaluatedInclude == pathToFile))
{
_cppProj.AddItem(type, pathToFile);
_isDirtyCppProj = true;
}
}
示例9: ToHierarchy
/// <summary>
/// Toes the hierarchy.
/// </summary>
/// <param name="project">The project.</param>
/// <returns></returns>
public static IVsHierarchy ToHierarchy(EnvDTE.Project project)
{
if (project == null) throw new ArgumentNullException("project");
// DTE does not expose the project GUID that exists at in the msbuild project file.
Microsoft.Build.Evaluation.Project msproject = new Microsoft.Build.Evaluation.Project();
msproject.FullPath = project.FileName;
string guid = msproject.GetPropertyValue("ProjectGuid");
IServiceProvider serviceProvider = new ServiceProvider(project.DTE as
Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
return VsShellUtilities.GetHierarchy(serviceProvider, new Guid(guid));
}
示例10: ConfigProjectImport
private static void ConfigProjectImport(Project project, string targetRelativePath, string configTransformTargetFile)
{
// clear out any existing value
var importPathMSBuildProperty = "ConfigTransformTargetPath";
var msbuildProp = project.Xml.Properties.Where(x => x.Name == importPathMSBuildProperty).ToArray();
msbuildProp.Delete();
// creates a property to store the target file path
var importPath = $"$({importPathMSBuildProperty})\\{configTransformTargetFile}";
project.Xml.AddProperty(importPathMSBuildProperty, targetRelativePath);
// create import element with exists condition and add as last project import
var importXmlElement = project.Xml.CreateImportElement(importPath);
importXmlElement.Condition = $"Exists('{importPath}')";
project.Xml.InsertAfterChild(importXmlElement, project.Xml.Imports.Last());
}
示例11: RemoveImportStatement
/// <summary>
/// Removes the Import element from the project file.
/// </summary>
/// <param name="project">The project file.</param>
/// <param name="targetsPath">The path to the imported file.</param>
public static void RemoveImportStatement(MsBuildProject project, string targetsPath)
{
if (project.Xml.Imports != null)
{
// search for this import statement and remove it
var importElement = project.Xml.Imports.FirstOrDefault(
import => targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase));
if (importElement != null)
{
importElement.Parent.RemoveChild(importElement);
NuGet.MSBuildProjectUtility.RemoveEnsureImportedTarget(project, targetsPath);
project.ReevaluateIfNecessary();
}
}
}
示例12: CSharpProject
public CSharpProject(Solution solution, string title, string fileName)
{
// Normalize the file name
fileName = Path.GetFullPath(fileName);
this.Solution = solution;
this.Title = title;
this.FileName = fileName;
// Use MSBuild to open the .csproj
var msbuildProject = new Microsoft.Build.Evaluation.Project(fileName);
// Figure out some compiler settings
this.AssemblyName = msbuildProject.GetPropertyValue("AssemblyName");
this.CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(msbuildProject, "AllowUnsafeBlocks") ?? false;
this.CompilerSettings.CheckForOverflow = GetBoolProperty(msbuildProject, "CheckForOverflowUnderflow") ?? false;
string defineConstants = msbuildProject.GetPropertyValue("DefineConstants");
foreach (string symbol in defineConstants.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
this.CompilerSettings.ConditionalSymbols.Add(symbol.Trim());
// Initialize the unresolved type system
IProjectContent pc = new CSharpProjectContent();
pc = pc.SetAssemblyName(this.AssemblyName);
pc = pc.SetProjectFileName(fileName);
pc = pc.SetCompilerSettings(this.CompilerSettings);
// Parse the C# code files
foreach (var item in msbuildProject.GetItems("Compile")) {
var file = new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude));
Files.Add(file);
}
// Add parsed files to the type system
pc = pc.AddOrUpdateFiles(Files.Select(f => f.UnresolvedTypeSystemForFile));
// Add referenced assemblies:
foreach (string assemblyFile in ResolveAssemblyReferences(msbuildProject)) {
IUnresolvedAssembly assembly = solution.LoadAssembly(assemblyFile);
pc = pc.AddAssemblyReferences(new [] { assembly });
}
// Add project references:
foreach (var item in msbuildProject.GetItems("ProjectReference")) {
string referencedFileName = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude);
// Normalize the path; this is required to match the name with the referenced project's file name
referencedFileName = Path.GetFullPath(referencedFileName);
pc = pc.AddAssemblyReferences(new[] { new ProjectReference(referencedFileName) });
}
this.ProjectContent = pc;
}
示例13: AddImportStatement
/// <summary>
/// Adds an Import element to this project file if it doesn't already exist.
/// </summary>
/// <param name="project">The project file.</param>
/// <param name="targetsPath">The path to the imported file.</param>
/// <param name="location">The location where the Import is added.</param>
public static void AddImportStatement(MsBuildProject project, string targetsPath, ProjectImportLocation location)
{
if (project.Xml.Imports == null ||
project.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
{
ProjectImportElement pie = project.Xml.AddImport(targetsPath);
pie.Condition = "Exists('" + targetsPath + "')";
if (location == ProjectImportLocation.Top)
{
// There's no public constructor to create a ProjectImportElement directly.
// So we have to cheat by adding Import at the end, then remove it and insert at the beginning
pie.Parent.RemoveChild(pie);
project.Xml.InsertBeforeChild(pie, project.Xml.FirstChild);
}
NuGet.MSBuildProjectUtility.AddEnsureImportedTarget(project, targetsPath);
project.ReevaluateIfNecessary();
}
}
示例14: CSharpProject
/// <summary>
/// The resolved type system for this project.
/// This field is initialized once all projects have been loaded (in Solution constructor).
/// </summary>
public CSharpProject(Solution solution, string title, string fileName)
{
// Normalize the file name
fileName = Path.GetFullPath(fileName);
this.Solution = solution;
this.Title = title;
this.FileName = fileName;
// Use MSBuild to open the .csproj
var msbuildProject = new Microsoft.Build.Evaluation.Project(fileName);
// Figure out some compiler settings
this.AssemblyName = msbuildProject.GetPropertyValue("AssemblyName");
// Parse the C# code files
foreach (var item in msbuildProject.GetItems("Compile"))
{
var file = new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude));
Files.Add(file);
}
}
示例15: RemoveEnsureImportedTarget
public static void RemoveEnsureImportedTarget(MsBuildProject buildProject, string targetsPath)
{
var targetElement = buildProject.Xml.Targets.FirstOrDefault(
target => string.Equals(target.Name, targetName, StringComparison.OrdinalIgnoreCase));
if (targetElement == null)
{
return;
}
string errorCondition = "!Exists('" + targetsPath + "')";
var taskElement = targetElement.Tasks.FirstOrDefault(
task => string.Equals(task.Condition, errorCondition, StringComparison.OrdinalIgnoreCase));
if (taskElement == null)
{
return;
}
taskElement.Parent.RemoveChild(taskElement);
if (targetElement.Tasks.Count == 0)
{
targetElement.Parent.RemoveChild(targetElement);
}
}