本文整理汇总了C#中Microsoft.Build.Evaluation.ProjectCollection.RegisterLogger方法的典型用法代码示例。如果您正苦于以下问题:C# ProjectCollection.RegisterLogger方法的具体用法?C# ProjectCollection.RegisterLogger怎么用?C# ProjectCollection.RegisterLogger使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Build.Evaluation.ProjectCollection
的用法示例。
在下文中一共展示了ProjectCollection.RegisterLogger方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: buildProject
public static bool buildProject(this string projectFile, bool redirectToConsole = false)
{
try
{
var fileLogger = new FileLogger();
var logFile = projectFile.directoryName().pathCombine(projectFile.fileName() + ".log");
fileLogger.field("logFileName", logFile);
if (logFile.fileExists())
logFile.file_Delete();
var projectCollection = new ProjectCollection();
var project = projectCollection.LoadProject(projectFile);
if (project.isNull())
{
"could not load project file: {0}".error(projectFile);
return false;
}
if (redirectToConsole)
projectCollection.RegisterLogger(new ConsoleLogger());
projectCollection.RegisterLogger(fileLogger);
var result = project.Build();
fileLogger.Shutdown();
return result;
}
catch(Exception ex)
{
ex.log();
return false;
}
}
示例2: ImportFromExtensionsPathNotFound
public void ImportFromExtensionsPathNotFound()
{
string extnDir1 = null;
string mainProjectPath = null;
try {
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), GetExtensionTargetsFileContent1());
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
var projColln = new ProjectCollection();
projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", extnDir1, Path.Combine("tmp", "nonexistant")));
var logger = new MockLogger();
projColln.RegisterLogger(logger);
Assert.Throws<InvalidProjectFileException>(() => projColln.LoadProject(mainProjectPath));
logger.AssertLogContains("MSB4226");
} finally {
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
}
}
示例3: BuildProject
/// <summary>
/// Builds the project - based on http://msdn.microsoft.com/en-us/library/microsoft.build.buildengine.engine.aspx.
/// </summary>
/// <param name="projectPath">The project (csproj) path</param>
/// <returns>True if builds okay</returns>
private static bool BuildProject(string projectPath)
{
var logPath = Path.Combine(Path.GetDirectoryName(projectPath), "build.log");
//.Net 4 Microsoft.Build.Evaluation.Project and ProjectCollection
var engine = new ProjectCollection();
// Instantiate a new FileLogger to generate build log
var logger = new Microsoft.Build.Logging.FileLogger();
// Set the logfile parameter to indicate the log destination
logger.Parameters = @"logfile=" + logPath;
// Register the logger with the engine
engine.RegisterLogger(logger);
// Build a project file
bool success = engine.LoadProject(projectPath).Build();
//Unregister all loggers to close the log file
engine.UnregisterAllLoggers();
//if fails, put the log file into the assert statement
string txt = "Should have built";
if (!success && File.Exists(logPath))
txt = File.ReadAllText(logPath);
Console.WriteLine(txt);
return success;
}
示例4: PublishSite
private void PublishSite(Dictionary<string, string> properties)
{
var logFile = Path.GetTempFileName();
try
{
bool success;
using (var projects = new ProjectCollection(properties))
{
projects.RegisterLogger(new FileLogger { Parameters = @"logfile=" + logFile, Verbosity = LoggerVerbosity.Quiet });
projects.OnlyLogCriticalEvents = true;
var project = projects.LoadProject(ProjectPath);
success = project.Build();
}
if (!success)
{
Console.WriteLine(File.ReadAllText(logFile));
throw new ApplicationException("Build failed.");
}
}
finally
{
if (File.Exists(logFile))
{
File.Delete(logFile);
}
}
}
示例5: NullTargetsToBuild
public void NullTargetsToBuild ()
{
string project_xml = @"<Project DefaultTargets='Foo' xmlns='http://schemas.microsoft.com/developer/msbuild/2003' />";
var xml = XmlReader.Create (new StringReader (project_xml));
var root = ProjectRootElement.Create (xml);
root.FullPath = "BuildRequestDataTest.NullTargetsToBuild.proj";
var pc = new ProjectCollection ();
var sw = new StringWriter ();
pc.RegisterLogger (new ConsoleLogger (LoggerVerbosity.Diagnostic, sw.WriteLine, null, null));
var proj = new ProjectInstance (root);
new BuildRequestData (proj, null);
}
示例6: BuildProject
/// <summary>
/// Builds a project (.csproj, .vbproj, etc)
/// </summary>
/// <param name="projectFileName">Physical path to project file</param>
/// <param name="configuration">Configuration to build in (usually "Debug" or "Release")</param>
/// <param name="logFilePath">Physical path to write a build log file to</param>
/// <param name="targets">The build target(s) to build. Usually "Build," "Rebuild," "Clean," etc</param>
/// <returns>True if the project compiled successfully</returns>
public static bool BuildProject(string projectFileName, string configuration, string logFilePath, string[] targets)
{
var projects = new ProjectCollection(ToolsetDefinitionLocations.Registry);
var logger = new FileLogger();
logger.Parameters = @"logfile=" + logFilePath;
projects.RegisterLogger(logger);
projects.DefaultToolsVersion = "4.0";
projects.SetGlobalProperty("Configuration", configuration);
return projects.LoadProject(projectFileName).Build(targets);
}
示例7: ProjectBuilder
public ProjectBuilder (string file, string binDir)
{
this.file = file;
RunSTA (delegate
{
engine = new ProjectCollection ();
engine.SetGlobalProperty ("BuildingInsideVisualStudio", "true");
//we don't have host compilers in MD, and this is set to true by some of the MS targets
//which causes it to always run the CoreCompile task if BuildingInsideVisualStudio is also
//true, because the VS in-process compiler would take care of the deps tracking
engine.SetGlobalProperty ("UseHostCompilerIfAvailable", "false");
consoleLogger = new ConsoleLogger (LoggerVerbosity.Normal, LogWriteLine, null, null);
engine.RegisterLogger (consoleLogger);
});
Refresh ();
}
示例8: BuildProject
public static BuildResult BuildProject(string projectPath, string configuration, string[] targets, Dictionary<string, string> properties, string toolsVersion)
{
if (!File.Exists(projectPath))
{
throw new ArgumentException("Project path " + projectPath + " did not exist.");
}
if (string.IsNullOrEmpty(toolsVersion))
toolsVersion = "4.0";
if (properties == null)
properties = new Dictionary<string, string>();
if (!properties.ContainsKey("Configuration") && !string.IsNullOrWhiteSpace(configuration))
properties.Add("Configuration", configuration);
if (targets == null)
{
var doc = new XmlDocument();
doc.LoadXml(File.ReadAllText(projectPath));
XmlNode defaultTargets = doc.SelectSingleNode("/Project[@DefaultTargets]");
if (defaultTargets != null) targets = defaultTargets.Value.Split(';');
}
var logger = new MsBuildCollectionLogger();
var buildRequest = new BuildRequestData(projectPath, properties, toolsVersion, targets, null);
var projects = new ProjectCollection();
projects.RegisterLogger(logger);
var parameters = new BuildParameters(projects);
parameters.Loggers = projects.Loggers;
Debug.Assert(targets != null, "dsfsdsf");
logger.AddMessage(new Message(string.Format("Building {0} ({1}), {2} targets using {3} tools", projectPath, configuration, string.Join(", ", targets), toolsVersion), MessageType.Info));
var result = BuildManager.DefaultBuildManager.Build(parameters, buildRequest);
return new BuildResult(logger.Messages, result.OverallResult == BuildResultCode.Success);
}
示例9: BuildProjectWithProperties
protected bool BuildProjectWithProperties(string projectFilepath,Dictionary<string,string>globalProperties) {
try {
var logmsg = new StringBuilder();
logmsg.AppendLine(string.Format(@"Building the project [{0}] with the following properties.", projectFilepath));
foreach (var key in globalProperties.Keys) {
logmsg.AppendLine(string.Format(@" ['{0}'='{1}']", key, globalProperties[key]));
}
System.Diagnostics.Trace.TraceInformation(logmsg.ToString());
var pc = new ProjectCollection(globalProperties);
var logger = new InmemoryMsbuildLogger();
logger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Detailed;
pc.RegisterLogger(logger);
var project = pc.LoadProject(projectFilepath);
var projectInstance = project.CreateProjectInstance();
string[] targets = new string[] { "BuildStandAlone" };
var buildReqData = new BuildRequestData(projectInstance, targets, null, BuildRequestDataFlags.ProvideProjectStateAfterBuild);
var buildResult = BuildManager.DefaultBuildManager.Build(
new BuildParameters(pc),
buildReqData);
// TODO: the log does not have much data
string log = logger.GetLog();
return (buildResult.OverallResult == BuildResultCode.Success);
}
catch (Exception ex) {
string message = string.Format("Unable to build templates from folder", ex.ToString());
System.Windows.MessageBox.Show(message);
throw ex;
}
}
示例10: CreateAndBuildProjectForImportFromExtensionsPath
void CreateAndBuildProjectForImportFromExtensionsPath(string mainProjectPath, string extnPathPropertyName, string[] extnDirs, Action<string[]> setExtensionsPath,
Action<Project, MockLogger> action)
{
try {
var projColln = new ProjectCollection();
projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader(extnPathPropertyName, extnDirs));
var logger = new MockLogger();
projColln.RegisterLogger(logger);
var project = projColln.LoadProject(mainProjectPath);
action(project, logger);
} finally {
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDirs != null)
{
foreach (var extnDir in extnDirs)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir, recursive: true);
}
}
}
}
示例11: BuildParameterLoggersExplicitlyRequired
public void BuildParameterLoggersExplicitlyRequired ()
{
string project_xml = @"<Project DefaultTargets='Foo' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' />
<Target Name='Foo'>
<ItemGroup>
<Foo Condition='$(X)' Include='foo.txt' />
</ItemGroup>
</Target>
</Project>";
var xml = XmlReader.Create (new StringReader (project_xml));
var root = ProjectRootElement.Create (xml);
root.FullPath = "BuildSubmissionTest.BuildParameterLoggersExplicitlyRequired.proj";
var pc = new ProjectCollection ();
var sw = new StringWriter ();
pc.RegisterLogger (new ConsoleLogger (LoggerVerbosity.Diagnostic, sw.WriteLine, null, null));
var proj = new ProjectInstance (root);
var bm = new BuildManager ();
var bp = new BuildParameters (pc);
var br = new BuildRequestData (proj, new string [] {"Foo"});
Assert.AreEqual (BuildResultCode.Failure, bm.Build (bp, br).OverallResult, "#1");
// the logger is *ignored*
Assert.IsFalse (sw.ToString ().Contains ("$(X)"), "#2");
}
示例12: Execute
public void Execute ()
{
bool result = false;
bool show_stacktrace = false;
try {
parameters.ParseArguments (args);
show_stacktrace = (parameters.LoggerVerbosity == LoggerVerbosity.Detailed ||
parameters.LoggerVerbosity == LoggerVerbosity.Diagnostic);
if (!parameters.NoLogo)
ErrorUtilities.ShowVersion (false);
project_collection = new ProjectCollection ();
if (!String.IsNullOrEmpty (parameters.ToolsVersion)) {
if (project_collection.GetToolset (parameters.ToolsVersion) == null)
ErrorUtilities.ReportError (0, new InvalidToolsetDefinitionException ("Toolset " + parameters.ToolsVersion + " was not found").Message);
project_collection.DefaultToolsVersion = parameters.ToolsVersion;
}
foreach (var p in parameters.Properties)
project_collection.GlobalProperties.Add (p.Key, p.Value);
if (!parameters.NoConsoleLogger) {
printer = new ConsoleReportPrinter ();
ConsoleLogger cl = new ConsoleLogger (parameters.LoggerVerbosity,
printer.Print, printer.SetForeground, printer.ResetColor);
cl.Parameters = parameters.ConsoleLoggerParameters;
cl.Verbosity = parameters.LoggerVerbosity;
project_collection.RegisterLogger (cl);
}
if (parameters.FileLoggerParameters != null) {
for (int i = 0; i < parameters.FileLoggerParameters.Length; i ++) {
string fl_params = parameters.FileLoggerParameters [i];
if (fl_params == null)
continue;
var fl = new FileLogger ();
if (fl_params.Length == 0 && i > 0)
fl.Parameters = String.Format ("LogFile=msbuild{0}.log", i);
else
fl.Parameters = fl_params;
project_collection.RegisterLogger (fl);
}
}
foreach (LoggerInfo li in parameters.Loggers) {
Assembly assembly;
if (li.InfoType == LoadInfoType.AssemblyFilename)
assembly = Assembly.LoadFrom (li.Filename);
else
assembly = Assembly.Load (li.AssemblyName);
ILogger logger = (ILogger)Activator.CreateInstance (assembly.GetType (li.ClassName));
logger.Parameters = li.Parameters;
project_collection.RegisterLogger (logger);
}
string projectFile = parameters.ProjectFile;
if (!File.Exists (projectFile)) {
ErrorUtilities.ReportError (0, String.Format ("Project file '{0}' not found.", projectFile));
return;
}
XmlReaderSettings settings = new XmlReaderSettings ();
if (parameters.Validate) {
settings.ValidationType = ValidationType.Schema;
if (parameters.ValidationSchema == null)
using (var xsdxml = XmlReader.Create (defaultSchema))
settings.Schemas.Add (XmlSchema.Read (xsdxml, null));
else
using (var xsdxml = XmlReader.Create (parameters.ValidationSchema))
settings.Schemas.Add (XmlSchema.Read (xsdxml, null));
}
var projectInstances = new List<ProjectInstance> ();
if (string.Equals (Path.GetExtension (projectFile), ".sln", StringComparison.OrdinalIgnoreCase)) {
var parser = new SolutionParser ();
var root = ProjectRootElement.Create (project_collection);
root.FullPath = projectFile;
parser.ParseSolution (projectFile, project_collection, root, LogWarning);
projectInstances.Add (new Project (root, parameters.Properties, parameters.ToolsVersion, project_collection).CreateProjectInstance ());
} else {
project = ProjectRootElement.Create (XmlReader.Create (projectFile, settings), project_collection);
project.FullPath = projectFile;
var pi = new ProjectInstance (project, parameters.Properties, parameters.ToolsVersion, project_collection);
projectInstances.Add (pi);
}
foreach (var projectInstance in projectInstances) {
var targets = parameters.Targets.Length > 0 ? parameters.Targets : projectInstance.DefaultTargets.ToArray ();
result = projectInstance.Build (targets, parameters.Loggers.Count > 0 ? parameters.Loggers : project_collection.Loggers);
if (!result)
break;
}
}
catch (InvalidProjectFileException ipfe) {
ErrorUtilities.ReportError (0, show_stacktrace ? ipfe.ToString () : ipfe.Message);
//.........这里部分代码省略.........
示例13: ProjectInstanceBuildLoggersExplicitlyRequired
public void ProjectInstanceBuildLoggersExplicitlyRequired ()
{
string project_xml = @"<Project DefaultTargets='Foo' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' />
<Target Name='Foo'>
<ItemGroup>
<Foo Condition='$(X)' Include='foo.txt' />
</ItemGroup>
</Target>
</Project>";
var xml = XmlReader.Create (new StringReader (project_xml));
var root = ProjectRootElement.Create (xml);
root.FullPath = "BuildSubmissionTest.TaskOutputsToLoggers.proj";
var pc = new ProjectCollection ();
var sw = new StringWriter ();
pc.RegisterLogger (new ConsoleLogger (LoggerVerbosity.Diagnostic, sw.WriteLine, null, null));
var proj = new ProjectInstance (root);
Assert.IsFalse (proj.Build (), "#1");
// the logger is *ignored* again
Assert.IsFalse (sw.ToString ().Contains ("$(X)"), "#2");
}
示例14: ImportFromExtensionsPathSearchOrder2
public void ImportFromExtensionsPathSearchOrder2()
{
string extnTargetsFileContent1 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FromFirstFile</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>
";
string extnTargetsFileContent2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FromSecondFile</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>
";
// File with the same name available in two different extension paths, but the one from the first
// directory in MSBuildExtensionsPath environment variable should get loaded
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1);
string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"), extnTargetsFileContent2);
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
// MSBuildExtensionsPath* property value has highest priority for the lookups
try {
var projColln = new ProjectCollection();
projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", Path.Combine("tmp", "non-existstant"), extnDir1));
var logger = new MockLogger();
projColln.RegisterLogger(logger);
var project = projColln.LoadProject(mainProjectPath);
project.SetProperty("MSBuildExtensionsPath", extnDir2);
project.ReevaluateIfNecessary();
Assert.True(project.Build());
logger.AssertLogContains("Running FromExtn");
logger.AssertLogContains("PropertyFromExtn1: FromSecondFile");
} finally {
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
if (extnDir2 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true);
}
}
}
示例15: ImportFromExtensionsPathAnd32And64
public void ImportFromExtensionsPathAnd32And64()
{
string extnTargetsFileContentTemplate = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn{0}' DependsOnTargets='{1}'>
<Message Text='Running FromExtn{0}'/>
</Target>
{2}
</Project>
";
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""14.1"">
<toolset toolsVersion=""14.1"">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value=""" + /*v4Folder*/"." + @"""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""MSBuildExtensionsPath"" value=""{0}"" />
<property name=""MSBuildExtensionsPath32"" value=""{1}"" />
<property name=""MSBuildExtensionsPath64"" value=""{2}"" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
string extnDir1 = null, extnDir2 = null, extnDir3 = null;
string mainProjectPath = null;
try {
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
String.Format(extnTargetsFileContentTemplate, String.Empty, "FromExtn2", "<Import Project='$(MSBuildExtensionsPath32)\\bar\\extn2.proj' />"));
extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("bar", "extn2.proj"),
String.Format(extnTargetsFileContentTemplate, 2, "FromExtn3", "<Import Project='$(MSBuildExtensionsPath64)\\xyz\\extn3.proj' />"));
extnDir3 = GetNewExtensionsPathAndCreateFile("extensions3", Path.Combine("xyz", "extn3.proj"),
String.Format(extnTargetsFileContentTemplate, 3, String.Empty, String.Empty));
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
var configFilePath = ToolsetConfigurationReaderTestHelper.WriteConfigFile(String.Format(configFileContents, extnDir1, extnDir2, extnDir3));
var reader = GetStandardConfigurationReader();
var projColln = new ProjectCollection();
projColln.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projColln.RegisterLogger(logger);
var project = projColln.LoadProject(mainProjectPath);
Assert.True(project.Build("Main"));
logger.AssertLogContains("Running FromExtn3");
logger.AssertLogContains("Running FromExtn2");
logger.AssertLogContains("Running FromExtn");
} finally {
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
if (extnDir2 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true);
}
if (extnDir3 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir3, recursive: true);
}
}
}