private RegisterLogger ( ILogger logger ) : void | ||
logger | ILogger | |
return | void |
protected override void RegisterConsoleLogger(Engine engine, string workingPath) { engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Minimal)); // TODO: implement FileLogger in mono, reenable this var logger = new FileLogger(); logger.Parameters = String.Format(@"logfile={0}", Path.Combine(workingPath, "compile.log")); logger.Verbosity = LoggerVerbosity.Minimal; // Normal, Detailed; engine.RegisterLogger(logger); }
public BuildRunner(BuilderSetup setup) { this.setup = setup; engine = new Engine(); if (setup.LoggerType != null) { var logger = (ILogger) Activator.CreateInstance(setup.LoggerAsType); engine.RegisterLogger(logger); } engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal)); }
internal MSBuildEngineWorker(MSBuildEngine parentEngine, MSBuildEngine.BuildRun buildRun) { this.parentEngine = parentEngine; this.buildRun = buildRun; engine = buildRun.CreateEngine(); logger = new SharpDevelopLogger(this); engine.RegisterLogger(logger); foreach (IMSBuildAdditionalLogger loggerProvider in MSBuildEngine.AdditionalMSBuildLoggers) { engine.RegisterLogger(loggerProvider.CreateLogger(this)); } }
public static bool Build(Project pProj, OutputWindowPane pPane, string pTarget, NameValueCollection pParams) { Microsoft.Build.BuildEngine.Engine buildEngine = new Microsoft.Build.BuildEngine.Engine(); BuildExecutor executor = new BuildExecutor(pPane); RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework", false); if (key == null) { throw new Exception("Failed to determine .NET Framework install root - no .NETFramework key"); } string installRoot = key.GetValue("InstallRoot") as string; if (installRoot == null) { throw new Exception("Failed to determine .NET Framework install root - no InstallRoot value"); } key.Close(); buildEngine.BinPath = Path.Combine(installRoot, string.Format("v{0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build)); buildEngine.RegisterLogger(executor); executor.Verbosity = LoggerVerbosity.Normal; BuildPropertyGroup properties = new BuildPropertyGroup(); foreach (string propKey in pParams.Keys) { string val = pParams[propKey]; properties.SetProperty(propKey, val, true); } return buildEngine.BuildProjectFile(pProj.FileName, new string[]{pTarget}, properties); }
public XnaContentProject(Task task, string msBuildPath, string xnaInstallPath) { m_engine = new Engine(msBuildPath); m_engine.RegisterLogger(new XnaContentLogger(task)); m_project = new Project(m_engine); m_project.AddNewUsingTaskFromAssemblyName("BuildContent", "Microsoft.Xna.Framework.Content.Pipeline, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6d5c3888ef60e27d"); m_project.AddNewUsingTaskFromAssemblyName("BuildXact", "Microsoft.Xna.Framework.Content.Pipeline, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6d5c3888ef60e27d"); // Add our Content Pipeline Assemblies m_pipelineGroup = m_project.AddNewItemGroup(); m_contentGroup = m_project.AddNewItemGroup(); m_contentTarget = m_project.Targets.AddNewTarget("_BuildXNAContentLists"); // Add our Build target m_xnaTarget = m_project.Targets.AddNewTarget("Build"); m_xnaTarget.DependsOnTargets = "_BuildXNAContentLists"; // Add Default Pipeline Assemblies. AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.EffectImporter.dll"); AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.FBXImporter.dll"); AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.TextureImporter.dll"); AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.XImporter.dll"); }
public ProjectBuilder (string file, string binDir) { this.file = file; engine = new Engine (binDir); engine.GlobalProperties.SetProperty ("BuildingInsideVisualStudio", "true"); consoleLogger = new ConsoleLogger (LoggerVerbosity.Normal, LogWriteLine, null, null); engine.RegisterLogger (consoleLogger); Refresh (); }
public void InvalidToolPath() { //Note Engine's BinPath is distinct from the ToolsVersion's ToolsPath Engine e = new Engine(); MockLogger mockLogger = new MockLogger(); e.RegisterLogger(mockLogger); ToolsetState t = new ToolsetState(e, new Toolset("toolsversionname", "invalid||path"), new GetFiles(this.getFiles), new LoadXmlFromPath(this.loadXmlFromPath)); TaskRegistry taskRegistry = (TaskRegistry) t.GetTaskRegistry(null); Console.WriteLine(mockLogger.FullLog); Assert.AreEqual(1, mockLogger.WarningCount, "Expected a warning for invalid character in toolpath"); }
public void Test1 () { string projectString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <ResXFile Include=""Item1""> <Culture>fr</Culture> </ResXFile> <ResXFile Include=""Item2""> <Culture>fr</Culture> </ResXFile> <ResXFile Include=""Item3""> <Culture>en</Culture> </ResXFile> <ResXFile Include=""Item4""> <Culture>gb</Culture> </ResXFile> <ResXFile Include=""Item5""> <Culture>fr</Culture> </ResXFile> <ResXFile Include=""Item6""> <Culture>it</Culture> </ResXFile> </ItemGroup> <Target Name=""ShowMessage""> <Message Text = ""Culture: %(ResXFile.Culture) -- ResXFile: @(ResXFile)"" /> </Target> </Project>"; Engine engine = new Engine (Consts.BinPath); Project project = engine.CreateNewProject (); TestMessageLogger testLogger = new TestMessageLogger (); engine.RegisterLogger (testLogger); project.LoadXml (projectString); Assert.IsTrue (project.Build ("ShowMessage"), "A1: Build failed"); CheckMessage (testLogger, "fr", "Item1;Item2;Item5", "A2"); CheckMessage (testLogger, "en", "Item3", "A3"); CheckMessage (testLogger, "gb", "Item4", "A4"); CheckMessage (testLogger, "it", "Item6", "A5"); CheckEngineEventCounts (testLogger, 1, 1, 4, 4); }
public ProjectBuilder (string file, string binDir) { this.file = file; RunSTA (delegate { engine = new Engine (binDir); engine.GlobalProperties.SetProperty ("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.GlobalProperties.SetProperty ("UseHostCompilerIfAvailable", "false"); consoleLogger = new MDConsoleLogger (LoggerVerbosity.Normal, LogWriteLine, null, null); engine.RegisterLogger (consoleLogger); }); Refresh (); }
public void WarningLoggedIfNoDefaultTasksFound() { //Note Engine's BinPath is distinct from the ToolsVersion's ToolsPath Engine e = new Engine(); MockLogger mockLogger = new MockLogger(); e.RegisterLogger(mockLogger); ToolsetState t = new ToolsetState(e, new Toolset("toolsversionname", "c:\\directory1\\directory2\\doesntexist"), new GetFiles(this.getFiles), new LoadXmlFromPath(this.loadXmlFromPath)); TaskRegistry taskRegistry = (TaskRegistry) t.GetTaskRegistry(null); string[] unexpectedRegisteredTasks = { "a1", "a2", "a3", "a4", "b1", "c1", "d1", "e1", "f1", "g1", "g2", "g3", "11", "12", "13", "21" }; Assert.AreEqual(1, mockLogger.WarningCount, "Expected 1 warning logged!"); foreach (string unexpectedRegisteredTask in unexpectedRegisteredTasks) { Hashtable registeredTasks; Assert.IsFalse(taskRegistry.FindRegisteredTasks(unexpectedRegisteredTask, true, out registeredTasks), String.Format("Unexpected task '{0}' registered!", unexpectedRegisteredTask)); } }
static void Main(string[] args) { // We need to tell MSBuild where msbuild.exe is, so it can launch child nodes string parameters = @"MSBUILDLOCATION=" + System.Environment.GetFolderPath(System.Environment.SpecialFolder.System) + @"\..\Microsoft.NET\Framework\v3.5"; // We need to tell MSBuild whether nodes should hang around for 60 seconds after the build is done in case they are needed again bool nodeReuse = true; // e.g. if (!nodeReuse) { parameters += ";NODEREUSE=false"; } // We need to tell MSBuild the maximum number of nodes to use. It is usually fastest to pick about the same number as you have CPU cores int maxNodeCount = 3; // e.g. // Create the engine with this information Engine buildEngine = new Engine(null, ToolsetDefinitionLocations.Registry | ToolsetDefinitionLocations.ConfigurationFile, maxNodeCount, parameters); // Create a file logger with a matching forwarding logger, e.g. FileLogger fileLogger = new FileLogger(); fileLogger.Verbosity = LoggerVerbosity.Detailed; Assembly engineAssembly = Assembly.GetAssembly(typeof(Engine)); string loggerAssemblyName = engineAssembly.GetName().FullName; LoggerDescription fileLoggerForwardingLoggerDescription = new LoggerDescription("Microsoft.Build.BuildEngine.ConfigurableForwardingLogger", loggerAssemblyName, null, String.Empty, LoggerVerbosity.Detailed); // Create a regular console logger too, e.g. ConsoleLogger logger = new ConsoleLogger(); logger.Verbosity = LoggerVerbosity.Normal; // Register all of these loggers buildEngine.RegisterDistributedLogger(fileLogger, fileLoggerForwardingLoggerDescription); buildEngine.RegisterLogger(logger); // Do a build buildEngine.BuildProjectFile("root.proj"); // Finish cleanly buildEngine.Shutdown(); }
public void TestItemsWithWildcards () { Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); engine.RegisterLogger (logger); // Setup string basedir = PathCombine ("Test", "resources", "dir"); string aaa = PathCombine ("a", "aa", "aaa"); string bb = Path.Combine ("b", "bb"); string[] dirs = { aaa, bb, "c" }; string [] files = { PathCombine (basedir, aaa, "foo.dll"), PathCombine (basedir, bb, "bar.dll"), PathCombine (basedir, bb, "sample.txt"), Path.Combine (basedir, "xyz.dll") }; string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <ItemsRel Include='dir\**\*.dll' Exclude='*\x*.dll' /> <ItemsRelExpanded Include=""@(ItemsRel->'%(FullPath)')"" /> <ItemsAbs Include='$(MSBuildProjectDirectory)\dir\**\*.dll'/> </ItemGroup> <Target Name='Main'> <Message Text=""ItemsRel: %(ItemsRel.FullPath) RecDir: %(ItemsRel.RecursiveDir)""/> <Message Text=""ItemsRelExpanded: %(ItemsRelExpanded.Identity)""/> <Message Text='ItemsAbs: %(ItemsAbs.Identity) RecDir: %(ItemsAbs.RecursiveDir)'/> </Target> </Project>"; try { CreateDirectoriesAndFiles (basedir, dirs, files); string projectdir = Path.Combine ("Test", "resources"); File.WriteAllText (Path.Combine (projectdir, "wild1.proj"), documentString); proj.Load (Path.Combine (projectdir, "wild1.proj")); if (!proj.Build ("Main")) { logger.DumpMessages (); Assert.Fail ("Build failed"); } string full_base_dir = Path.GetFullPath (basedir); logger.CheckLoggedAny (@"ItemsRel: "+ PathCombine (full_base_dir, aaa, "foo.dll") + " RecDir: " + aaa + Path.DirectorySeparatorChar, MessageImportance.Normal, "A1"); logger.CheckLoggedAny (@"ItemsRel: " + PathCombine (full_base_dir, bb, "bar.dll") + " RecDir: " + bb + Path.DirectorySeparatorChar, MessageImportance.Normal, "A2"); logger.CheckLoggedAny (@"ItemsRelExpanded: " + PathCombine (full_base_dir, aaa, "foo.dll"), MessageImportance.Normal, "A3"); logger.CheckLoggedAny (@"ItemsRelExpanded: " + PathCombine (full_base_dir, bb, "bar.dll"), MessageImportance.Normal, "A4"); logger.CheckLoggedAny (@"ItemsAbs: " + PathCombine (full_base_dir, aaa, "foo.dll") + @" RecDir: " + aaa + Path.DirectorySeparatorChar, MessageImportance.Normal, "A5"); logger.CheckLoggedAny (@"ItemsAbs: " + PathCombine (full_base_dir, bb, "bar.dll") + @" RecDir: " + bb + Path.DirectorySeparatorChar, MessageImportance.Normal, "A6"); logger.CheckLoggedAny (@"ItemsAbs: " + PathCombine (full_base_dir, "xyz.dll") + @" RecDir: ", MessageImportance.Normal, "A7"); Assert.AreEqual (0, logger.NormalMessageCount, "Unexpected extra messages found"); } catch (AssertionException) { logger.DumpMessages (); throw; } finally { Directory.Delete (basedir, true); } }
//Test with string public void TestItemsInTarget3c () { Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger(); engine.RegisterLogger(logger); string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <UsingTask TaskName='BatchingTestTask' AssemblyFile='Test\resources\TestTasks.dll' /> <PropertyGroup> <A>A</A> <B>A;B</B> <C>A;;</C> <D>$(C);Foo</D> </PropertyGroup> <ItemGroup> <A Include='A;B;;;C' /> </ItemGroup>"; documentString += CreateTargetFragment ("BatchingTestTask", "SingleString", "SingleStringOutput", "I", new string [] { "$(A)$(A)", "$(B)$(B)", "$(C)", "$(C)$(C)", "$(C) $(C)", "@(A);$(C)", "@(A);A;B;C", "@(A) $(C) @(A)", }) + "</Project>"; proj.LoadXml (documentString); if (!proj.Build("1")) { logger.DumpMessages(); Assert.Fail("Build failed"); } BuildProperty bp = proj.EvaluatedProperties ["D"]; Assert.AreEqual ("$(C);Foo", bp.Value, "B0"); Assert.AreEqual ("A;;;Foo", bp.FinalValue, "B1"); bp = proj.EvaluatedProperties ["C"]; Assert.AreEqual ("A;;", bp.Value, "B3"); Assert.AreEqual ("A;;", bp.FinalValue, "B4"); CheckItems (proj, "I0", "A0", "AA"); CheckItems (proj, "I1", "A1", "A;BA;B"); CheckItems (proj, "I2", "A2", "A;;"); CheckItems (proj, "I3", "A3", "A;;A;;"); CheckItems (proj, "I4", "A4", "A;; A;;"); CheckItems (proj, "I5", "A5", "A;B;C;A;;"); CheckItems (proj, "I6", "A6", "A;B;C;A;B;C"); CheckItems (proj, "I7", "A7", "A;B;C A;; A;B;C"); }
void CreateAndCheckProject (string[] guids, string[] project_ref_guids, string[] messages, bool build_result, string prefix) { Engine engine = new Engine (Consts.BinPath); Project project = engine.CreateNewProject (); TestMessageLogger testLogger = new TestMessageLogger (); engine.RegisterLogger (testLogger); string projectString = CreateProject (guids, project_ref_guids); project.LoadXml (projectString); try { Assert.AreEqual (build_result, project.Build (), "Build " + (build_result ? "failed" : "should've failed")); if (!build_result || messages == null) // build failed as expected, don't check outputs return; for (int i = 0; i < messages.Length; i++) testLogger.CheckLoggedMessageHead (messages [i], prefix + i.ToString ()); Assert.AreEqual (0, testLogger.NormalMessageCount); } catch (AssertionException) { Console.WriteLine (projectString); testLogger.DumpMessages (); throw; } }
public void TestEmptyPropertyValue () { Engine engine; Project project; string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <A>1</A> </PropertyGroup> <Target Name='1'> <Message Text='Before: $(A)'/> <CreateProperty Value=''> <Output TaskParameter='Value' PropertyName='A' /> </CreateProperty> <Message Text='After: $(A)'/> </Target> </Project> "; engine = new Engine (Consts.BinPath); TestMessageLogger testLogger = new TestMessageLogger (); engine.RegisterLogger (testLogger); project = engine.CreateNewProject (); project.LoadXml (documentString); if (!project.Build ("1")) { testLogger.DumpMessages (); Assert.Fail ("Build failed"); } testLogger.CheckLoggedMessageHead ("Before: 1", "A1"); testLogger.CheckLoggedMessageHead ("After: ", "A2"); Assert.AreEqual (0, testLogger.NormalMessageCount, "Unexpected messages found"); }
public void TestExecution2 () { string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='1'> <Error Text='Text' HelpKeyword='HelpKeyword' Code='Code' /> </Target> </Project> "; engine = new Engine (Consts.BinPath); testLogger = new TestErrorLogger (); engine.RegisterLogger (testLogger); project = engine.CreateNewProject (); project.LoadXml (documentString); project.Build ("1"); Assert.AreEqual (0, testLogger.CheckHead ("Text", "HelpKeyword", "Code"), "A1"); }
public override void Execute() { if (!(hostContext.Data["EnabledRenderers"] as StringCollection).Contains(this.Identifier)) { return; } // Get parameters Dictionary <String, StringCollection> parameters = hostContext.Data["CommandParameters"] as Dictionary <String, StringCollection>; System.Diagnostics.Trace.WriteLine("\r\nStarting RIMBA Renderer", "information"); StringCollection genFormatters = new StringCollection(); bool makeWP7Proj = false; if (hostContext.Mode == Pipeline.OperationModeType.Quirks) { System.Diagnostics.Trace.WriteLine("--- WARNING ---\r\n Host context is operating in Quirks mode, GPMR cannot guarantee output will be accurate\r\n--- WARNING ---"); } #region Validate all parameters // Validate parameters if (!parameters.ContainsKey("rimbapi-api-ns")) { parameters.Add("rimbapi-api-ns", new StringCollection()); parameters["rimbapi-api-ns"].Add("MARC.Everest"); } if (!parameters.ContainsKey("rimbapi-target-ns")) { parameters.Add("rimbapi-target-ns", new StringCollection()); parameters["rimbapi-target-ns"].Add("output"); } if (parameters.ContainsKey("rimbapi-root-class")) { RootClass = parameters["rimbapi-root-class"][0]; } if (parameters.ContainsKey("rimbapi-gen-vocab")) { GenerateVocab = Convert.ToBoolean(parameters["rimbapi-gen-vocab"][0]); } if (parameters.ContainsKey("rimbapi-gen-rim")) { GenerateRim = Convert.ToBoolean(parameters["rimbapi-gen-rim"][0]); } if (parameters.ContainsKey("rimbapi-profileid")) { InteractionRenderer.profileId = parameters["rimbapi-profileid"][0]; } if (parameters.ContainsKey("rimbapi-oid-profileid")) { InteractionRenderer.profileIdOid = parameters["rimbapi-oid-profileid"][0]; } if (parameters.ContainsKey("rimbapi-oid-interactionid")) { InteractionRenderer.interactionIdOid = parameters["rimbapi-oid-interactionid"][0]; } if (parameters.ContainsKey("rimbapi-oid-triggerevent")) { InteractionRenderer.triggerEventOid = parameters["rimbapi-oid-triggerevent"][0]; } if (parameters.ContainsKey("rimbapi-gen-its")) { genFormatters = parameters["rimbapi-gen-its"]; } if (parameters.ContainsKey("rimbapi-phone")) { makeWP7Proj = bool.Parse(parameters["rimbapi-phone"][0]); } #endregion // Initialize Heuristics MohawkCollege.EHR.gpmr.Pipeline.Renderer.RimbaCS.HeuristicEngine.Datatypes.Initialize(parameters["rimbapi-api-ns"][0]); MohawkCollege.EHR.gpmr.Pipeline.Renderer.RimbaCS.HeuristicEngine.Interfaces.Initialize(parameters["rimbapi-api-ns"][0]); // Get our repository ready ClassRepository classRep = hostContext.Data["SourceCR"] as ClassRepository; string ProjectFileName = "output.csproj"; // Set the output file name if (parameters.ContainsKey("rimbapi-target-ns")) { ProjectFileName = parameters["rimbapi-target-ns"][0]; } if (parameters.ContainsKey("rimbapi-partials")) { RenderPartials = Boolean.Parse(parameters["rimbapi-partials"][0]); } if (parameters.ContainsKey("rimbapi-realm-pref")) { prefRealm = parameters["rimbapi-realm-pref"][0]; } if (parameters.ContainsKey("rimbapi-max-literals")) { MaxLiterals = Int32.Parse(parameters["rimbapi-max-literals"][0]); } if (parameters.ContainsKey("rimbapi-suppress-doc")) { SuppressDoc = Boolean.Parse(parameters["rimbapi-suppress-doc"][0]); } // Setup the template parameters string[][] templateFields = new string[][] { new string[] { "$license$", parameters.ContainsKey("rimbapi-license") ? Licenses.ResourceManager.GetString(parameters["rimbapi-license"][0].ToUpper()) : "" }, new string[] { "$org$", parameters.ContainsKey("rimbapi-org") ? parameters["rimbapi-org"][0] : "" }, new string[] { "$date$", DateTime.Now.ToString("yyyy-MM-dd") }, new string[] { "$clrversion$", Environment.Version.ToString() }, new string[] { "$time$", DateTime.Now.ToString("HH:mm:ss") }, new string[] { "$author$", SystemInformation.UserName }, new string[] { "$year$", DateTime.Now.Year.ToString() }, new string[] { "$version$", Assembly.GetEntryAssembly().GetName().Version.ToString() }, new string[] { "$guid$", Guid.NewGuid().ToString() }, new string[] { "$name$", ProjectFileName }, new string[] { "$mrversion$", InteractionRenderer.profileId ?? "" } }; // Now we want to scan our assembly for FeatureRenderers List <KeyValuePair <FeatureRendererAttribute, IFeatureRenderer> > renderers = new List <KeyValuePair <FeatureRendererAttribute, IFeatureRenderer> >(); foreach (Type t in this.GetType().Assembly.GetTypes()) { if (t.GetInterface("MohawkCollege.EHR.gpmr.Pipeline.Renderer.RimbaCS.Interfaces.IFeatureRenderer") != null && t.GetCustomAttributes(typeof(FeatureRendererAttribute), true).Length > 0) { foreach (FeatureRendererAttribute feature in (t.GetCustomAttributes(typeof(FeatureRendererAttribute), true))) { // Only one feature renderer per feature, so if the dictionary throws an exception // on the add it is ok renderers.Add(new KeyValuePair <FeatureRendererAttribute, IFeatureRenderer>(feature, (IFeatureRenderer)t.Assembly.CreateInstance(t.FullName))); } } } #region Setup the project // Create engine reference Microsoft.Build.BuildEngine.Engine engine = new Microsoft.Build.BuildEngine.Engine( Path.Combine(Path.Combine(Path.Combine(System.Environment.SystemDirectory, "..\\Microsoft.NET"), "Framework"), "v3.5")), phoneEngine = new Microsoft.Build.BuildEngine.Engine( Path.Combine(Path.Combine(Path.Combine(System.Environment.SystemDirectory, "..\\Microsoft.NET"), "Framework"), "v4.0.30319")); // Create MSPROJ Microsoft.Build.BuildEngine.Project project = new Microsoft.Build.BuildEngine.Project(engine), phoneProj = new Project(phoneEngine, "4.0"); phoneProj.DefaultTargets = project.DefaultTargets = "Build"; // Setup project attributes Microsoft.Build.BuildEngine.BuildPropertyGroup pg = project.AddNewPropertyGroup(false); Microsoft.Build.BuildEngine.BuildProperty property = pg.AddNewProperty("Configuration", "Release"); property.Condition = "'$(Configuration)' == ''"; property = pg.AddNewProperty("Platform", "AnyCPU"); property.Condition = "'$(Platform)' == ''"; pg.AddNewProperty("ProductVersion", "10.0.20506"); pg.AddNewProperty("SchemaVersion", "2.0"); pg.AddNewProperty("ProjectGuid", Guid.NewGuid().ToString()); pg.AddNewProperty("OutputType", "Library"); pg.AddNewProperty("AppDesignerFolder", "Properties"); pg.AddNewProperty("RootNamespace", parameters["rimbapi-target-ns"][0]); pg.AddNewProperty("AssemblyName", parameters["rimbapi-target-ns"][0]); // Release AnyCPU pg = project.AddNewPropertyGroup(false); pg.Condition = "'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"; pg.AddNewProperty("DebugType", "pdbonly"); pg.AddNewProperty("Optimize", "true"); pg.AddNewProperty("OutputPath", "bin\\release"); pg.AddNewProperty("DefineConstants", "TRACE"); pg.AddNewProperty("ErrorReport", "prompt"); pg.AddNewProperty("WarningLevel", "4"); pg.AddNewProperty("DocumentationFile", "bin\\release\\" + parameters["rimbapi-target-ns"][0] + ".xml"); // Create Dir Structure Directory.CreateDirectory(Path.Combine(hostContext.Output, "bin")); Directory.CreateDirectory(Path.Combine(hostContext.Output, "lib")); Directory.CreateDirectory(Path.Combine(hostContext.Output, "Properties")); Directory.CreateDirectory(Path.Combine(hostContext.Output, "Vocabulary")); Directory.CreateDirectory(Path.Combine(hostContext.Output, "Interaction")); // Add reference structure Microsoft.Build.BuildEngine.BuildItemGroup refItemGroup = project.AddNewItemGroup(); // Add References File.Copy(Path.Combine(System.Windows.Forms.Application.StartupPath, "MARC.Everest.dll"), Path.Combine(Path.Combine(hostContext.Output, "lib"), "MARC.Everest.dll"), true); if (makeWP7Proj) { File.Copy(Path.Combine(Path.Combine(System.Windows.Forms.Application.StartupPath, "lib"), "MARC.Everest.Phone.dll"), Path.Combine(Path.Combine(hostContext.Output, "lib"), "MARC.Everest.Phone.dll"), true); } File.Copy(Path.Combine(System.Windows.Forms.Application.StartupPath, "MARC.Everest.xml"), Path.Combine(Path.Combine(hostContext.Output, "lib"), "MARC.Everest.xml"), true); refItemGroup.AddNewItem("Reference", "System"); refItemGroup.AddNewItem("Reference", "System.Drawing"); refItemGroup.AddNewItem("Reference", "System.Xml"); Microsoft.Build.BuildEngine.BuildItem buildItem = refItemGroup.AddNewItem("Reference", @"MARC.Everest"); buildItem.SetMetadata("SpecificVersion", "false"); buildItem.SetMetadata("HintPath", "lib\\MARC.Everest.dll"); project.AddNewImport("$(MSBuildBinPath)\\Microsoft.CSharp.targets", null); Microsoft.Build.BuildEngine.BuildItemGroup fileItemGroup = project.AddNewItemGroup(), phoneFileItemGroup = phoneProj.AddNewItemGroup(); #region Assembly Info try { TextWriter tw = File.CreateText(Path.Combine(Path.Combine(hostContext.Output, "Properties"), "AssemblyInfo.cs")); try { string Header = Template.AssemblyInfo; // Set the header to the default // Populate template fields foreach (String[] st in templateFields) { Header = Header.Replace(st[0], st[1]); } // Write header tw.Write(Header); } finally { tw.Close(); } fileItemGroup.AddNewItem("Compile", Path.Combine("Properties", "AssemblyInfo.cs")); phoneFileItemGroup.AddNewItem("Compile", Path.Combine("Properties", "AssemblyInfo.cs")); } catch (Exception) { System.Diagnostics.Trace.WriteLine("Couldn't generate the AssemblyInfo.cs file for this project", "warn"); } #endregion #endregion #region Code Create // Convert class rep to list List <Feature> features = new List <Feature>(); foreach (KeyValuePair <String, Feature> kv in classRep) { features.Add(kv.Value); } // Sort so classes are processed first features.Sort(delegate(Feature a, Feature b) { if ((a is SubSystem) && !(b is SubSystem)) { return(-1); } else if ((b is SubSystem) && !(a is SubSystem)) { return(1); } else { return(a.GetType().Name.CompareTo(b.GetType().Name)); } }); RenderFeatureList(features, templateFields, renderers, fileItemGroup, phoneFileItemGroup, parameters); // Any added features? // HACK: This should be fixed soon, but meh... I'll get around to it List <Feature> addlFeatures = new List <Feature>(); foreach (KeyValuePair <String, Feature> kv in classRep) { if (!features.Contains(kv.Value)) { addlFeatures.Add(kv.Value); } } RenderFeatureList(addlFeatures, templateFields, renderers, fileItemGroup, phoneFileItemGroup, parameters); // Save the project project.Save(Path.Combine(hostContext.Output, ProjectFileName) + ".csproj"); #endregion // Compile? #region Compile this project // Does the user want to compile? if (parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-compile"][0])) { string logPath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); // Create log Microsoft.Build.BuildEngine.FileLogger logger = new Microsoft.Build.BuildEngine.FileLogger(); logger.Parameters = "logfile=" + logPath; engine.RegisterLogger(logger); System.Diagnostics.Trace.Write(String.Format("Compiling project (Build log {0})...", logPath), "information"); // Compile if (engine.BuildProject(project)) { System.Diagnostics.Trace.WriteLine("Success!", "information"); } else { System.Diagnostics.Trace.WriteLine("Fail", "information"); throw new InvalidOperationException("Failed compilation, operation cannot continue"); } engine.UnregisterAllLoggers(); } #endregion #region Windows Phone if (makeWP7Proj) { // Setup project attributes pg = phoneProj.AddNewPropertyGroup(false); property = pg.AddNewProperty("Configuration", "Release"); property.Condition = "'$(Configuration)' == ''"; property = pg.AddNewProperty("Platform", "AnyCPU"); property.Condition = "'$(Platform)' == ''"; pg.AddNewProperty("ProductVersion", "10.0.20506"); pg.AddNewProperty("SchemaVersion", "2.0"); pg.AddNewProperty("ProjectGuid", Guid.NewGuid().ToString()); pg.AddNewProperty("OutputType", "Library"); pg.AddNewProperty("AppDesignerFolder", "Properties"); pg.AddNewProperty("RootNamespace", parameters["rimbapi-target-ns"][0]); pg.AddNewProperty("AssemblyName", parameters["rimbapi-target-ns"][0] + ".Phone"); pg.AddNewProperty("ProjectTypeGuids", "{C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}"); pg.AddNewProperty("TargetFrameworkVersion", "v4.0"); pg.AddNewProperty("SilverlightVersion", "$(TargetFrameworkVersion)"); pg.AddNewProperty("TargetFrameworkProfile", "WindowsPhone71"); pg.AddNewProperty("TargetFrameworkIdentifier", "Silverlight"); pg.AddNewProperty("SilverlightApplication", "false"); pg.AddNewProperty("ValidateXaml", "true"); pg.AddNewProperty("ThrowErrorsInValidation", "true"); // Release AnyCPU pg = phoneProj.AddNewPropertyGroup(false); pg.Condition = "'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"; pg.AddNewProperty("DebugType", "pdbonly"); pg.AddNewProperty("Optimize", "true"); pg.AddNewProperty("OutputPath", "bin\\release"); pg.AddNewProperty("DefineConstants", "TRACE;SILVERLIGHT;WINDOWS_PHONE"); pg.AddNewProperty("ErrorReport", "prompt"); pg.AddNewProperty("NoStdLib", "true"); pg.AddNewProperty("NoConfig", "true"); pg.AddNewProperty("WarningLevel", "4"); pg.AddNewProperty("DocumentationFile", "bin\\release\\" + parameters["rimbapi-target-ns"][0] + ".Phone.xml"); // Add reference structure refItemGroup = phoneProj.AddNewItemGroup(); refItemGroup.AddNewItem("Reference", "System"); refItemGroup.AddNewItem("Reference", "System.Xml"); BuildItem evReference = refItemGroup.AddNewItem("Reference", @"MARC.Everest.Phone"); evReference.SetMetadata("SpecificVersion", "false"); evReference.SetMetadata("HintPath", "lib\\MARC.Everest.Phone.dll"); // Add WP7 Imports phoneProj.AddNewImport(@"$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.$(TargetFrameworkProfile).Overrides.targets", null); phoneProj.AddNewImport(@"$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.CSharp.targets", null); // HACK: Add tools version string fileName = Path.Combine(hostContext.Output, ProjectFileName) + ".Phone.csproj"; phoneProj.Save(fileName); XmlDocument doc = new XmlDocument(); doc.Load(fileName); doc.DocumentElement.Attributes.Append(doc.CreateAttribute("ToolsVersion")); doc.DocumentElement.Attributes["ToolsVersion"].Value = "4.0"; doc.Save(fileName); if (parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-compile"][0])) { System.Diagnostics.Trace.Write(String.Format("Compiling phone project..."), "information"); // Compile if (phoneEngine.BuildProjectFile(fileName)) { System.Diagnostics.Trace.WriteLine("Success!", "information"); } else { System.Diagnostics.Trace.WriteLine("Fail", "information"); throw new InvalidOperationException("Failed compilation, operation cannot continue"); } } } #endregion #region Generate Formatter Assemblies // Generate the formatter assemblies if (genFormatters.Count > 0 && parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-compile"][0])) { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); Trace.WriteLine("Generating ITS Formatter Types:", "information"); // Load the assembly Assembly genAsm = Assembly.LoadFile(Path.Combine(Path.Combine(Path.Combine(hostContext.Output, "bin"), "release"), ProjectFileName + ".dll")); foreach (string s in genFormatters) { GenerateFormatterAssembly(s, genAsm, InteractionRenderer.profileId ?? "formatter"); } // Assembly resolve AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve); } else if (genFormatters.Count > 0) { Trace.WriteLine("Can't use --rimbapi-gen-its when --rimbapi-compile is not true, skipping ITS generation", "warn"); } #endregion // Does the user only want asm? #region dllonly if (parameters.ContainsKey("rimbapi-dllonly") && parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-dllonly"][0])) { try { // Move the assemblies up to root foreach (string file in Directory.GetFiles(Path.Combine(Path.Combine(hostContext.Output, "bin"), "release"))) { if (File.Exists(Path.Combine(hostContext.Output, Path.GetFileName(file)))) { File.Delete(Path.Combine(hostContext.Output, Path.GetFileName(file))); } File.Move(file, Path.Combine(hostContext.Output, Path.GetFileName(file))); } // Clean all in the projects and remove all directories List <String> directories = new List <string>(new string[] { Path.Combine(Path.Combine(hostContext.Output, "bin"), "release"), Path.Combine(hostContext.Output, "bin"), Path.Combine(hostContext.Output, "lib"), Path.Combine(hostContext.Output, "Vocabulary"), Path.Combine(hostContext.Output, "Interaction"), Path.Combine(hostContext.Output, "obj") }); // Gather files and clean foreach (Microsoft.Build.BuildEngine.BuildItem fi in fileItemGroup) { // Add directory on the "to be deleted" string dirName = Path.GetDirectoryName(Path.Combine(hostContext.Output, fi.Include)); if (!directories.Contains(dirName)) { directories.Add(dirName); } Trace.WriteLine(String.Format("Deleting {0}...", fi.Include), "debug"); File.Delete(Path.Combine(hostContext.Output, fi.Include)); } // Clean dirs foreach (string s in directories) { Directory.Delete(s, true); } File.Delete(project.FullFileName); } catch (Exception) { System.Diagnostics.Trace.WriteLine("Could not clean working files!", "warn"); } } #endregion }
public void TestMetadataFromItemReferences () { string project_xml = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <Item1 Include=""Item1Val1;Item1Val2""> <Item1Md>False</Item1Md> </Item1> <Item2 Include=""Val1;Val2;@(Item1);Val3""> <Name>Random name</Name> </Item2> <Item3 Include=""foo;bar;@(Item2);Last""/> </ItemGroup> <Target Name=""Main""> <CreateItem Include=""@(Item3)""> <Output TaskParameter=""Include"" ItemName=""Final""/> </CreateItem> <Message Text=""Final: %(Final.Identity) Item1Md: %(Final.Item1Md) Name: %(Final.Name)""/> </Target> </Project>"; Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); proj.LoadXml (project_xml); engine.RegisterLogger (logger); if (!proj.Build ("Main")) { logger.DumpMessages (); Assert.Fail ("Build failed"); } CheckItems (proj, "Final", "Z", "foo", "bar", "Val1", "Val2", "Item1Val1", "Item1Val2", "Val3", "Last"); logger.CheckLoggedMessageHead ("Final: foo Item1Md: Name: ", "A1"); logger.CheckLoggedMessageHead ("Final: bar Item1Md: Name: ", "A2"); logger.CheckLoggedMessageHead ("Final: Val1 Item1Md: Name: Random name", "A3"); logger.CheckLoggedMessageHead ("Final: Val2 Item1Md: Name: Random name", "A4"); logger.CheckLoggedMessageHead ("Final: Item1Val1 Item1Md: False Name: Random name", "A5"); logger.CheckLoggedMessageHead ("Final: Item1Val2 Item1Md: False Name: Random name", "A6"); logger.CheckLoggedMessageHead ("Final: Val3 Item1Md: Name: Random name", "A7"); logger.CheckLoggedMessageHead ("Final: Last Item1Md: Name: ", "A8"); Assert.AreEqual (0, logger.NormalMessageCount, "unexpected messages found"); }
// test properties and item refs, with dynamic properties/items public void TestItems12 () { string project_xml = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <Prop2>@(Ref1)</Prop2> </PropertyGroup> <ItemGroup> <Ref1 Include=""File1"" /> <Files Include=""@(Ref1)""/> </ItemGroup> <Target Name=""1""> <Message Text=""Prop2: $(Prop2)""/> <Message Text=""Files: @(Files)""/> <CreateItem Include=""foobar""> <Output TaskParameter=""Include"" ItemName=""Ref1""/> </CreateItem> <Message Text=""Files: @(Files)""/> <Message Text=""Prop2: $(Prop2)""/> <CreateProperty Value=""NewValue""> <Output TaskParameter=""Value"" PropertyName=""Prop2""/> </CreateProperty> <Message Text=""Prop2: $(Prop2)""/> </Target> </Project> "; Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); proj.LoadXml (project_xml); engine.RegisterLogger (logger); if (!proj.Build ("1")) { logger.DumpMessages (); Assert.Fail ("Build failed"); } logger.DumpMessages (); logger.CheckLoggedMessageHead ("Prop2: File1", "A1"); logger.CheckLoggedMessageHead ("Files: File1", "A1"); logger.CheckLoggedMessageHead ("Files: File1", "A1"); logger.CheckLoggedMessageHead ("Prop2: File1;foobar", "A1"); logger.CheckLoggedMessageHead ("Prop2: NewValue", "A1"); Assert.AreEqual (0, logger.NormalMessageCount, "unexpected messages found"); }
// test item metadata public void TestItems10 () { string project_xml = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <Prop1>@(Item0)</Prop1> <Prop2>@(Ref1)</Prop2> </PropertyGroup> <ItemGroup> <Item0 Include=""Foo""/> <Ref1 Include=""File1"" /> <IWithM Include=""A""> <Md>@(Item0)</Md> <Md2>$(Prop2)</Md2> </IWithM> </ItemGroup> <Target Name=""1""> <Message Text=""IWithM.md: %(IWithM.Md)""/> <Message Text=""IWithM.md2: %(IWithM.Md2)""/> <CreateItem Include=""Bar;Xyz""> <Output TaskParameter=""Include"" ItemName=""Item0""/> </CreateItem> <Message Text=""IWithM.md: %(IWithM.Md)""/> <Message Text=""IWithM.md2: %(IWithM.Md2)""/> </Target> </Project> "; Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); proj.LoadXml (project_xml); engine.RegisterLogger (logger); if (!proj.Build ("1")) { logger.DumpMessages (); Assert.Fail ("Build failed"); } logger.CheckLoggedMessageHead ("IWithM.md: Foo", "A1"); logger.CheckLoggedMessageHead ("IWithM.md2: File1", "A2"); logger.CheckLoggedMessageHead ("IWithM.md: Foo", "A3"); logger.CheckLoggedMessageHead ("IWithM.md2: File1", "A4"); Assert.AreEqual (0, logger.NormalMessageCount, "unexpected messages found"); }
private void NodeLocalEngineLoop() { buildInProgress = true; // Create a logging service for this build request localEngine = new Engine(parentGlobalProperties, toolsetSearchLocations, 1 /* cpus */, true /* child node */, this.nodeId, parentStartupDirectory, null); localEngine.Router.ChildMode = true; localEngine.Router.ParentNode = this; this.outProcLoggingService = new EngineLoggingServicesOutProc(this, localEngine.FlushRequestEvent); if (nodeLoggers.Length != 0) { foreach (LoggerDescription loggerDescription in nodeLoggers) { IForwardingLogger newLogger = null; bool exitedDueToError = true; try { newLogger = loggerDescription.CreateForwardingLogger(); // Check if the class was not found in the assembly if (newLogger == null) { InternalLoggerException.Throw(null, null, "FatalErrorWhileInitializingLogger", true, loggerDescription.Name); } newLogger.Verbosity = loggerDescription.Verbosity; newLogger.Parameters = loggerDescription.LoggerSwitchParameters; newLogger.NodeId = nodeId; EventRedirector newRedirector = new EventRedirector(loggerDescription.LoggerId, outProcLoggingService); newLogger.BuildEventRedirector = newRedirector; exitedDueToError = false; } // Polite logger failure catch (LoggerException e) { ReportUnhandledError(e); } // Logger class was not found catch (InternalLoggerException e) { ReportUnhandledError(e); } catch (Exception e) { // Wrap the exception in a InternalLoggerException and send it to the parent node string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "FatalErrorWhileInitializingLogger", loggerDescription.Name); ReportUnhandledError(new InternalLoggerException(message, e, null, errorCode, helpKeyword, true)); } // If there was a failure registering loggers, null out the engine pointer if (exitedDueToError) { localEngine = null; return; } localEngine.RegisterLogger(newLogger); } localEngine.ExternalLoggingServices = outProcLoggingService; } // Hook up logging service to forward all events to the central engine if necessary if (centralizedLogging) { if (nodeLoggers.Length != 0) { localEngine.LoggingServices.ForwardingService = outProcLoggingService; localEngine.ExternalLoggingServices = outProcLoggingService; } else { localEngine.LoggingServices = outProcLoggingService; } } localEngine.LoggingServices.OnlyLogCriticalEvents = this.logOnlyCriticalEvents; if (!useBreadthFirstTraversal) { localEngine.PostEngineCommand(new ChangeTraversalTypeCommand(useBreadthFirstTraversal, true)); } // Post all the requests that passed in while the engine was being constructed // into the engine queue lock (buildRequests) { while (buildRequests.Count != 0) { BuildRequest buildRequest = buildRequests.Dequeue(); localEngine.PostBuildRequest(buildRequest); } } try { // If there are forwarding loggers registered - generate a custom build started if (nodeLoggers.Length > 0) { localEngine.LoggingServices.LogBuildStarted(EngineLoggingServicesInProc.CENTRAL_ENGINE_EVENTSOURCE); localEngine.LoggingServices.ProcessPostedLoggingEvents(); } // Trigger the actual build if shutdown was not called while the engine was being initialized if (!nodeShutdown) { localEngine.EngineBuildLoop(null); } } catch (Exception e) { // Unhandled exception during execution. The node has to be shutdown. ReportUnhandledError(e); } finally { if (localEngine != null) { // Flush all the messages associated before shutting down localEngine.LoggingServices.ProcessPostedLoggingEvents(); NodeManager nodeManager = localEngine.NodeManager; // If the local engine is already shutting down, the TEM will be nulled out if (nodeManager.TaskExecutionModule != null && nodeManager.TaskExecutionModule.TaskExecutionTime != 0) { TimeSpan taskTimeSpan = new TimeSpan(localEngine.NodeManager.TaskExecutionModule.TaskExecutionTime); totalTaskTime = (int)taskTimeSpan.TotalMilliseconds; } localEngine.Shutdown(); } // Flush all the events to the parent engine outProcLoggingService.ProcessPostedLoggingEvents(); // Indicate that the node logger thread should exit exitNodeEvent.Set(); } }
public void TestReservedMetadata () { Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); engine.RegisterLogger (logger); string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup><File1 Include=""bar\foo.dll""/></ItemGroup> <Target Name='Main'> <Message Text='file1: @(File1)'/> <Message Text='file1: RootDir: %(File1.RootDir)'/> <Message Text='file1: Directory: %(File1.Directory)'/> </Target> </Project>"; string projectdir = Path.Combine ("Test", "resources"); File.WriteAllText (Path.Combine (projectdir, "test1.proj"), documentString); proj.Load (Path.Combine (projectdir, "test1.proj")); if (!proj.Build ("Main")) { logger.DumpMessages (); Assert.Fail ("Build failed"); } logger.DumpMessages (); logger.CheckLoggedMessageHead ("file1: " + Path.Combine ("bar", "foo.dll"), "A1"); string path_root = Path.GetPathRoot (Path.GetFullPath (projectdir)); logger.CheckLoggedMessageHead ("file1: RootDir: " + path_root, "A2"); string fullpath = Path.GetFullPath (Path.Combine (projectdir, "bar")); logger.CheckLoggedMessageHead ("file1: Directory: " + fullpath.Substring (path_root.Length) + Path.DirectorySeparatorChar, "A3"); if (logger.NormalMessageCount != 0) { logger.DumpMessages (); Assert.Fail ("Unexpected extra messages found"); } }
public void TestInheritedMetadataFromItemRefs2 () { Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); engine.RegisterLogger (logger); string documentString = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <Item5 Include='ZZ'> <MD5>Val5</MD5> </Item5> <Item0 Include='D'> <MD0>Val0</MD0> </Item0> <Item1 Include='A;@(Item0)' > <MD1>Val1</MD1> </Item1> <Item2 Include=""@(Item1,'-');@(Item5)"" /> </ItemGroup> <Target Name=""Main""> <Message Text=""Item2: %(Item2.Identity) MD0: %(Item2.MD0) MD1: %(Item2.MD1) MD5: %(Item2.MD5)""/> </Target> </Project> "; proj.LoadXml (documentString); CheckItems (proj, "Item2", "A1", "A-D", "ZZ"); if (!proj.Build ("Main")) { logger.DumpMessages (); Assert.Fail ("Build failed"); } logger.CheckLoggedMessageHead ("Item2: A-D MD0: MD1: MD5: ", "A4"); logger.CheckLoggedMessageHead ("Item2: ZZ MD0: MD1: MD5: Val5", "A5"); Assert.AreEqual (0, logger.NormalMessageCount, "Unexpected extra messages found"); }
public void TestEmptyItemsWithBatching () { string project_xml = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <UsingTask TaskName='StringTestTask' AssemblyFile='Test\resources\TestTasks.dll' /> <UsingTask TaskName='TestTask_TaskItem' AssemblyFile='Test\resources\TestTasks.dll' /> <UsingTask TaskName='TestTask_TaskItems' AssemblyFile='Test\resources\TestTasks.dll' /> <Target Name=""1""> <StringTestTask Property=""%(Item4.Identity)""> <Output TaskParameter=""OutputString"" PropertyName=""OutputString""/> </StringTestTask> <Message Text='output1: $(OutputString)'/> <StringTestTask Property="" %(Item4.Identity)""> <Output TaskParameter=""OutputString"" PropertyName=""OutputString""/> </StringTestTask> <Message Text='output2: $(OutputString)'/> <StringTestTask Array=""%(Item4.Identity)""> <Output TaskParameter=""OutputString"" PropertyName=""OutputString""/> </StringTestTask> <Message Text='output3: $(OutputString)'/> <StringTestTask Array="" %(Item4.Identity)""> <Output TaskParameter=""OutputString"" PropertyName=""OutputString""/> </StringTestTask> <Message Text='output4: $(OutputString)'/> <TestTask_TaskItem Property=""%(Item4.Identity)""> <Output TaskParameter=""Output"" PropertyName=""OutputString""/> </TestTask_TaskItem> <Message Text='output5: $(OutputString)'/> <TestTask_TaskItem Property="" %(Item4.Identity)""> <Output TaskParameter=""Output"" PropertyName=""OutputString""/> </TestTask_TaskItem> <Message Text='output6: $(OutputString)'/> <TestTask_TaskItems Property="" %(Item4.Identity)""> <Output TaskParameter=""Output"" PropertyName=""OutputString""/> </TestTask_TaskItems> <Message Text='output7: $(OutputString)'/> <!-- no space in property --> <TestTask_TaskItems Property=""%(Item4.Identity)""> <Output TaskParameter=""Output"" PropertyName=""OutputString""/> </TestTask_TaskItems> <Message Text='output8: $(OutputString)'/> </Target> </Project> "; Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); proj.LoadXml (project_xml); engine.RegisterLogger (logger); if (!proj.Build ("1")) { logger.DumpMessages (); Assert.Fail ("Build failed"); } logger.DumpMessages (); logger.CheckLoggedMessageHead ("output1: property: null ## array: null", "A1"); logger.CheckLoggedMessageHead ("output2: property: ## array: null", "A2"); logger.CheckLoggedMessageHead ("output3: property: null ## array: null", "A3"); logger.CheckLoggedMessageHead ("output4: property: null ## array: null", "A4"); logger.CheckLoggedMessageHead ("output5: null", "A5"); logger.CheckLoggedMessageHead ("output6: null", "A6"); logger.CheckLoggedMessageHead ("output7: null", "A7"); logger.CheckLoggedMessageHead ("output8: null", "A8"); Assert.AreEqual (0, logger.NormalMessageCount, "unexpected messages found"); }
// Test Item/prop references in conditions public void TestItems11 () { string project_xml = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <Prop1>@(Item0)</Prop1> </PropertyGroup> <ItemGroup> <Item0 Include=""Foo""/> <Item1 Include=""@(Item0)""/> <CondItem Condition=""'@(Item1)' == '@(Item0)'"" Include=""Equal to item0""/> <CondItem Condition=""'@(Item1)' == 'Foo'"" Include=""Equal to item0's value""/> <CondItem1 Condition=""'$(Prop1)' == '@(Item0)'"" Include=""Equal to item0""/> <CondItem1 Condition=""'$(Prop1)' == 'Foo'"" Include=""Equal to item0's value""/> </ItemGroup> <Target Name=""1""> <Message Text = ""CondItem: %(CondItem.Identity)""/> <Message Text = ""CondItem1: %(CondItem1.Identity)""/> </Target> </Project> "; Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); proj.LoadXml (project_xml); engine.RegisterLogger (logger); if (!proj.Build ("1")) { logger.DumpMessages (); Assert.Fail ("Build failed"); } logger.CheckLoggedMessageHead ("CondItem: Equal to item0", "A1"); logger.CheckLoggedMessageHead ("CondItem: Equal to item0's value", "A2"); logger.CheckLoggedMessageHead ("CondItem1: Equal to item0", "A3"); logger.CheckLoggedMessageHead ("CondItem1: Equal to item0's value", "A4"); Assert.AreEqual (0, logger.NormalMessageCount, "unexpected messages found"); }
public void TestTargetOutputsIncludingMetadata () { Engine engine; Project project; string documentString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <fruit Include=""apple""><md>a</md></fruit> <fruit Include=""rhubarb""><md>b</md></fruit> <fruit Include=""apricot""><md>c</md></fruit> </ItemGroup> <Target Name=""Main""> <CallTarget Targets=""foo""> <Output TaskParameter=""TargetOutputs"" ItemName=""AllOut""/> </CallTarget> <CallTarget Targets=""foo""> <Output TaskParameter=""TargetOutputs"" ItemName=""AllOut""/> </CallTarget> <Message Text=""AllOut: @(AllOut) metadata: %(AllOut.md)""/> </Target> <Target Name=""foo"" Outputs=""@(FooItem)""> <Message Text=""foo called""/> <CreateItem Include=""@(fruit)""> <Output TaskParameter=""Include"" ItemName=""FooItem""/> </CreateItem> <Message Text=""FooItem: @(FooItem) metadata: %(FooItem.md)""/> </Target> </Project>"; engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.LoadXml (documentString); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); engine.RegisterLogger (logger); bool result = project.Build ("Main"); if (!result) { logger.DumpMessages (); Assert.Fail ("Build failed"); } try { logger.CheckLoggedMessageHead ("foo called", "A1"); logger.CheckLoggedMessageHead ("FooItem: apple metadata: a", "A2"); logger.CheckLoggedMessageHead ("FooItem: rhubarb metadata: b", "A3"); logger.CheckLoggedMessageHead ("FooItem: apricot metadata: c", "A4"); logger.CheckLoggedMessageHead ("AllOut: apple;apple metadata: a", "A5"); logger.CheckLoggedMessageHead ("AllOut: rhubarb;rhubarb metadata: b", "A6"); logger.CheckLoggedMessageHead ("AllOut: apricot;apricot metadata: c", "A7"); Assert.AreEqual (0, logger.NormalMessageCount, "Extra messages found"); Assert.AreEqual (2, logger.TargetStarted, "TargetStarted count"); Assert.AreEqual (2, logger.TargetFinished, "TargetFinished count"); Assert.AreEqual (10, logger.TaskStarted, "TaskStarted count"); Assert.AreEqual (10, logger.TaskFinished, "TaskFinished count"); } catch (AssertionException) { logger.DumpMessages (); throw; } }
// test item refs in properties public void TestItems13 () { string project_xml = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <Prop1>@(Item0)</Prop1> </PropertyGroup> <ItemGroup> <Item0 Include=""Foo""/> <Item1 Include=""A\B.txt;A\C.txt;B\B.zip;B\C.zip"" /> <Item2 Include=""@(Item1->'%(Extension)/$(Prop1)')"" /> </ItemGroup> <Target Name='1'> <Message Text=""Item2: @(Item2)""/> </Target> </Project>"; Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); proj.LoadXml (project_xml); engine.RegisterLogger (logger); if (!proj.Build ("1")) { logger.DumpMessages (); Assert.Fail ("Build failed"); } logger.CheckLoggedMessageHead ("Item2: .txt/@(Item0);.txt/@(Item0);.zip/@(Item0);.zip/@(Item0)", "A1"); Assert.AreEqual (0, logger.NormalMessageCount, "unexpected messages found"); }
public void TestOverridingTargets () { Engine engine; Project project; string second = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='BeforeBuild'/> <Target Name='AfterBuild'/> <Target Name='Build' DependsOnTargets='BeforeBuild'> <Message Text='Build executing'/> <CallTarget Targets='AfterBuild'/> </Target> </Project>"; using (StreamWriter sw = new StreamWriter (Path.Combine ("Test", Path.Combine ("resources", "second.proj")))) { sw.Write (second); } string documentString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='AfterBuild'> <Message Text='Overriding AfterBuild'/> </Target> <Import Project='Test/resources/second.proj'/> <Target Name='BeforeBuild'> <Message Text='Overriding BeforeBuild'/> </Target> </Project>"; engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.LoadXml (documentString); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); engine.RegisterLogger (logger); bool result = project.Build ("Build"); if (!result) { logger.DumpMessages (); Assert.Fail ("Build failed"); } logger.CheckLoggedMessageHead ("Overriding BeforeBuild", "A1"); logger.CheckLoggedMessageHead ("Build executing", "A1"); Assert.AreEqual (0, logger.NormalMessageCount, "Unexpected extra messages found"); }
public void TestSelfRefrentialItems () { string project_xml = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <Prop1>@(Item1);Val</Prop1> <Prop2>@(Item2)</Prop2> <Prop3>@(Item3)</Prop3> </PropertyGroup> <ItemGroup> <Item1 Include=""Item1OldVal""/> <Item1 Include=""@(Item1);$(Prop1)""/> <Item2 Include=""Item2OldVal""/> <Item2 Include=""@(Item2->'%(Identity)');$(Prop2)""/> <Item3 Include=""Item3OldVal""/> <Item3 Include=""@(Item3, '_');$(Prop3)""/> <Item4 Include=""@(Item4)""/> </ItemGroup> <Target Name=""1""> <Message Text=""Item1: %(Item1.Identity)""/> <Message Text=""Item2: %(Item2.Identity)""/> <Message Text=""Item3: %(Item3.Identity)""/> <Message Text=""%(Item4.Identity)""/> <Message Text=""Item4: %(Item4.Identity)""/> </Target> </Project> "; Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); proj.LoadXml (project_xml); engine.RegisterLogger (logger); if (!proj.Build ("1")) { logger.DumpMessages (); Assert.Fail ("Build failed"); } logger.DumpMessages (); logger.CheckLoggedMessageHead ("Item1: Item1OldVal", "A1"); logger.CheckLoggedMessageHead ("Item1: Val", "A2"); logger.CheckLoggedMessageHead ("Item2: Item2OldVal", "A3"); logger.CheckLoggedMessageHead ("Item3: Item3OldVal", "A4"); logger.CheckLoggedMessageHead ("Item4: ", "A5"); Assert.AreEqual (0, logger.NormalMessageCount, "unexpected messages found"); }
public void TestBeforeAndAfterTargets () { Engine engine; Project project; string projectString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""4.0""> <Target Name=""DefaultBeforeTarget1"" BeforeTargets=""Default""> <Message Text=""Hello from DefaultBeforeTarget1""/> </Target> <Target Name=""DefaultBeforeTarget2"" BeforeTargets=""Default;Default;NonExistant""> <Message Text=""Hello from DefaultBeforeTarget2""/> </Target> <Target Name=""DefaultAfterTarget"" AfterTargets=""Default ; Foo""> <Message Text=""Hello from DefaultAfterTarget""/> </Target> <Target Name=""Default"" DependsOnTargets=""DefaultDependsOn""> <Message Text=""Hello from Default""/> </Target> <Target Name=""DefaultDependsOn""> <Message Text=""Hello from DefaultDependsOn""/> </Target> </Project>"; engine = new Engine (); project = engine.CreateNewProject (); project.LoadXml (projectString); MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); engine.RegisterLogger (logger); if (!project.Build ("Default")) { logger.DumpMessages (); Assert.Fail ("Build failed"); } logger.CheckLoggedMessageHead ("Hello from DefaultDependsOn", "A1"); logger.CheckLoggedMessageHead ("Hello from DefaultBeforeTarget1", "A1"); logger.CheckLoggedMessageHead ("Hello from DefaultBeforeTarget2", "A1"); logger.CheckLoggedMessageHead ("Hello from Default", "A1"); logger.CheckLoggedMessageHead ("Hello from DefaultAfterTarget", "A1"); Assert.AreEqual (0, logger.NormalMessageCount, "Unexpected messages found"); //warnings for referencing unknown targets: NonExistant and Foo Assert.AreEqual (2, logger.WarningsCount, "Expected warnings not raised"); }
public void TestItemsInTarget1 () { Engine engine = new Engine (Consts.BinPath); Project proj = engine.CreateNewProject (); string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <UsingTask TaskName='StringTestTask' AssemblyFile='Test\resources\TestTasks.dll' /> <PropertyGroup> <A>A</A> <B>@(A)g</B> </PropertyGroup> <ItemGroup> <A Include='A;B;C' /> </ItemGroup> <Target Name='1'> <StringTestTask Property='@(A)@(Z)'> <Output TaskParameter='Property' PropertyName='P1' /> </StringTestTask> <StringTestTask Property=""@(A,'')""> <Output TaskParameter='Property' PropertyName='P2' /> </StringTestTask> <StringTestTask Property=""@(A,'@(A)')""> <Output TaskParameter='Property' PropertyName='P3' /> </StringTestTask> <StringTestTask Property=""@(A,'$(A)')""> <Output TaskParameter='Property' PropertyName='P4' /> </StringTestTask> <StringTestTask Property=""@(A,'@(A,'')')""> <Output TaskParameter='Property' PropertyName='P5' /> </StringTestTask> <StringTestTask Property=""@(A,'$(B)')""> <Output TaskParameter='Property' PropertyName='P6' /> </StringTestTask> <StringTestTask Property=""%(A.Filename)""> <Output TaskParameter='Property' ItemName='I1' /> </StringTestTask> <StringTestTask Property=""@(A) %(Filename)""> <Output TaskParameter='Property' ItemName='I2' /> </StringTestTask> </Target> </Project> "; MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); engine.RegisterLogger (logger); proj.LoadXml (documentString); if (!proj.Build ("1")) { logger.DumpMessages (); Assert.Fail ("build failed"); } Assert.AreEqual ("A;B;C", proj.GetEvaluatedProperty ("P1"), "A1"); Assert.AreEqual ("ABC", proj.GetEvaluatedProperty ("P2"), "A2"); Assert.AreEqual ("A@(A)B@(A)C", proj.GetEvaluatedProperty ("P3"), "A3"); Assert.AreEqual ("AABAC", proj.GetEvaluatedProperty ("P4"), "A4"); Assert.AreEqual ("@(A,'ABC')", proj.GetEvaluatedProperty ("P5"), "A5"); Assert.AreEqual ("A@(A)gB@(A)gC", proj.GetEvaluatedProperty ("P6"), "A6"); CheckItems (proj, "I1", "A6", "A", "B", "C"); CheckItems (proj, "I2", "A7", "A A", "B B", "C C"); }
public void TestTargetReturns () { engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.Load (Path.Combine ("Test", Path.Combine ("resources", "TestReturns.csproj"))); var logger = new TestMessageLogger (); engine.RegisterLogger (logger); bool result = project.Build ("Main"); if (!result) { logger.DumpMessages (); Assert.Fail ("Build failed"); } logger.CheckLoggedMessageHead ("Result: Bar", "A1"); Assert.AreEqual (0, logger.NormalMessageCount, "Unexpected extra messages found"); }