public bool Build (Target target, out bool executeOnErrors) { executeOnErrors = false; try { string reason; if (!BuildTargetNeeded (out reason)) { LogTargetStarted (target); LogTargetSkipped (target, reason); LogTargetFinished (target, true); return true; } if (!String.IsNullOrEmpty (reason)) target.Engine.LogMessage (MessageImportance.Low, reason); Init (); ParseTargetAttributes (target); BatchAndPrepareBuckets (); return Run (target, out executeOnErrors); } finally { consumedItemsByName = null; consumedMetadataReferences = null; consumedQMetadataReferences = null; consumedUQMetadataReferences = null; batchedItemsByName = null; commonItemsByName = null; } }
static BuildTask[] GetTasks (Target t) { List <BuildTask> list = new List <BuildTask> (); foreach (BuildTask bt in t) list.Add (bt); return list.ToArray (); }
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"); }
internal TargetInProgessState ( EngineCallback engineCallback, Target target, List<ProjectBuildState> waitingBuildStates, ProjectBuildState initiatingRequest, BuildRequest [] outstandingBuildRequests, string projectName ) { this.targetId = new TargetIdWrapper(target); this.outstandingBuildRequests = outstandingBuildRequests; // For each waiting build context try to find the parent target this.parentBuildRequests = new List<BuildRequest>(); this.parentTargets = new List<TargetIdWrapper>(); this.projectName = projectName; // Process the waiting contexts if there are any if (waitingBuildStates != null) { for (int i = 0; i < waitingBuildStates.Count; i++) { ProcessBuildContext(engineCallback, waitingBuildStates[i], target); } } // Process the initiating context ProcessBuildContext(engineCallback, initiatingRequest, target); }
public void TestFromXml2 () { string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='Target' Condition='false' DependsOnTargets='X' > </Target> </Project> "; engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.LoadXml (documentString); Target[] t = new Target [1]; project.Targets.CopyTo (t, 0); Assert.AreEqual ("false", t [0].Condition, "A1"); Assert.AreEqual ("X", t [0].DependsOnTargets, "A2"); t [0].Condition = "true"; t [0].DependsOnTargets = "A;B"; Assert.AreEqual ("true", t [0].Condition, "A3"); Assert.AreEqual ("A;B", t [0].DependsOnTargets, "A4"); }
public void Visit(UsingTaskToken token) { currentTarget = null; // Out of any previous target context valueResolver.Normalize(token); if (token["AssemblyFile"] != null) Project.AddNewUsingTaskFromAssemblyFile(token["TaskName"], token["AssemblyFile"]); }
internal TargetExecutionWrapper ( Target targetClass, ArrayList taskElementList, List<string> targetParameters, XmlElement targetElement, Expander expander, BuildEventContext targetBuildEventContext ) { // Initialize the data about the target XML that has been calculated in the target class this.targetClass = targetClass; this.parentEngine = targetClass.ParentEngine; this.parentProject = targetClass.ParentProject; this.targetElement = targetElement; this.taskElementList = taskElementList; this.targetParameters = targetParameters; this.targetBuildEventContext = targetBuildEventContext; // Expand the list of depends on targets dependsOnTargetNames = expander.ExpandAllIntoStringList(targetClass.DependsOnTargets, targetClass.DependsOnTargetsAttribute); // Starting to build the target inProgressBuildState = InProgressBuildState.StartingBuild; // No messages have been logged loggedTargetStart = false; }
public bool Build (Target target, out bool executeOnErrors) { executeOnErrors = false; try { if (!BuildTargetNeeded ()) { LogTargetStarted (target); LogTargetSkipped (target); LogTargetFinished (target, true); return true; } Init (); ParseTargetAttributes (target); BatchAndPrepareBuckets (); return Run (target, out executeOnErrors); } finally { consumedItemsByName = null; consumedMetadataReferences = null; consumedQMetadataReferences = null; consumedUQMetadataReferences = null; batchedItemsByName = null; commonItemsByName = null; } }
bool Run (Target target, out bool executeOnErrors) { executeOnErrors = false; if (buckets.Count > 0) return RunBatched (target, out executeOnErrors); else return RunUnbatched (target, out executeOnErrors); }
internal BuildTask (XmlElement taskElement, Target parentTarget) { if (taskElement == null) throw new ArgumentNullException ("taskElement"); if (parentTarget == null) throw new ArgumentNullException ("parentTarget"); this.taskElement = taskElement; this.parentTarget = parentTarget; }
bool Run (Target target, out bool executeOnErrors) { executeOnErrors = false; if (buckets.Count > 0) { foreach (Dictionary<string, BuildItemGroup> bucket in buckets) if (!RunTargetWithBucket (bucket, target, out executeOnErrors)) return false; return true; } else { return RunTargetWithBucket (null, target, out executeOnErrors); } }
/// <summary> /// Creates an instance of this class for the given target. /// </summary> /// <owner>SumedhK</owner> internal TargetDependencyAnalyzer(string projectDirectory, Target targetToAnalyze, EngineLoggingServices loggingServices, BuildEventContext buildEventContext) { ErrorUtilities.VerifyThrow(projectDirectory != null, "Need a project directory."); ErrorUtilities.VerifyThrow(targetToAnalyze != null, "Need a target to analyze."); ErrorUtilities.VerifyThrow(targetToAnalyze.TargetElement != null, "Need a target element."); this.projectDirectory = projectDirectory; this.targetToAnalyze = targetToAnalyze; this.targetInputsAttribute = targetToAnalyze.TargetElement.Attributes[XMakeAttributes.inputs]; this.targetOutputsAttribute = targetToAnalyze.TargetElement.Attributes[XMakeAttributes.outputs]; this.loggingService = loggingServices; this.buildEventContext = buildEventContext; }
public void Visit(TargetToken token) { valueResolver.Normalize(token); currentTarget = Project.Targets.AddNewTarget(token["Name"]); getAndDo( token, depends => currentTarget.DependsOnTargets = depends, "DependsOnTargets", "Depends", "Deps"); getAndDo( token, condition => currentTarget.Condition = condition, "Condition", "If", "When"); }
/// <summary> /// Figure out the parent target or the parent build request for the given context /// </summary> private void ProcessBuildContext(EngineCallback engineCallback, ProjectBuildState buildContext, Target target) { BuildRequest parentRequest = null; TargetIdWrapper parentName = FindParentTarget(engineCallback, buildContext, target, out parentRequest); if (parentName != null) { parentTargets.Add(parentName); } if (parentRequest != null) { parentBuildRequests.Add(parentRequest); } }
/// <summary> /// This constructor initializes a persisted task from an existing task /// element which exists either in the main project file or one of the /// imported files. /// </summary> /// <param name="taskElement"></param> /// <param name="parentTarget"></param> /// <param name="importedFromAnotherProject"></param> /// <owner>rgoel</owner> internal BuildTask ( XmlElement taskElement, Target parentTarget, bool importedFromAnotherProject ) { // Make sure a valid node has been given to us. error.VerifyThrow(taskElement != null, "Need a valid XML node."); // Make sure a valid target has been given to us. error.VerifyThrow(parentTarget != null, "Need a valid target parent."); this.taskElement = taskElement; this.parentTarget = parentTarget; this.conditionAttribute = null; this.continueOnErrorAttribute = null; this.importedFromAnotherProject = importedFromAnotherProject; // Loop through all the attributes on the task element. foreach (XmlAttribute taskAttribute in taskElement.Attributes) { switch (taskAttribute.Name) { case XMakeAttributes.condition: this.conditionAttribute = taskAttribute; break; case XMakeAttributes.continueOnError: this.continueOnErrorAttribute = taskAttribute; break; // this only makes sense in the context of the new OM, // so just ignore it. case XMakeAttributes.msbuildRuntime: // do nothing break; // this only makes sense in the context of the new OM, // so just ignore it. case XMakeAttributes.msbuildArchitecture: // do nothing break; } } this.taskName = taskElement.Name; }
public Target AddNewTarget (string targetName) { if (targetName == null) throw new InvalidProjectFileException ( "The required attribute \"Name\" is missing from element <Target>."); XmlElement targetElement = parentProject.XmlDocument.CreateElement ("Target", Project.XmlNamespace); parentProject.XmlDocument.DocumentElement.AppendChild (targetElement); targetElement.SetAttribute ("Name", targetName); Target t = new Target (targetElement, parentProject, null); AddTarget (t); return t; }
/// <summary> /// Default constructor for creation of task execution wrapper /// </summary> internal TaskExecutionContext ( Project parentProject, Target parentTarget, XmlElement taskNode, ProjectBuildState buildContext, int handleId, int nodeIndex, BuildEventContext taskBuildEventContext ) :base(handleId, nodeIndex, taskBuildEventContext) { this.parentProject = parentProject; this.parentTarget = parentTarget; this.taskNode = taskNode; this.buildContext = buildContext; this.thrownException = null; }
public bool Build (Target target, out bool executeOnErrors) { executeOnErrors = false; try { Init (); ParseTargetAttributes (target); BatchAndPrepareBuckets (); return Run (target, out executeOnErrors); } finally { consumedItemsByName = null; consumedMetadataReferences = null; consumedQMetadataReferences = null; consumedUQMetadataReferences = null; batchedItemsByName = null; commonItemsByName = null; } }
public void TestFromXml1 () { string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='Target'> </Target> </Project> "; engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.LoadXml (documentString); Target[] t = new Target [1]; project.Targets.CopyTo (t, 0); Assert.AreEqual (String.Empty, t [0].Condition, "A1"); Assert.AreEqual (String.Empty, t [0].DependsOnTargets, "A2"); Assert.IsFalse (t [0].IsImported, "A3"); Assert.AreEqual ("Target", t [0].Name, "A4"); }
public void TestFromXml () { Engine engine; Project project; string documentString = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <Property>true</Property> </PropertyGroup> <Target Name='T'> <Message Text='Text' /> <Message Text='Text' Condition='$(Property)' ContinueOnError='$(Property)' /> </Target> </Project> "; engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.LoadXml (documentString); Target[] t = new Target [1]; BuildTask[] bt; project.Targets.CopyTo (t, 0); bt = GetTasks (t [0]); Assert.AreEqual (String.Empty, bt [0].Condition, "A1"); Assert.IsFalse (bt [0].ContinueOnError, "A2"); Assert.IsNull (bt [0].HostObject, "A3"); Assert.AreEqual ("Message", bt [0].Name, "A4"); Assert.IsNotNull (bt [0].Type, "A5"); Assert.AreEqual ("$(Property)", bt [1].Condition, "A6"); Assert.IsTrue (bt [1].ContinueOnError, "A7"); Assert.IsNull (bt [1].HostObject, "A8"); Assert.AreEqual ("Message", bt [0].Name, "A9"); Assert.IsNotNull (bt [0].Type, "A10"); }
/// <summary> /// Adds tasks that create a temporary VC project file with pre-resolved project references (that is, /// replaced with file references) /// </summary> /// <param name="solution"></param> /// <param name="target"></param> /// <param name="proj"></param> /// <param name="solutionConfiguration"></param> /// <param name="subTargetName"></param> /// <param name="projectConfigurationName"></param> /// <returns>The path to the temporary project file</returns> /// <owner>LukaszG</owner> static private string AddCreateTemporaryVCProjectTasks ( SolutionParser solution, Project msbuildProject, Target target, ProjectInSolution proj, ConfigurationInSolution solutionConfiguration, string subTargetName, string projectConfigurationName ) { StringBuilder referenceItemName = new StringBuilder(GenerateSafePropertyName(proj, "References")); if (!string.IsNullOrEmpty(subTargetName)) { referenceItemName.Append('_'); referenceItemName.Append(subTargetName); } StringBuilder importLibraryItemName = new StringBuilder(GenerateSafePropertyName(proj, "ImportLibraries")); if (!string.IsNullOrEmpty(subTargetName)) { importLibraryItemName.Append('_'); importLibraryItemName.Append(subTargetName); } string referenceGuidsToRemove = null; AddResolveProjectReferenceTasks(solution, msbuildProject, target, proj, solutionConfiguration, referenceItemName.ToString(), importLibraryItemName.ToString(), out referenceGuidsToRemove); if (string.IsNullOrEmpty(referenceGuidsToRemove)) referenceGuidsToRemove = string.Empty; string fullProjectPath = null; string tmpExtension = null; string projectPath = null; try { fullProjectPath = proj.AbsolutePath; tmpExtension = string.Format(CultureInfo.InvariantCulture, ".tmp_{0}_{1}.vcproj", solutionConfiguration.ConfigurationName, solutionConfiguration.PlatformName); projectPath = Path.ChangeExtension(fullProjectPath, tmpExtension); } catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) throw; ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(solution.SolutionFile), "SolutionParseInvalidProjectFileName", proj.RelativePath, e.Message); } // Create the temporary VC project BuildTask createVCProjectTask = target.AddNewTask("CreateTemporaryVCProject"); createVCProjectTask.SetParameterValue("ProjectFile", fullProjectPath, true /* treat as literal */); createVCProjectTask.SetParameterValue("Configuration", projectConfigurationName, true /* treat as literal */); createVCProjectTask.SetParameterValue("OutputProjectFile", projectPath, true /* treat as literal */); createVCProjectTask.SetParameterValue("ReferenceGuids", referenceGuidsToRemove, false /* Contains semicolon-separated list. DO NOT treat as literal */); createVCProjectTask.SetParameterValue("ReferenceAssemblies", string.Format(CultureInfo.InvariantCulture, "@({0})", referenceItemName.ToString()), false /* DO NOT treat as literal */); createVCProjectTask.SetParameterValue("ReferenceImportLibraries", string.Format(CultureInfo.InvariantCulture, "@({0})", importLibraryItemName.ToString()), false /* DO NOT treat as literal */); createVCProjectTask.Condition = GetConditionStringForConfiguration(solutionConfiguration); return projectPath; }
/// <summary> /// Add a call to the ResolveAssemblyReference task to crack the pre-resolved referenced /// assemblies for the complete list of dependencies, PDBs, satellites, etc. The invoke /// the Copy task to copy all these files (or at least the ones that RAR determined should /// be copied local) into the web project's bin directory. /// </summary> /// <param name="target"></param> /// <param name="proj"></param> /// <param name="referenceItemName"></param> /// <param name="conditionDescribingValidConfigurations"></param> /// <owner>RGoel</owner> static private void AddTasksToCopyAllDependenciesIntoBinDir ( Target target, ProjectInSolution proj, string referenceItemName, string conditionDescribingValidConfigurations ) { string copyLocalFilesItemName = referenceItemName + "_CopyLocalFiles"; string destinationFolder = String.Format(CultureInfo.InvariantCulture, @"$({0})\Bin\", GenerateSafePropertyName(proj, "AspNetPhysicalPath")); // This is a bit of a hack. We're actually calling the "Copy" task on all of // the *non-existent* files. Why? Because we want to emit a warning in the // log for each non-existent file, and the Copy task does that nicely for us. // I would have used the <Warning> task except for the fact that we are in // string-resource lockdown. BuildTask copyNonExistentReferencesTask = target.AddNewTask("Copy"); copyNonExistentReferencesTask.SetParameterValue("SourceFiles", "@(" + referenceItemName + "->'%(FullPath)')", false /* Do not treat as literal */); copyNonExistentReferencesTask.SetParameterValue("DestinationFolder", destinationFolder); copyNonExistentReferencesTask.Condition = String.Format(CultureInfo.InvariantCulture, "!Exists('%({0}.Identity)')", referenceItemName); copyNonExistentReferencesTask.ContinueOnError = true; // Call ResolveAssemblyReference on each of the .DLL files that were found on // disk from the .REFRESH files as well as the P2P references. RAR will crack // the dependencies, find PDBs, satellite assemblies, etc., and determine which // files need to be copy-localed. BuildTask rarTask = target.AddNewTask("ResolveAssemblyReference"); rarTask.SetParameterValue("Assemblies", "@(" + referenceItemName + "->'%(FullPath)')", false /* Do not treat as literal */); rarTask.SetParameterValue("TargetFrameworkDirectories", "@(_CombinedTargetFrameworkDirectoriesItem)", false /* Do not treat as literal */); rarTask.SetParameterValue("InstalledAssemblyTables", "@(InstalledAssemblyTables)", false /* Do not treat as literal */); rarTask.SetParameterValue("SearchPaths", "{RawFileName};{TargetFrameworkDirectory};{GAC}"); rarTask.SetParameterValue("FindDependencies", "true"); rarTask.SetParameterValue("FindSatellites", "true"); rarTask.SetParameterValue("FindSerializationAssemblies", "true"); rarTask.SetParameterValue("FindRelatedFiles", "true"); rarTask.Condition = String.Format(CultureInfo.InvariantCulture, "Exists('%({0}.Identity)')", referenceItemName); rarTask.AddOutputItem("CopyLocalFiles", copyLocalFilesItemName); // Copy all the copy-local files (reported by RAR) to the web project's "bin" // directory. BuildTask copyTask = target.AddNewTask("Copy"); copyTask.SetParameterValue("SourceFiles", "@(" + copyLocalFilesItemName + ")", false /* DO NOT treat as literal */); copyTask.SetParameterValue("DestinationFiles", String.Format(CultureInfo.InvariantCulture, @"@({0}->'{1}%(DestinationSubDirectory)%(Filename)%(Extension)')", copyLocalFilesItemName, destinationFolder), false /* DO NOT treat as literal */); copyTask.Condition = conditionDescribingValidConfigurations; }
public void TestAddNewTask1 () { string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='Target' > </Target> </Project> "; engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.LoadXml (documentString); Target[] t = new Target [1]; project.Targets.CopyTo (t, 0); BuildTask bt = t [0].AddNewTask ("Message"); Assert.AreEqual ("Message", bt.Name, "A1"); }
/// <summary> /// This code handles the *.REFRESH files that are in the "bin" subdirectory of /// a web project. These .REFRESH files are just text files that contain absolute or /// relative paths to the referenced assemblies. The goal of these tasks is to /// search all *.REFRESH files and extract fully-qualified absolute paths for /// each of the references. /// </summary> /// <param name="target"></param> /// <param name="proj"></param> /// <param name="referenceItemName"></param> /// <owner>RGoel</owner> static private void AddTasksToResolveAutoRefreshFileReferences ( Target target, ProjectInSolution proj, string referenceItemName ) { string webRoot = "$(" + GenerateSafePropertyName(proj, "AspNetPhysicalPath") + ")"; // Create an item list containing each of the .REFRESH files. BuildTask createItemTask = target.AddNewTask("CreateItem"); createItemTask.SetParameterValue("Include", webRoot + @"\Bin\*.refresh"); createItemTask.AddOutputItem("Include", referenceItemName + "_RefreshFile"); // Read the lines out of each .REFRESH file; they should be paths to .DLLs. Put these paths // into an item list. BuildTask readLinesTask = target.AddNewTask("ReadLinesFromFile"); readLinesTask.SetParameterValue("File", String.Format(CultureInfo.InvariantCulture, @"%({0}_RefreshFile.Identity)", referenceItemName)); readLinesTask.Condition = String.Format(CultureInfo.InvariantCulture, @" '%({0}_RefreshFile.Identity)' != '' ", referenceItemName); readLinesTask.AddOutputItem("Lines", referenceItemName + "_ReferenceRelPath"); // Take those paths and combine them with the root of the web project to form either // an absolute path or a path relative to the .SLN file. These paths can be passed // directly to RAR later. BuildTask combinePathTask = target.AddNewTask("CombinePath"); combinePathTask.SetParameterValue("BasePath", webRoot); combinePathTask.SetParameterValue("Paths", String.Format(CultureInfo.InvariantCulture, @"@({0}_ReferenceRelPath)", referenceItemName)); combinePathTask.AddOutputItem("CombinedPaths", referenceItemName); }
public void TestRemoveTask2 () { string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='Target' > </Target> </Project> "; engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.LoadXml (documentString); Target[] t = new Target [1]; project.Targets.CopyTo (t, 0); t [0].RemoveTask (null); }
public void TestRemoveTask1 () { string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='Target' > <Message Text='text' /> <Warning Text='text' /> </Target> </Project> "; engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.LoadXml (documentString); Target[] t = new Target [1]; project.Targets.CopyTo (t, 0); IEnumerator e = t [0].GetEnumerator (); e.MoveNext (); t [0].RemoveTask ((BuildTask) e.Current); e = t [0].GetEnumerator (); e.MoveNext (); Assert.AreEqual ("Warning", ((BuildTask) e.Current).Name, "A1"); Assert.IsFalse (e.MoveNext (), "A2"); }
/// <summary> /// Adds MSBuild and ResolveVCProjectOutput tasks to a project target to pre-resolve its project references /// </summary> /// <param name="solution"></param> /// <param name="target"></param> /// <param name="proj"></param> /// <param name="solutionConfiguration"></param> /// <param name="outputReferenceItemName"></param> /// <param name="outputImportLibraryItemName"></param> /// <param name="addedReferenceGuids"></param> /// <owner>LukaszG</owner> static private void AddResolveProjectReferenceTasks ( SolutionParser solution, Project msbuildProject, Target target, ProjectInSolution proj, ConfigurationInSolution solutionConfiguration, string outputReferenceItemName, string outputImportLibraryItemName, out string addedReferenceGuids ) { StringBuilder referenceGuids = new StringBuilder(); string message = null; // Suffix for the reference item name. Since we need to attach additional (different) metadata to every // reference item, we need to have helper item lists each with only one item int outputReferenceItemNameSuffix = 0; // Pre-resolve the MSBuild/VC project references foreach (string projectReferenceGuid in proj.ProjectReferences) { ProjectInSolution referencedProject = (ProjectInSolution)solution.ProjectsByGuid[projectReferenceGuid]; ProjectConfigurationInSolution referencedProjectConfiguration = null; if ((referencedProject != null) && (referencedProject.ProjectConfigurations.TryGetValue(solutionConfiguration.FullName, out referencedProjectConfiguration)) && (referencedProjectConfiguration != null)) { string outputReferenceItemNameWithSuffix = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", outputReferenceItemName, outputReferenceItemNameSuffix); bool addCreateItem = false; if ((referencedProject.ProjectType == SolutionProjectType.ManagedProject) || ((referencedProject.ProjectType == SolutionProjectType.Unknown) && (referencedProject.CanBeMSBuildProjectFile(out message)))) { string condition = GetConditionStringForConfiguration(solutionConfiguration); bool specifyProjectToolsVersion = String.Equals(msbuildProject.ToolsVersion, "2.0", StringComparison.OrdinalIgnoreCase) ? false : true; BuildTask msbuildTask = AddMSBuildTaskElement(target, referencedProject.RelativePath, "GetTargetPath", referencedProjectConfiguration.ConfigurationName, referencedProjectConfiguration.PlatformName, specifyProjectToolsVersion); msbuildTask.Condition = condition; msbuildTask.AddOutputItem("TargetOutputs", outputReferenceItemNameWithSuffix); if (referenceGuids.Length > 0) { referenceGuids.Append(';'); } referenceGuids.Append(projectReferenceGuid); addCreateItem = true; } else if (referencedProject.ProjectType == SolutionProjectType.VCProject) { BuildTask vcbuildTask = null; try { vcbuildTask = AddResolveVCProjectOutputTaskElement(target, Path.Combine(solution.SolutionFileDirectory, Path.GetFileName(solution.SolutionFile)), referencedProject.AbsolutePath, referencedProjectConfiguration.FullName); } catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) throw; ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(solution.SolutionFile), "SolutionParseInvalidProjectFileName", referencedProject.RelativePath, e.Message); } vcbuildTask.Condition = GetConditionStringForConfiguration(solutionConfiguration); vcbuildTask.AddOutputItem("ResolvedOutputPaths", outputReferenceItemNameWithSuffix); if (outputImportLibraryItemName != null) { vcbuildTask.AddOutputItem("ResolvedImportLibraryPaths", outputImportLibraryItemName); } if (referenceGuids.Length > 0) { referenceGuids.Append(';'); } referenceGuids.Append(projectReferenceGuid); addCreateItem = true; } // Add create item if either of the conditions above was true. // This merges the one-item item list into the main list, adding the appropriate guid metadata if (addCreateItem) { BuildTask createItemTask = target.AddNewTask("CreateItem"); createItemTask.SetParameterValue("Include", "@(" + outputReferenceItemNameWithSuffix + ")", false /* do not treat as literal */); createItemTask.SetParameterValue("AdditionalMetadata", "Guid=" + projectReferenceGuid, false /* do not treat as literal */); createItemTask.AddOutputItem("Include", outputReferenceItemName); } outputReferenceItemNameSuffix++; } } addedReferenceGuids = referenceGuids.ToString(); }
/// <summary> /// Adds a new ResolveVCProjectOutput task element to the specified target /// </summary> /// <param name="target"></param> /// <param name="solutionPath"></param> /// <param name="projectPath"></param> /// <param name="fullConfigurationName"></param> /// <returns></returns> /// <owner>LukaszG</owner> static private BuildTask AddResolveVCProjectOutputTaskElement ( Target target, string solutionPath, string projectPath, string fullConfigurationName ) { BuildTask newTask = target.AddNewTask("ResolveVCProjectOutput"); newTask.SetParameterValue("ProjectReferences", projectPath, true /* treat as literal */); newTask.SetParameterValue("Configuration", fullConfigurationName, true /* treat as literal */); newTask.SetParameterValue("SolutionFile", solutionPath, true /* treat as literal */); // If the user passed in an override stylesheet for this .VCPROJ (by specifying a global // property called VCBuildOverride), we need to use it to resolve the output path. Override // stylesheets can be used to change the directory that VC projects get built to. newTask.SetParameterValue("Override", "$(VCBuildOverride)"); return newTask; }
/// <summary> /// Adds an MSBuild task to the specified target /// </summary> /// <param name="target"></param> /// <param name="projectPath"></param> /// <param name="msbuildTargetName"></param> /// <param name="configurationName"></param> /// <param name="platformName"></param> /// <returns></returns> /// <owner>RGoel, LukaszG</owner> static private BuildTask AddMSBuildTaskElement ( Target target, string projectPath, string msbuildTargetName, string configurationName, string platformName, bool specifyProjectToolsVersion ) { BuildTask newTask = target.AddNewTask("MSBuild"); newTask.SetParameterValue("Projects", projectPath, true /* treat as literal */); if (msbuildTargetName != null && msbuildTargetName.Length > 0) { newTask.SetParameterValue("Targets", msbuildTargetName); } string additionalProperties = string.Format( CultureInfo.InvariantCulture, "Configuration={0}; Platform={1}; BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)", EscapingUtilities.Escape(configurationName), EscapingUtilities.Escape(platformName) ); newTask.SetParameterValue("Properties", additionalProperties); if (specifyProjectToolsVersion) { newTask.SetParameterValue("ToolsVersion", "$(ProjectToolsVersion)"); newTask.SetParameterValue("UnloadProjectsOnCompletion", "$(UnloadProjectsOnCompletion)"); newTask.SetParameterValue("UseResultsCache", "$(UseResultsCache)"); } return newTask; }
/// <summary> /// Add a new error/warning/message tag into the given target /// </summary> /// <param name="target">Destination target for the tag</param> /// <param name="elementType">Element type to add (Error, Warning, Message)</param> /// <param name="treatAsLiteral">Whether to treat the Text as a literal string or one that contains embedded properties, etc.</param> /// <param name="textResourceName">Resource string name to use in the tag text</param> /// <param name="args">Additional parameters to pass to FormatString</param> /// <owner>LukaszG</owner> static internal BuildTask AddErrorWarningMessageElement(Target target, string elementType, bool treatAsLiteral, string textResourceName, params object[] args) { string code = null; string helpKeyword = null; string text = ResourceUtilities.FormatResourceString(out code, out helpKeyword, textResourceName, args); BuildTask task = target.AddNewTask(elementType); task.SetParameterValue("Text", text, treatAsLiteral); if ((elementType != XMakeElements.message) && (code != null)) { task.SetParameterValue("Code", code, true /* treat as literal */); } if ((elementType != XMakeElements.message) && (helpKeyword != null)) { task.SetParameterValue("HelpKeyword", helpKeyword, true /* treat as literal */); } return task; }