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; } }
public static bool Compile(Project project, string logfile, Log log) { try { if (project != null) { var doLog = false; var logErrorFile = Path.Combine(Directories.LogsDir, ("Error - " + Path.GetFileName(logfile))); if (File.Exists(logErrorFile)) { File.Delete(logErrorFile); } if (!string.IsNullOrWhiteSpace(logfile)) { var logDir = Path.GetDirectoryName(logfile); if (!string.IsNullOrWhiteSpace(logDir)) { doLog = true; if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir); } var fileLogger = new FileLogger { Parameters = @"logfile=" + logfile, ShowSummary = true }; ProjectCollection.GlobalProjectCollection.RegisterLogger(fileLogger); } } var result = project.Build(); ProjectCollection.GlobalProjectCollection.UnregisterAllLoggers(); ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); Utility.Log( result ? LogStatus.Ok : LogStatus.Error, "Compiler", result ? string.Format("Compile - {0}", project.FullPath) : string.Format("Compile - Check ./logs/ for details - {0}", project.FullPath), log); if (!result && doLog && File.Exists(logfile)) { var pathDir = Path.GetDirectoryName(logfile); if (!string.IsNullOrWhiteSpace(pathDir)) { File.Move( logfile, Path.Combine(Directories.LogsDir, ("Error - " + Path.GetFileName(logfile)))); } } else if (result && File.Exists(logfile)) { File.Delete(logfile); } return result; } } catch (Exception ex) { Utility.Log(LogStatus.Error, "Compiler", ex.Message, log); } return false; }
/// <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); }
public void Basic() { FileLogger fileLogger = new FileLogger(); string logFile = FileUtilities.GetTemporaryFile(); fileLogger.Parameters = "verbosity=Normal;logfile=" + logFile; Project project = ObjectModelHelpers.CreateInMemoryProject(@" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`Build`> <Message Text=`Hello world from the FileLogger`/> </Target> </Project> "); project.Build(fileLogger); project.ProjectCollection.UnregisterAllLoggers(); string log = File.ReadAllText(logFile); Assert.True(log.Contains("Hello world from the FileLogger")); // "Log should have contained message" File.Delete(logFile); }
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); } catch (InternalLoggerException ile) { ErrorUtilities.ReportError (0, show_stacktrace ? ile.ToString () : ile.Message); } catch (CommandLineException cle) { ErrorUtilities.ReportError(cle.ErrorCode, show_stacktrace ? cle.ToString() : cle.Message); } finally { //if (project_collection != null) // project_collection.UnregisterAllLoggers (); Environment.Exit (result ? 0 : 1); } }
string build(string project) { var pathPubFile = Path.Combine(Config.Builds, project, Config.PubFile); var fileContent = File.ReadAllText(pathPubFile); fileContent = fileContent.Replace("{0}", Path.Combine(Config.Builds, project, Config.Pub)); File.WriteAllText(pathPubFile, fileContent); var props = new Dictionary<string, string>(); props.Add("DeployOnBuild", "true"); props.Add("PublishProfile", pathPubFile); var request = new BuildRequestData(Path.Combine(Config.Builds, project, project, Config.ProjectFile), props, null, new string[] { "Build" }, null); var parms = new BuildParameters(); var pathLogFile = Path.Combine(Config.Builds, project, Config.BuildLog); FileLogger logger = new FileLogger() { Parameters = "logfile=" + pathLogFile }; parms.Loggers = new List<ILogger> { logger }.AsEnumerable(); var result = BuildManager.DefaultBuildManager.Build(parms, request); return result.OverallResult.ToString(); }
/// <summary> /// Compiling the workflow xamls into the assembly. /// </summary> internal void Compile(List<string> dependentWorkflows, Dictionary<string, string> requiredAssemblies) { if (IsRunningOnProcessorArchitectureARM()) { Tracer.WriteMessage("The workflow Calling workflow is not supported so throwing the exception."); throw new NotSupportedException(Resources.WFCallingWFNotSupported); } // Note that the _NOT_ARMBUILD_ flag is not a global build flag and needs to be set in the corresponding sources.inc file as appropriate. #if _NOTARMBUILD_ DirectoryInfo folder = new DirectoryInfo(this.ProjectFolderPath); folder.Create(); List<string> workflowFiles = new List<string>(); try { // Dump the files foreach (string dependentWorkflow in dependentWorkflows) { string newFileName = Path.Combine(this.ProjectFolderPath, Path.GetRandomFileName() + ".xaml"); File.WriteAllText(newFileName, dependentWorkflow); workflowFiles.Add(newFileName); } File.WriteAllText(this.ProjectFilePath, Template_Project); } catch (Exception e) { Tracer.TraceException(e); throw; } using (ProjectCollection projects = new ProjectCollection()) { Project project = projects.LoadProject(this.ProjectFilePath); project.SetProperty("AssemblyName", this.AssemblyName); HashSet<string> Assemblies = new HashSet<string>(); foreach (string file in workflowFiles) { project.AddItem("XamlAppDef", file); XamlXmlReader reader = new XamlXmlReader(XmlReader.Create(file), new XamlSchemaContext()); using (reader) { while (reader.Read()) { if (reader.NodeType == XamlNodeType.NamespaceDeclaration) { string _namespace = reader.Namespace.Namespace.ToLowerInvariant(); if (_namespace.IndexOf("assembly=", StringComparison.OrdinalIgnoreCase) > -1) { List<string> filters = new List<string>(); filters.Add("assembly="); string[] results = _namespace.Split(filters.ToArray(), StringSplitOptions.RemoveEmptyEntries); if (results.Length > 1 && !string.IsNullOrEmpty(results[1])) { string requiredAssemblyLocation; if (requiredAssemblies != null && requiredAssemblies.Count > 0 && requiredAssemblies.TryGetValue(results[1], out requiredAssemblyLocation)) { Assemblies.Add(requiredAssemblyLocation); } else { Assemblies.Add(results[1]); } } } } } } } foreach (string assembly in Assemblies) { project.AddItem("Reference", assembly); } project.Save(this.ProjectFilePath); FileLogger logger = new FileLogger(); logger.Parameters = "logfile=" + this.BuildLogPath; this.BuildReturnedCode = false; // According to MSDN, http://msdn.microsoft.com/en-us/library/microsoft.build.evaluation.projectcollection.aspx // multiple project collections can exist within an app domain. However, these must not build concurrently. // Therefore, we need a static lock to prevent multiple threads from accessing this call. lock (_syncObject) { this.BuildReturnedCode = project.Build(logger); } logger.Shutdown(); // If compilation succeeded, delete the project files. // if (this.BuildReturnedCode) { string generatedAssemblyPath = Path.Combine(this.ProjectFolderPath, @"obj\Release\" + this.ProjectName + ".dll"); if (File.Exists(generatedAssemblyPath)) { File.Move(generatedAssemblyPath, this.AssemblyPath); } try { System.IO.Directory.Delete(this.ProjectFolderPath, true); } catch (Exception e) { Tracer.TraceException(e); // Ignoring the exceptions from Delete of temp directory. } } } #endif }
public bool Build(IEnumerable <string> ProjectsPath, long VersionId, string OutputDirectory) { var ret = false; try { // Properties passed to MSBUID (the ones of the .target file) var globalProperties = new Dictionary <string, string>(); globalProperties.Add("CodeContractsCacheDirectory", OutputDirectory); globalProperties.Add("CodeContractsCacheAnalysisResults", "true"); globalProperties.Add("CodeContractsCacheVersion", VersionId.ToString()); globalProperties.Add("CodeContractsCacheMaxSize", Int32.MaxValue.ToString()); #if WITH_LOG // It does not work: The log file is empty var logFileName = "build." + VersionId + ".log"; var logger = new FileLogger(); logger.Parameters = "logfile=" + Path.Combine(OutputDirectory, logFileName); logger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic; var loggers = new FileLogger[] { logger }; // with this version, loggers don't work (log files are created but empty), why? #else var loggers = new FileLogger[0]; #endif 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; // 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); }
public bool Build(IEnumerable <string> ProjectsPath, string versionName, string outputPrefix) { var ret = false; try { // Properties passed to MSBUILD (the ones of the .target file) var globalProperties = new Dictionary <string, string>(); // INFERENCE off globalProperties.Add("CodeContractsInferRequires", "false"); globalProperties.Add("CodeContractsInferEnsures", "false"); globalProperties.Add("CodeContractsInferObjectInvariants", "false"); // SUGGESTIONS off globalProperties.Add("CodeContractsSuggestAssumptions", "false"); globalProperties.Add("CodeContractsSuggestRequires", "false"); globalProperties.Add("CodeContractsSuggestEnsures", "false"); globalProperties.Add("CodeContractsSuggestObjectInvariants", "false"); // WARNINGS globalProperties.Add("CodeContractsRunCodeAnalysis", "true"); globalProperties.Add("CodeContractsAnalysisWarningLevel", "3"); globalProperties.Add("CodeContractsNonNullObligations", "true"); globalProperties.Add("CodeContractsBoundsObligations", "true"); globalProperties.Add("CodeContractsArithmeticObligations", "true"); globalProperties.Add("CodeContractsEnumObligations", "true"); globalProperties.Add("CodeContractsRedundantAssumptions", "false"); globalProperties.Add("CodeContractsMissingPublicRequiresAsWarnings", "false"); globalProperties.Add("CodeContractsRunInBackground", "false"); // get output globalProperties.Add("CodeContractsEnableRuntimeChecking", "false"); // speedup globalProperties.Add("CodeContractsReferenceAssembly", "Build"); // make sure we have it //globalProperties.Add("CodeContractsUseBaseLine", "true"); //globalProperties.Add("CodeContractsBaseLineFile", "base.xml"); //globalProperties.Add("CodeContractsExtraAnalysisOptions", "-repro"); globalProperties.Add("CodeContractsCacheAnalysisResults", "true"); globalProperties.Add("CodeContractsSQLServerOption", "cloudotserver"); var extraOptions = this.ExtraOptions == null ? "" : this.ExtraOptions; extraOptions += " -sortwarns:false -stats:perMethod -show:progress -trace:cache"; if (this.SaveSemanticBaseline) { extraOptions += String.Format(" -saveSemanticBaseline:{0}", versionName); } else { extraOptions += String.Format(" -useSemanticBaseline:{0}", versionName); } globalProperties.Add("CodeContractsExtraAnalysisOptions", extraOptions); //globalProperties.Add("CodeContractsCacheVersion", VersionId.ToString()); //globalProperties.Add("CodeContractsCacheMaxSize", Int32.MaxValue.ToString()); globalProperties.Add("DeployExtension", "false"); // avoid vsix deployment // It does not work: The log file is empty var logFileName = "buildlog." + versionName + "." + outputPrefix + (this.SaveSemanticBaseline ? ".save.txt" : ".use.txt"); var fileLogger = new FileLogger(); fileLogger.Parameters = "logfile=" + Path.Combine(this.SourceDirectory, logFileName); fileLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Normal; var consoleLogger = new ConsoleLogger(); consoleLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Normal; var overallLoggers = new[] { fileLogger, consoleLogger }; // with this version, loggers don't work (log files are created but empty), why? var loggers = new FileLogger[0]; 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); }
public void InvalidVerbosity() { Assert.Throws<LoggerException>(() => { FileLogger fl = new FileLogger(); fl.Parameters = "verbosity=CookiesAndCream"; EventSourceSink es = new EventSourceSink(); fl.Initialize(es); } ); }
public void ValidVerbosities() { string[] verbositySettings = new string[] { "Q", "quiet", "m", "minimal", "N", "normal", "d", "detailed", "diag", "DIAGNOSTIC" }; LoggerVerbosity[] verbosityEnumerations = new LoggerVerbosity[] {LoggerVerbosity.Quiet, LoggerVerbosity.Quiet, LoggerVerbosity.Minimal, LoggerVerbosity.Minimal, LoggerVerbosity.Normal, LoggerVerbosity.Normal, LoggerVerbosity.Detailed, LoggerVerbosity.Detailed, LoggerVerbosity.Diagnostic, LoggerVerbosity.Diagnostic}; for (int i = 0; i < verbositySettings.Length; i++) { FileLogger fl = new FileLogger(); fl.Parameters = "verbosity=" + verbositySettings[i] + ";"; EventSourceSink es = new EventSourceSink(); fl.Initialize(es); fl.Shutdown(); Assert.Equal(fl.Verbosity, verbosityEnumerations[i]); } // Do the same using the v shorthand for (int i = 0; i < verbositySettings.Length; i++) { FileLogger fl = new FileLogger(); fl.Parameters = "v=" + verbositySettings[i] + ";"; EventSourceSink es = new EventSourceSink(); fl.Initialize(es); fl.Shutdown(); Assert.Equal(fl.Verbosity, verbosityEnumerations[i]); } }
public void BuildMyCode() { //retrieve assembly execution path string assemblyExecutionPath = System.Reflection.Assembly.GetExecutingAssembly().Location; string logFilePath = assemblyExecutionPath.Remove(assemblyExecutionPath.LastIndexOf("\\") + 1) + "build.log"; var sln = @"C:\Users\Danni\Desktop\FarExo Prototypes\BuildTester\FarExoCD.sln"; var OutputHeaderRow = new List<string>(); var OutputItemRow = new List<string>(); try { // Instantiate a new FileLogger to generate build log FileLogger logger = new FileLogger(); // Set the logfile parameter to indicate the log destination logger.Parameters = @"logfile=" + logFilePath; ProjectCollection pc = new ProjectCollection(); Dictionary<string, string> GlobalProperty = new Dictionary<string, string>(); GlobalProperty.Add("Configuration", "Release"); GlobalProperty.Add("Platform", "Any CPU"); BuildRequestData buildRequest = new BuildRequestData(sln, GlobalProperty, null, new string[] { "Build" }, null); //register file logger using BuildParameters BuildParameters bp = new BuildParameters(pc); bp.Loggers = new List<Microsoft.Build.Framework.ILogger> { logger }.AsEnumerable(); //build solution BuildResult buildResult = BuildManager.DefaultBuildManager.Build(bp, buildRequest); //Unregister all loggers to close the log file pc.UnregisterAllLoggers(); //read lines from log file having project build output details string[] solutionBuildOutputs = File.ReadAllLines(logFilePath); //write the result of solution build to html report OutputHeaderRow.Add("Artifact;Build Result"); //split the contents of logger file to retrieve project build details string[] splitter = { "__________________________________________________" }; string loggerOutput = File.ReadAllText(logFilePath); string[] projectResults = loggerOutput.Split(splitter, StringSplitOptions.None); foreach (string projectBuildDetails in projectResults) { if (projectBuildDetails.Contains("(default targets):")) { if (projectBuildDetails.Contains("Done building project \"")) { //write the result of failed projects build to html report string[] lines = projectBuildDetails.Split("\n".ToCharArray()); string buildFailedProjectName = lines.Where(x => x.Contains("Done building project \"")).FirstOrDefault(); buildFailedProjectName = buildFailedProjectName.Replace("Done building project ", string.Empty).Trim(); buildFailedProjectName = buildFailedProjectName.Replace("\"", string.Empty); buildFailedProjectName = buildFailedProjectName.Replace(" -- FAILED.", string.Empty); OutputItemRow.Add(buildFailedProjectName + ";FAILED"); } else { //write the result of successfully built projects to html report string[] lines = projectBuildDetails.Split("\n".ToCharArray()); string buildSuccededProjectName = lines.Where(x => x.Contains(" (default targets):")).FirstOrDefault().Replace("\" (default targets):", ""); string finalProjectName = buildSuccededProjectName.Substring(buildSuccededProjectName.LastIndexOf("\\") + 1); OutputItemRow.Add(finalProjectName + ";SUCCEEDED"); } } } } catch (Exception ex) { throw ex; } finally { //delete log file File.Delete(logFilePath); } }
public void InvalidVerbosity() { FileLogger fl = new FileLogger(); fl.Parameters = "verbosity=CookiesAndCream"; EventSourceSink es = new EventSourceSink(); fl.Initialize(es); }
static void Main(string[] args) { var slnInfo = new DirectoryInfo(@"C:\Users\Danni\Desktop\FarExo Prototypes\FarExoCD"); var slnFileInfo = new DirectoryInfo(@"C:\Users\Danni\Desktop\FarExo Prototypes\FarExoCD\FarExoCD.sln"); var projectFileInfo = new FileInfo(@"C:\Users\Danni\Desktop\FarExo Prototypes\FarExoCD\Instrumentation\Instrumentation.Impl\Instrumentation.Impl.csproj"); var outputDirectoryInfo = new DirectoryInfo(@"C:\Users\Danni\Desktop\FarExo Prototypes\FarExoCD\.output"); var logFileInfo = new FileInfo(Path.Combine(outputDirectoryInfo.FullName, "build.log")); var projectCollection = BuildProjectCollection(slnInfo); var globalProperties = new Dictionary<string, string>(); globalProperties.Add("Configuration", "Release"); globalProperties.Add("Platform", "AnyCPU"); globalProperties.Add("BuildInParallel", "True"); globalProperties.Add("OutputPath", outputDirectoryInfo.FullName); var fileLogger = new FileLogger(); fileLogger.Parameters = @"logfile=" + logFileInfo.FullName; var consoleLogger = new ConsoleLogger(LoggerVerbosity.Detailed); foreach (var project in projectCollection.LoadedProjects) { project.SetProperty("Configuration", globalProperties["Configuration"]); project.SetProperty("Platform", globalProperties["Platform"]); project.SetProperty("OutputPath", Path.Combine(globalProperties["OutputPath"], project.GetProperty("MsBuildProjectName").EvaluatedValue, globalProperties["Configuration"])); project.SetProperty("BuildInParallel", globalProperties["BuildInParallel"]); } var buildProject = projectCollection.LoadedProjects.Single(x => x.GetProperty("MsBuildProjectName").EvaluatedValue == "Instrumentation.Impl"); var propertyList = buildProject.Properties.Where(x => x.EvaluatedValue.Contains(@"bin\")); var buildParameters = new BuildParameters(projectCollection); buildParameters.Loggers = new List<ILogger> { consoleLogger }; if (buildParameters.Toolsets.Any(x => x.ToolsVersion == _defaultToolsVersion)) { buildParameters.DefaultToolsVersion = _defaultToolsVersion; } else { throw new Exception($"Tools version {_defaultToolsVersion} are not available."); } var buildRequest = new BuildRequestData(buildProject.CreateProjectInstance(ProjectInstanceSettings.None), new string[] { _defaultTarget }); var buildManager = new BuildManager(); BuildResult buildResult = null; try { buildManager.BeginBuild(buildParameters); buildResult = buildManager.BuildRequest(buildRequest); buildManager.EndBuild(); projectCollection.UnregisterAllLoggers(); } catch (Exception ex) { throw ex; } finally { File.Delete(logFileInfo.FullName); } }
internal void Compile(List<string> dependentWorkflows, Dictionary<string, string> requiredAssemblies) { string str = null; DirectoryInfo directoryInfo = new DirectoryInfo(this.ProjectFolderPath); directoryInfo.Create(); List<string> strs = new List<string>(); try { foreach (string dependentWorkflow in dependentWorkflows) { string str1 = Path.Combine(this.ProjectFolderPath, string.Concat(Path.GetRandomFileName(), ".xaml")); File.WriteAllText(str1, dependentWorkflow); strs.Add(str1); } File.WriteAllText(this.ProjectFilePath, "<?xml version=\"1.0\" encoding=\"utf-8\"?><Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"><PropertyGroup><Configuration Condition=\" '$(Configuration)' == '' \">Release</Configuration><Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform><ProductVersion>10.0</ProductVersion><SchemaVersion>2.0</SchemaVersion><OutputType>Library</OutputType><AppDesignerFolder>Properties</AppDesignerFolder><TargetFrameworkVersion>v4.0</TargetFrameworkVersion><TargetFrameworkProfile></TargetFrameworkProfile><FileAlignment>512</FileAlignment></PropertyGroup><PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \"><DebugSymbols>true</DebugSymbols><DebugType>full</DebugType><Optimize>false</Optimize><OutputPath>bin\\Debug\\</OutputPath><DefineConstants>DEBUG;TRACE</DefineConstants><ErrorReport>prompt</ErrorReport><WarningLevel>4</WarningLevel></PropertyGroup><PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \"><DebugType>pdbonly</DebugType><Optimize>true</Optimize><OutputPath>bin\\Release\\</OutputPath><DefineConstants>TRACE</DefineConstants><ErrorReport>prompt</ErrorReport><WarningLevel>4</WarningLevel></PropertyGroup><ItemGroup><Reference Include=\"Microsoft.CSharp\" /><Reference Include=\"System\" /><Reference Include=\"System.Activities\" /><Reference Include=\"System.Core\" /><Reference Include=\"System.Data\" /><Reference Include=\"System.ServiceModel\" /><Reference Include=\"System.ServiceModel.Activities\" /><Reference Include=\"System.Xaml\" /><Reference Include=\"System.Xml\" /><Reference Include=\"System.Xml.Linq\" /><Reference Include=\"System.Management\" /><Reference Include=\"System.Management.Automation\" /><Reference Include=\"Microsoft.PowerShell.Workflow.ServiceCore\" /></ItemGroup><Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" /><!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name=\"BeforeBuild\"></Target><Target Name=\"AfterBuild\"></Target>--></Project>"); } catch (Exception exception1) { Exception exception = exception1; WorkflowRuntimeCompilation.Tracer.TraceException(exception); throw; } using (ProjectCollection projectCollection = new ProjectCollection()) { Project project = projectCollection.LoadProject(this.ProjectFilePath); project.SetProperty("AssemblyName", this.AssemblyName); HashSet<string> strs1 = new HashSet<string>(); foreach (string str2 in strs) { project.AddItem("XamlAppDef", str2); XamlXmlReader xamlXmlReader = new XamlXmlReader(XmlReader.Create(str2), new XamlSchemaContext()); using (xamlXmlReader) { while (xamlXmlReader.Read()) { if (xamlXmlReader.NodeType != XamlNodeType.NamespaceDeclaration) { continue; } string lowerInvariant = xamlXmlReader.Namespace.Namespace.ToLowerInvariant(); if (lowerInvariant.IndexOf("assembly=", StringComparison.OrdinalIgnoreCase) <= -1) { continue; } List<string> strs2 = new List<string>(); strs2.Add("assembly="); string[] strArrays = lowerInvariant.Split(strs2.ToArray(), StringSplitOptions.RemoveEmptyEntries); if ((int)strArrays.Length <= 1 || string.IsNullOrEmpty(strArrays[1])) { continue; } if (requiredAssemblies == null || requiredAssemblies.Count <= 0 || !requiredAssemblies.TryGetValue(strArrays[1], out str)) { strs1.Add(strArrays[1]); } else { strs1.Add(str); } } } } foreach (string str3 in strs1) { project.AddItem("Reference", str3); } project.Save(this.ProjectFilePath); FileLogger fileLogger = new FileLogger(); fileLogger.Parameters = string.Concat("logfile=", this.BuildLogPath); this.BuildReturnedCode = false; lock (WorkflowRuntimeCompilation._syncObject) { this.BuildReturnedCode = project.Build(fileLogger); } fileLogger.Shutdown(); if (this.BuildReturnedCode) { string str4 = Path.Combine(this.ProjectFolderPath, string.Concat("obj\\Release\\", this.ProjectName, ".dll")); if (File.Exists(str4)) { File.Move(str4, this.AssemblyPath); } try { Directory.Delete(this.ProjectFolderPath, true); } catch (Exception exception3) { Exception exception2 = exception3; WorkflowRuntimeCompilation.Tracer.TraceException(exception2); } } } }
public void InvalidEncoding() { Assert.Throws<LoggerException>(() => { string log = null; try { log = GetTempFilename(); FileLogger fl = new FileLogger(); EventSourceSink es = new EventSourceSink(); fl.Parameters = "encoding=foo;logfile=" + log; fl.Initialize(es); } finally { if (null != log) File.Delete(log); } } ); }
public bool Build(IEnumerable<string> ProjectsPath, long VersionId, string OutputDirectory) { var ret = false; try { // Properties passed to MSBUID (the ones of the .target file) var globalProperties = new Dictionary<string, string>(); globalProperties.Add("CodeContractsCacheDirectory", OutputDirectory); globalProperties.Add("CodeContractsCacheAnalysisResults", "true"); globalProperties.Add("CodeContractsCacheVersion", VersionId.ToString()); globalProperties.Add("CodeContractsCacheMaxSize", Int32.MaxValue.ToString()); #if WITH_LOG // It does not work: The log file is empty var logFileName = "build." + VersionId + ".log"; var logger = new FileLogger(); logger.Parameters = "logfile=" + Path.Combine(OutputDirectory, logFileName); logger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic; var loggers = new FileLogger[]{ logger }; // with this version, loggers don't work (log files are created but empty), why? #else var loggers = new FileLogger[0]; #endif 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; // 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; }
/// <summary> /// Build a Visual Studio web project and generate a WebDeploy package. /// </summary> /// <param name="projectFile">The project file.</param> /// <param name="configuration">The configuration of the build, like Release or Debug.</param> /// <param name="logFile">The build log file if there is any error.</param> /// <returns>The full path of the generated WebDeploy package.</returns> public string BuildWebProject(string projectFile, string configuration, string logFile) { ProjectCollection pc = new ProjectCollection(); Project project = pc.LoadProject(projectFile); // Use a file logger to store detailed build info. FileLogger fileLogger = new FileLogger(); fileLogger.Parameters = string.Format("logfile={0}", logFile); fileLogger.Verbosity = LoggerVerbosity.Diagnostic; // Set the configuration used by MSBuild. project.SetProperty("Configuration", configuration); // Set this property use "managedRuntimeVersion=v4.0". // Otherwise, WebDeploy will fail becasue Azure Web Site is expecting v4.0. project.SetProperty("VisualStudioVersion", "11.0"); // Build the project. var buildSucceed = project.Build("Package", new ILogger[] { fileLogger }); if (buildSucceed) { // If build succeeds, delete the build.log file since there is no use of it. File.Delete(logFile); return Path.Combine(Path.GetDirectoryName(projectFile), "obj", configuration, "Package", Path.GetFileNameWithoutExtension(projectFile) + ".zip"); } else { // If build fails, tell the user to look at the build.log file. throw new Exception(string.Format(Resources.WebProjectBuildFailTemplate, logFile)); } }
public void Initialize(IEventSource eventSource) { ErrorUtilities.VerifyThrowArgumentNull(eventSource, "eventSource"); ParseFileLoggerParameters(); string fileName = _logFile; try { // Create a new file logger and pass it some parameters to make the build log very detailed _nodeFileLogger = new FileLogger(); string extension = Path.GetExtension(_logFile); // If there is no extension add a default of .log to it if (String.IsNullOrEmpty(extension)) { _logFile += ".log"; extension = ".log"; } // Log 0-based node id's, where 0 is the parent. This is a little unnatural for the reader, // but avoids confusion by being consistent with the Engine and any error messages it may produce. fileName = _logFile.Replace(extension, _nodeId + extension); _nodeFileLogger.Verbosity = LoggerVerbosity.Detailed; _nodeFileLogger.Parameters = "ShowEventId;ShowCommandLine;logfile=" + fileName + ";" + _parameters; } catch (ArgumentException e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (_nodeFileLogger != null) { _nodeFileLogger.Shutdown(); } string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "InvalidFileLoggerFile", fileName, e.Message); throw new LoggerException(message, e, errorCode, helpKeyword); } // Say we are operating on 2 processors so we can get the multiproc output _nodeFileLogger.Initialize(eventSource, 2); }
public bool Build(IEnumerable<string> ProjectsPath, string versionName, string outputPrefix) { var ret = false; try { // Properties passed to MSBUILD (the ones of the .target file) var globalProperties = new Dictionary<string, string>(); // INFERENCE off globalProperties.Add("CodeContractsInferRequires", "false"); globalProperties.Add("CodeContractsInferEnsures", "false"); globalProperties.Add("CodeContractsInferObjectInvariants", "false"); // SUGGESTIONS off globalProperties.Add("CodeContractsSuggestAssumptions", "false"); globalProperties.Add("CodeContractsSuggestRequires", "false"); globalProperties.Add("CodeContractsSuggestEnsures", "false"); globalProperties.Add("CodeContractsSuggestObjectInvariants", "false"); // WARNINGS globalProperties.Add("CodeContractsRunCodeAnalysis", "true"); globalProperties.Add("CodeContractsAnalysisWarningLevel", "3"); globalProperties.Add("CodeContractsNonNullObligations", "true"); globalProperties.Add("CodeContractsBoundsObligations", "true"); globalProperties.Add("CodeContractsArithmeticObligations", "true"); globalProperties.Add("CodeContractsEnumObligations", "true"); globalProperties.Add("CodeContractsRedundantAssumptions", "false"); globalProperties.Add("CodeContractsMissingPublicRequiresAsWarnings", "false"); globalProperties.Add("CodeContractsRunInBackground", "false"); // get output globalProperties.Add("CodeContractsEnableRuntimeChecking", "false"); // speedup globalProperties.Add("CodeContractsReferenceAssembly", "Build"); // make sure we have it //globalProperties.Add("CodeContractsUseBaseLine", "true"); //globalProperties.Add("CodeContractsBaseLineFile", "base.xml"); //globalProperties.Add("CodeContractsExtraAnalysisOptions", "-repro"); globalProperties.Add("CodeContractsCacheAnalysisResults", "true"); globalProperties.Add("CodeContractsSQLServerOption", "cloudotserver"); var extraOptions = this.ExtraOptions == null ? "" : this.ExtraOptions; extraOptions += " -sortwarns:false -stats:perMethod -show:progress -trace:cache"; if (this.SaveSemanticBaseline) { extraOptions += String.Format(" -saveSemanticBaseline:{0}", versionName); } else { extraOptions += String.Format(" -useSemanticBaseline:{0}", versionName); } globalProperties.Add("CodeContractsExtraAnalysisOptions", extraOptions); //globalProperties.Add("CodeContractsCacheVersion", VersionId.ToString()); //globalProperties.Add("CodeContractsCacheMaxSize", Int32.MaxValue.ToString()); globalProperties.Add("DeployExtension", "false"); // avoid vsix deployment // It does not work: The log file is empty var logFileName = "buildlog." + versionName + "." + outputPrefix + (this.SaveSemanticBaseline ? ".save.txt" : ".use.txt"); var fileLogger = new FileLogger(); fileLogger.Parameters = "logfile=" + Path.Combine(this.SourceDirectory, logFileName); fileLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Normal; var consoleLogger = new ConsoleLogger(); consoleLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Normal; var overallLoggers = new[] { fileLogger, consoleLogger }; // with this version, loggers don't work (log files are created but empty), why? var loggers = new FileLogger[0]; 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; }
/// <summary> /// Creates a FileLogger, sets its parameters and initializes it, /// logs a message to it, and calls shutdown /// </summary> /// <param name="parameters"></param> /// <returns></returns> private void SetUpFileLoggerAndLogMessage(string parameters, BuildMessageEventArgs message) { FileLogger fl = new FileLogger(); EventSourceSink es = new EventSourceSink(); fl.Parameters = parameters; fl.Initialize(es); fl.MessageHandler(null, message); fl.Shutdown(); return; }
public void SpecificVerbosity() { string log = null; try { log = GetTempFilename(); FileLogger fl = new FileLogger(); EventSourceSink es = new EventSourceSink(); fl.Parameters = "verbosity=diagnostic;logfile=" + log; // diagnostic specific setting fl.Verbosity = LoggerVerbosity.Quiet; // quiet global setting fl.Initialize(es); fl.MessageHandler(null, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); fl.Shutdown(); // expect message to appear because diagnostic not quiet verbosity was used VerifyFileContent(log, "message here"); } finally { if (null != log) File.Delete(log); } }