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 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); } } }
/// <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; }
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); } } }
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); }
/// <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 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 (); }
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); }
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; } }
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); } } } }
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"); }
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); } }
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"); }
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); } } }
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); } } }
private static bool Build(string projectFilePath, IDictionary<string, string> buildProperties, LoggerVerbosity verbosity, string logPath = null) { var workspace = new FileInfo(projectFilePath).Directory; if (workspace == null) throw new DirectoryNotFoundException( "Somehow the project file is not in a directory. Report this to Icedream!"); // Mono compatibility Environment.SetEnvironmentVariable("MONO_IOMAP", "all"); // Make sure we restore nuget packages automatically and without permissions interfering with /tmp/nuget/ (edge case) var newTempDir = workspace.CreateSubdirectory(".tmp"); Environment.SetEnvironmentVariable("EnableNuGetPackageRestore", "true"); Environment.SetEnvironmentVariable("TEMP", newTempDir.FullName); Environment.SetEnvironmentVariable("TMP", newTempDir.FullName); try { var pc = new ProjectCollection(); pc.RegisterLogger(new ConsoleLogger(verbosity)); var loggers = new List<ILogger>(); if (logPath != null) loggers.Add(new FileLogger { Parameters = string.Format("LogFile={0}", logPath), Verbosity = LoggerVerbosity.Detailed, ShowSummary = true, SkipProjectStartedText = true }); loggers.Add(new ConsoleLogger(verbosity) {ShowSummary = false}); // Import/Update Mozilla certs for NuGet to not fail out on non-Windows machines if (!Environment.OSVersion.IsWin32()) { try { var automaticYesResponder = new Action<string, StreamWriter>((s, writer) => { if (s == null || !s.Contains("X.509 Certificate")) return; writer.WriteLine("yes"); }); // TODO: Make sure this does not fail out by checking if mozroots is installed Console.WriteLine("Updating SSL certificates for NuGet..."); RunProcessThrowOnException("mozroots", "--import --sync --quiet"); RunProcessThrowOnException("certmgr", "-ssl https://go.microsoft.com", lineProcessor: automaticYesResponder); RunProcessThrowOnException("certmgr", "-ssl https://nugetgallery.blob.core.windows.net", lineProcessor: automaticYesResponder); RunProcessThrowOnException("certmgr", "-ssl https://nuget.org", lineProcessor: automaticYesResponder); } catch (Exception error) { Console.Error.WriteLine("ERROR: {0}", error.Message); throw; } } { // The NuGet.exe that is shipped with CitizenMP.Server has a few bugs... var nugetExePath = Path.Combine(workspace.FullName, ".nuget", "NuGet.exe"); Console.WriteLine("Updating NuGet..."); File.Delete(nugetExePath); using (var wc = new WebClient()) { wc.DownloadFile("https://nuget.org/NuGet.exe", nugetExePath); } } // Use a different build route if running on the Mono interpreter if (!Environment.OSVersion.IsWin32()) { Console.WriteLine("Building server binaries..."); #pragma warning disable 618 // Build doesn't work with the new API on Mono, use the deprecated api var engine = Engine.GlobalEngine; // loggers foreach (var logger in loggers) engine.RegisterLogger(logger); // Apply build properties var buildPropertiesConverted = new BuildPropertyGroup(); engine.GlobalProperties = buildPropertiesConverted; foreach (var property in buildProperties) buildPropertiesConverted.SetProperty(property.Key, property.Value); // Load project var result = engine.BuildProjectFile(projectFilePath, new string[0], null, null, BuildSettings.None, null); #pragma warning restore 618 return result; } // Windows build can make use of the new API which is more efficient { Console.WriteLine("Building server binaries..."); var buildReq = new BuildRequestData(projectFilePath, buildProperties, null, new[] {"Build"}, null); var result = BuildManager.DefaultBuildManager.Build( new BuildParameters(pc) { Loggers = loggers.ToArray(), MaxNodeCount = Environment.ProcessorCount }, buildReq); return result.OverallResult == BuildResultCode.Success; } } finally { newTempDir.Delete(true); } }
public void FallbackImportWithUndefinedProperty() { string mainTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Import Project='$(UndefinedProperty)\file.props' Condition=""Exists('$(UndefinedProperty)\file.props')"" /> <Target Name='Main' DependsOnTargets='FromExtn' /> </Project>"; string extnTargetsFileContentTemplate = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> </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="".""/> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""UndefinedProperty"" value=""$(FallbackExpandDir1)"" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"; string extnDir1 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("file.props"), extnTargetsFileContentTemplate); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent); ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents); var reader = GetStandardConfigurationReader(); var projectCollection = new ProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 }); projectCollection.ResetToolsetsForTests(reader); var logger = new MockLogger(); projectCollection.RegisterLogger(logger); var project = projectCollection.LoadProject(mainProjectPath); Assert.True(project.Build("Main")); logger.AssertLogContains("Running FromExtn"); } finally { FileUtilities.DeleteNoThrow(mainProjectPath); FileUtilities.DeleteDirectoryNoThrow(extnDir1, true); } }
public void ExpandExtensionsPathFallbackInErrorMessage() { string extnTargetsFileContentTemplate = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> <Import Project='$(MSBuildExtensionsPath)\\foo\\extn2.proj' Condition=""Exists('$(MSBuildExtensionsPath)\foo\extn.proj')"" /> </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="".""/> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"; string extnDir1 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContentTemplate); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents); var reader = GetStandardConfigurationReader(); var projectCollection = new ProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 }); projectCollection.ResetToolsetsForTests(reader); var logger = new MockLogger(); projectCollection.RegisterLogger(logger); Assert.Throws<InvalidProjectFileException>(() => projectCollection.LoadProject(mainProjectPath)); // Expanded $(FallbackExpandDir) will appear in quotes in the log logger.AssertLogContains("\"" + extnDir1 + "\""); } finally { FileUtilities.DeleteNoThrow(mainProjectPath); FileUtilities.DeleteDirectoryNoThrow(extnDir1, true); } }
public void LogWithLoggersOnProjectCollection() { MockLogger mockLogger = new MockLogger(); string projectFileContent = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace'> <Target Name=""BUild""> <Message Text=""IHaveBeenLogged"" Importance=""High""/> </Target> </Project>"); ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent))); ProjectCollection collection = new ProjectCollection(); collection.RegisterLogger(mockLogger); Project project = new Project(xml, null, null, collection); bool result = project.Build(); Assert.Equal(true, result); mockLogger.AssertLogContains("IHaveBeenLogged"); }
public void ProjectCollectionChangedEvent() { ProjectCollection collection = new ProjectCollection(); bool dirtyRaised = false; ProjectCollectionChangedState expectedChange = ProjectCollectionChangedState.Loggers; collection.ProjectCollectionChanged += (sender, e) => { Assert.Same(collection, sender); Assert.Equal(expectedChange, e.Changed); dirtyRaised = true; }; Assert.False(dirtyRaised); expectedChange = ProjectCollectionChangedState.DisableMarkDirty; dirtyRaised = false; collection.DisableMarkDirty = true; // LEAVE THIS TRUE for rest of the test, to verify it doesn't suppress these events Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.IsBuildEnabled; dirtyRaised = false; collection.IsBuildEnabled = !collection.IsBuildEnabled; Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.OnlyLogCriticalEvents; dirtyRaised = false; collection.OnlyLogCriticalEvents = !collection.OnlyLogCriticalEvents; Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.SkipEvaluation; dirtyRaised = false; collection.SkipEvaluation = !collection.SkipEvaluation; Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.GlobalProperties; dirtyRaised = false; collection.SetGlobalProperty("a", "b"); Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.GlobalProperties; dirtyRaised = false; collection.RemoveGlobalProperty("a"); Assert.True(dirtyRaised); // Verify HostServices changes raise the event. expectedChange = ProjectCollectionChangedState.HostServices; dirtyRaised = false; collection.HostServices = new Execution.HostServices(); Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.Loggers; dirtyRaised = false; collection.RegisterLogger(new MockLogger()); Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.Loggers; dirtyRaised = false; collection.RegisterLoggers(new Microsoft.Build.Framework.ILogger[] { new MockLogger(), new MockLogger() }); Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.Loggers; dirtyRaised = false; collection.UnregisterAllLoggers(); Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.Toolsets; dirtyRaised = false; collection.AddToolset(new Toolset("testTools", Path.GetTempPath(), collection, Path.GetTempPath())); Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.DefaultToolsVersion; dirtyRaised = false; collection.DefaultToolsVersion = "testTools"; Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.Toolsets; dirtyRaised = false; collection.RemoveToolset("testTools"); Assert.True(dirtyRaised); expectedChange = ProjectCollectionChangedState.Toolsets; dirtyRaised = false; collection.RemoveAllToolsets(); Assert.True(dirtyRaised); }
public void ImportSelfIgnored() { string file = null; try { ProjectCollection collection = new ProjectCollection(); MockLogger logger = new MockLogger(); collection.RegisterLogger(logger); Project project = new Project(collection); project.Xml.AddImport("$(MSBuildProjectFullPath)"); file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); project.Save(file); project.ReevaluateIfNecessary(); logger.AssertLogContains("MSB4210"); // selfimport } finally { File.Delete(file); } }
public void DoubleImportIndirectIgnored() { string file = null; string file2 = null; string file3 = null; try { ProjectCollection collection = new ProjectCollection(); MockLogger logger = new MockLogger(); collection.RegisterLogger(logger); file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); file2 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); file3 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); Project project = new Project(collection); project.Xml.AddImport(file2); project.Xml.AddImport(file3); project.Save(file); Project project2 = new Project(collection); project.Xml.AddImport(file3); project2.Save(file2); Project project3 = new Project(collection); project3.Save(file3); project.ReevaluateIfNecessary(); logger.AssertLogContains("MSB4011"); // duplicate import } finally { File.Delete(file); File.Delete(file2); File.Delete(file3); } }
public void Test_1() { var projectFileName = TestDirectory + @"GlueTestProject\GlueTestProject\GlueTestProject\GlueTestProject.csproj"; //Start up Glue AutoGlue.Start(); ProjectLoader.Self.LoadProject(projectFileName); //Build Project var pc = new ProjectCollection(); var fileLogger = new OutputLogger(); pc.RegisterLogger(fileLogger); var p = pc.LoadProject(projectFileName); p.SetProperty("Configuration", "UnitTests"); Assert.AreEqual(true, p.Build(), "Failed to build project."); //Run Project var proc = new Process { StartInfo = { UseShellExecute = false, FileName = TestDirectory + @"GlueTestProject\GlueTestProject\GlueTestProject\bin\x86\Debug\GlueTestProject.exe", RedirectStandardError = true } }; proc.Start(); proc.WaitForExit(); Trace.Write(proc.StandardError.ReadToEnd()); Assert.AreEqual(0, proc.ExitCode); }