/// <summary> /// Executes this instance. /// </summary> public override bool Execute() { foreach (var projectTaskItem in this.Projects) { var project = new Project(); project.Load(projectTaskItem.ItemSpec); foreach (var projectItem in this.Items) { string itemType = projectItem.GetMetadata("ItemType"); if (string.IsNullOrEmpty(itemType)) { itemType = "None"; } BuildItem newItem = project.AddNewItem(itemType, projectItem.ItemSpec, false); var customMetadata = projectItem.CloneCustomMetadata(); foreach (DictionaryEntry entry in customMetadata) { string value = (string)entry.Value; if (value.Length > 0) { newItem.SetMetadata((string)entry.Key, value); } } } project.Save(projectTaskItem.ItemSpec); } return !this.Log.HasLoggedErrors; }
public override bool Execute() { if (this.ProjectReferences.Length != this.References.Length) { this.Log.LogError("ProjectReferences and References arrays do not have matching lengths."); } foreach (var project in Projects) { Project doc = new Project(); doc.Load(project.ItemSpec); var projectReferences = doc.EvaluatedItems.OfType<BuildItem>().Where(item => item.Name == "ProjectReference"); var matchingReferences = from reference in projectReferences join refToRemove in this.ProjectReferences on reference.Include equals refToRemove.ItemSpec let addIndex = Array.IndexOf(this.ProjectReferences, refToRemove) select new { Remove = reference, Add = this.References[addIndex] }; foreach (var matchingReference in matchingReferences) { this.Log.LogMessage("Removing project reference to \"{0}\" from \"{1}\".", matchingReference.Remove.Include, project.ItemSpec); doc.RemoveItem(matchingReference.Remove); if (matchingReference.Add.ItemSpec != "REMOVE") { this.Log.LogMessage("Adding assembly reference to \"{0}\" to \"{1}\".", matchingReference.Add.ItemSpec, project.ItemSpec); var newReference = doc.AddNewItem("Reference", Path.GetFileNameWithoutExtension(matchingReference.Add.ItemSpec), true); newReference.SetMetadata("HintPath", matchingReference.Add.ItemSpec); } } doc.Save(project.ItemSpec); } return true; }
/// <summary> /// Executes this instance. /// </summary> /// <returns></returns> public override bool Execute() { foreach (ITaskItem projectTaskItem in this.Projects) { this.Log.LogMessage("Fixing up the {0} sample for shipping as source code.", Path.GetFileNameWithoutExtension(projectTaskItem.ItemSpec)); var project = new Project(); Uri projectUri = new Uri(projectTaskItem.GetMetadata("FullPath")); project.Load(projectTaskItem.ItemSpec, ProjectLoadSettings.IgnoreMissingImports); if (this.RemoveImportsStartingWith != null && this.RemoveImportsStartingWith.Length > 0) { project.Imports.Cast<Import>() .Where(import => this.RemoveImportsStartingWith.Any(start => import.ProjectPath.StartsWith(start, StringComparison.OrdinalIgnoreCase))) .ToList() .ForEach(import => project.Imports.RemoveImport(import)); } if (this.AddReferences != null) { foreach (var reference in this.AddReferences) { BuildItem item = project.AddNewItem("Reference", reference.ItemSpec); foreach (DictionaryEntry metadata in reference.CloneCustomMetadata()) { item.SetMetadata((string)metadata.Key, (string)metadata.Value); } } } project.Save(projectTaskItem.ItemSpec); } return !this.Log.HasLoggedErrors; }
/// <summary> /// Executes this instance. /// </summary> public override bool Execute() { foreach (ITaskItem taskItem in this.Projects) { switch (GetClassification(taskItem)) { case ProjectClassification.VS2010Project: this.Log.LogMessage(MessageImportance.Low, "Downgrading project \"{0}\".", taskItem.ItemSpec); Project project = new Project(); project.Load(taskItem.ItemSpec); project.DefaultToolsVersion = "3.5"; if (this.DowngradeMvc2ToMvc1) { string projectTypeGuids = project.GetEvaluatedProperty("ProjectTypeGuids"); if (!string.IsNullOrEmpty(projectTypeGuids)) { projectTypeGuids = projectTypeGuids.Replace("{F85E285D-A4E0-4152-9332-AB1D724D3325}", "{603c0e0b-db56-11dc-be95-000d561079b0}"); project.SetProperty("ProjectTypeGuids", projectTypeGuids); } } // Web projects usually have an import that includes these substrings foreach (Import import in project.Imports) { import.ProjectPath = import.ProjectPath .Replace("$(MSBuildExtensionsPath32)", "$(MSBuildExtensionsPath)") .Replace("VisualStudio\\v10.0", "VisualStudio\\v9.0"); } // VS2010 won't let you have a System.Core reference, but VS2008 requires it. BuildItemGroup references = project.GetEvaluatedItemsByName("Reference"); if (!references.Cast<BuildItem>().Any(item => item.FinalItemSpec.StartsWith("System.Core", StringComparison.OrdinalIgnoreCase))) { project.AddNewItem("Reference", "System.Core"); } project.Save(taskItem.ItemSpec); break; case ProjectClassification.VS2010Solution: this.Log.LogMessage(MessageImportance.Low, "Downgrading solution \"{0}\".", taskItem.ItemSpec); string[] contents = File.ReadAllLines(taskItem.ItemSpec); if (contents[1] != "Microsoft Visual Studio Solution File, Format Version 11.00" || contents[2] != "# Visual Studio 2010") { this.Log.LogError("Unrecognized solution file header in \"{0}\".", taskItem.ItemSpec); break; } contents[1] = "Microsoft Visual Studio Solution File, Format Version 10.00"; contents[2] = "# Visual Studio 2008"; for (int i = 3; i < contents.Length; i++) { contents[i] = contents[i].Replace("TargetFrameworkMoniker = \".NETFramework,Version%3Dv", "TargetFramework = \""); } File.WriteAllLines(taskItem.ItemSpec, contents); break; default: this.Log.LogWarning("Unrecognized project type for \"{0}\".", taskItem.ItemSpec); break; } } return !this.Log.HasLoggedErrors; }
public override bool Execute() { foreach (var project in Projects) { Project doc = new Project(); doc.Load(project.ItemSpec); var projectReference = doc.EvaluatedItems.OfType<BuildItem>().Where( item => item.Name == "ProjectReference" && item.Include == ProjectReference).Single(); doc.RemoveItem(projectReference); var newReference = doc.AddNewItem("Reference", Path.GetFileNameWithoutExtension(Reference)); newReference.SetMetadata("HintPath", Reference); doc.Save(project.ItemSpec); } return true; }
public override bool Execute() { if (this.ProjectReferences.Length != this.References.Length) { this.Log.LogError("ProjectReferences and References arrays do not have matching lengths."); this.Log.LogError("ProjectReferences contents ({0} elements): {1}", this.ProjectReferences.Length, String.Join<ITaskItem>(";", this.ProjectReferences)); this.Log.LogError("References contents ({0} elements): {1}", this.References.Length, String.Join<ITaskItem>(";", this.References)); return false; } foreach (var project in Projects) { Project doc = new Project(); doc.Load(project.ItemSpec, ProjectLoadSettings.IgnoreMissingImports); var projectReferences = doc.EvaluatedItems.OfType<BuildItem>().Where(item => item.Name == "ProjectReference"); var matchingReferences = from reference in projectReferences join refToRemove in this.ProjectReferences on reference.Include equals refToRemove.ItemSpec let addIndex = Array.IndexOf(this.ProjectReferences, refToRemove) select new { Remove = reference, Add = this.References[addIndex] }; foreach (var matchingReference in matchingReferences) { this.Log.LogMessage("Removing project reference to \"{0}\" from \"{1}\".", matchingReference.Remove.Include, project.ItemSpec); doc.RemoveItem(matchingReference.Remove); if (matchingReference.Add.ItemSpec != "REMOVE") { this.Log.LogMessage("Adding assembly reference to \"{0}\" to \"{1}\".", matchingReference.Add.ItemSpec, project.ItemSpec); string newItemSpec = Path.GetFileNameWithoutExtension(matchingReference.Add.ItemSpec); if (!doc.GetEvaluatedItemsByName("Reference").OfType<BuildItem>().Any(bi => String.Equals(bi.Include, newItemSpec, StringComparison.OrdinalIgnoreCase))) { var newReference = doc.AddNewItem("Reference", newItemSpec, true); newReference.SetMetadata("HintPath", matchingReference.Add.ItemSpec); } } } doc.Save(project.ItemSpec); } return true; }
public override void AddNewItem(Project project, string name, string include) { project.AddNewItem(name, include); }
/// <summary> /// Executes this instance. /// </summary> public override bool Execute() { var newProjectToOldProjectMapping = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); var createdProjectFiles = new List<TaskItem>(); foreach (ITaskItem taskItem in this.Projects) { switch (GetClassification(taskItem)) { case ProjectClassification.VS2010Project: case ProjectClassification.VS2010Solution: string projectNameForVS2008 = InPlaceDowngrade ? taskItem.ItemSpec : Path.Combine( Path.GetDirectoryName(taskItem.ItemSpec), Path.GetFileNameWithoutExtension(taskItem.ItemSpec) + "-vs2008" + Path.GetExtension(taskItem.ItemSpec)); newProjectToOldProjectMapping[taskItem.ItemSpec] = projectNameForVS2008; break; } } foreach (ITaskItem taskItem in this.Projects) { switch (GetClassification(taskItem)) { case ProjectClassification.VS2010Project: this.Log.LogMessage(MessageImportance.Low, "Downgrading project \"{0}\".", taskItem.ItemSpec); var project = new Project(); project.Load(taskItem.ItemSpec, ProjectLoadSettings.IgnoreMissingImports); project.DefaultToolsVersion = "3.5"; if (this.DowngradeMvc2ToMvc1) { string projectTypeGuids = project.GetEvaluatedProperty("ProjectTypeGuids"); if (!string.IsNullOrEmpty(projectTypeGuids)) { projectTypeGuids = projectTypeGuids.Replace("{F85E285D-A4E0-4152-9332-AB1D724D3325}", "{603c0e0b-db56-11dc-be95-000d561079b0}"); project.SetProperty("ProjectTypeGuids", projectTypeGuids); } } // MSBuild v3.5 doesn't support the GetDirectoryNameOfFileAbove function var enlistmentInfoImports = project.Imports.Cast<Import>().Where(i => i.ProjectPath.IndexOf("[MSBuild]::GetDirectoryNameOfFileAbove", StringComparison.OrdinalIgnoreCase) >= 0); enlistmentInfoImports.ToList().ForEach(i => project.Imports.RemoveImport(i)); // Web projects usually have an import that includes these substrings));) foreach (Import import in project.Imports) { import.ProjectPath = import.ProjectPath .Replace("$(MSBuildExtensionsPath32)", "$(MSBuildExtensionsPath)") .Replace("VisualStudio\\v10.0", "VisualStudio\\v9.0"); } // VS2010 won't let you have a System.Core reference, but VS2008 requires it. BuildItemGroup references = project.GetEvaluatedItemsByName("Reference"); if (!references.Cast<BuildItem>().Any(item => item.FinalItemSpec.StartsWith("System.Core", StringComparison.OrdinalIgnoreCase))) { project.AddNewItem("Reference", "System.Core"); } // Rewrite ProjectReferences to other renamed projects. BuildItemGroup projectReferences = project.GetEvaluatedItemsByName("ProjectReference"); foreach (var mapping in newProjectToOldProjectMapping) { string oldName = Path.GetFileName(mapping.Key); string newName = Path.GetFileName(mapping.Value); foreach (BuildItem projectReference in projectReferences) { projectReference.Include = Regex.Replace(projectReference.Include, oldName, newName, RegexOptions.IgnoreCase); } } project.Save(newProjectToOldProjectMapping[taskItem.ItemSpec]); createdProjectFiles.Add(new TaskItem(taskItem) { ItemSpec = newProjectToOldProjectMapping[taskItem.ItemSpec] }); break; case ProjectClassification.VS2010Solution: this.Log.LogMessage(MessageImportance.Low, "Downgrading solution \"{0}\".", taskItem.ItemSpec); string[] contents = File.ReadAllLines(taskItem.ItemSpec); if (contents[1] != "Microsoft Visual Studio Solution File, Format Version 11.00" || contents[2] != "# Visual Studio 2010") { this.Log.LogError("Unrecognized solution file header in \"{0}\".", taskItem.ItemSpec); break; } contents[1] = "Microsoft Visual Studio Solution File, Format Version 10.00"; contents[2] = "# Visual Studio 2008"; for (int i = 3; i < contents.Length; i++) { contents[i] = contents[i].Replace("TargetFrameworkMoniker = \".NETFramework,Version%3Dv", "TargetFramework = \""); } foreach (var mapping in newProjectToOldProjectMapping) { string oldName = Path.GetFileName(mapping.Key); string newName = Path.GetFileName(mapping.Value); for (int i = 0; i < contents.Length; i++) { contents[i] = Regex.Replace(contents[i], oldName, newName, RegexOptions.IgnoreCase); } } File.WriteAllLines(newProjectToOldProjectMapping[taskItem.ItemSpec], contents); createdProjectFiles.Add(new TaskItem(taskItem) { ItemSpec = newProjectToOldProjectMapping[taskItem.ItemSpec] }); break; default: this.Log.LogWarning("Unrecognized project type for \"{0}\".", taskItem.ItemSpec); break; } } if (InPlaceDowngrade) { this.DowngradedProjects = new ITaskItem[0]; } else { this.DowngradedProjects = createdProjectFiles.ToArray(); } return !this.Log.HasLoggedErrors; }
/// <summary> /// Creates a temporary MSBuild content project in memory. /// </summary> void CreateBuildProject() { string projectPath = Path.Combine(buildDirectory, "content.contentproj"); string outputPath = Path.Combine(buildDirectory, "bin"); // Create the build engine. msBuildEngine = new Engine(RuntimeEnvironment.GetRuntimeDirectory()); // Hook up our custom error logger. errorLogger = new ErrorLogger(); msBuildEngine.RegisterLogger(errorLogger); // Create the build project. msBuildProject = new Project(msBuildEngine); msBuildProject.FullFileName = projectPath; msBuildProject.SetProperty("XnaPlatform", "Windows"); msBuildProject.SetProperty("XnaFrameworkVersion", "v2.0"); msBuildProject.SetProperty("Configuration", "Release"); msBuildProject.SetProperty("OutputPath", outputPath); // Register any custom importers or processors. foreach (string pipelineAssembly in pipelineAssemblies) { msBuildProject.AddNewItem("Reference", pipelineAssembly); } // Include the standard targets file that defines // how to build XNA Framework content. msBuildProject.AddNewImport("$(MSBuildExtensionsPath)\\Microsoft\\XNA " + "Game Studio\\v3.1\\Microsoft.Xna.GameStudio" + ".ContentPipeline.targets", null); }
public void RemoveEvaluatedItemAfterExpansionFails() { try { CompatibilityTestHelpers.CreateFiles(2, "foo", "foo", ObjectModelHelpers.TempProjectDir); Project p = new Project(); object o = p.EvaluatedItems; // this causes failure p.AddNewItem("foos", Path.Combine(ObjectModelHelpers.TempProjectDir, "*.foo")); p.RemoveItem(p.EvaluatedItems[0]); // Exception thrown here Assertion.Fail("success as failure"); // should not get here due to exception above } catch (Exception e) { // ExpectedException cannot be asserted as InternalErrorExceptions are internally scoped. Assertion.AssertEquals(true, e.GetType().ToString().Contains("InternalErrorException")); } finally { CompatibilityTestHelpers.CleanupDirectory(ObjectModelHelpers.TempProjectDir); } }
/// <summary> /// �ꎞ MSBuild �R���e���c �v���W�F�N�g��������[��ɍ쐬���܂��B /// </summary> void CreateBuildProject() { string projectPath = Path.Combine(buildDirectory, "content.contentproj"); string outputPath = Path.Combine(buildDirectory, "bin"); // �r���h �G���W����쐬���܂��B msBuildEngine = new Engine(RuntimeEnvironment.GetRuntimeDirectory()); // �J�X�^�� �G���[ ���K�[��o�^���܂��B errorLogger = new ErrorLogger(); msBuildEngine.RegisterLogger(errorLogger); // �r���h �v���W�F�N�g��쐬���܂��B msBuildProject = new Project(msBuildEngine); msBuildProject.FullFileName = projectPath; msBuildProject.SetProperty("XnaPlatform", "Windows"); msBuildProject.SetProperty("XnaFrameworkVersion", "v2.0"); msBuildProject.SetProperty("Configuration", "Release"); msBuildProject.SetProperty("OutputPath", outputPath); // �J�X�^�� �C���|�[�^�[�܂��̓v���Z�b�T��o�^���܂��B foreach (string pipelineAssembly in pipelineAssemblies) { msBuildProject.AddNewItem("Reference", pipelineAssembly); } // XNA Framework �R���e���c�̃r���h���@���`����W���^�[�Q�b�g �t�@�C����܂߂܂��B msBuildProject.AddNewImport("$(MSBuildExtensionsPath)\\Microsoft\\XNA " + "Game Studio\\v3.0\\Microsoft.Xna.GameStudio" + ".ContentPipeline.targets", null); }
public void AddNewItemName_Null() { Project p = new Project(); p.AddNewItem(null, "include"); }
public void RemoveItem_IsNotImported() { Project p = new Project(); Project i = new Project(p.ParentEngine); BuildItem buildItem = i.AddNewItem("n", "i"); p.RemoveItem(buildItem); }
public void AddNewItemName_Empty() { Project p = new Project(); p.AddNewItem(String.Empty, "include"); }
public void RemoveItem() { Project p = new Project(); BuildItem buildItem1 = p.AddNewItem("n", "i", true); Assertion.AssertNotNull(CompatibilityTestHelpers.FindBuildItem(p, "n")); p.RemoveItem(buildItem1); Assertion.AssertNull(CompatibilityTestHelpers.FindBuildItem(p, "n")); }
public void RemoveItem_null() { Project p = new Project(); p.AddNewItem("n", "i", true); BuildItem buildItem1 = null; p.RemoveItem(buildItem1); }
public void RemoveEvaluatedItemAfterExpansionSuccess() { try { int numberOfFoos = 5; CompatibilityTestHelpers.CreateFiles(numberOfFoos, "foo", "foo", ObjectModelHelpers.TempProjectDir); CompatibilityTestHelpers.CreateFiles(1, "bar", "bar", ObjectModelHelpers.TempProjectDir); Project p = new Project(); p.AddNewItem("foos", Path.Combine(ObjectModelHelpers.TempProjectDir, "*.foo")); p.RemoveItem(p.EvaluatedItems[0]); Assertion.AssertEquals(true, p.EvaluatedItems[0].Include.Contains("foo1.foo")); Assertion.AssertEquals(numberOfFoos - 1, p.EvaluatedItems.Count); } finally { CompatibilityTestHelpers.CleanupDirectory(ObjectModelHelpers.TempProjectDir); } }
public void RemoveEvaluatedItemDelimitedSuccess() { try { CompatibilityTestHelpers.CreateFiles(1, "foo", "foo", ObjectModelHelpers.TempProjectDir); Project p = new Project(); p.AddNewItem("foos", Path.Combine(ObjectModelHelpers.TempProjectDir, "foo.foo,bar.bar")); p.RemoveItem(p.EvaluatedItems[0]); Assertion.AssertEquals(0, p.EvaluatedItems.Count); } finally { CompatibilityTestHelpers.CleanupDirectory(ObjectModelHelpers.TempProjectDir); } }
public void RemoveEvaluatedItemDelimtedFails() { try { CompatibilityTestHelpers.CreateFiles(1, "foo", "foo", ObjectModelHelpers.TempProjectDir); Project p = new Project(); object o = p.EvaluatedItems; // this causes the failure p.AddNewItem("foos", Path.Combine(ObjectModelHelpers.TempProjectDir, "foo.foo;bar.bar")); p.RemoveItem(p.EvaluatedItems[0]); // Exception thrown here Assertion.Fail("success as failure"); // should not get here due to exception above } catch (Exception e) { if (!(e.GetType().ToString().Contains("InternalErrorException"))) { Assertion.Fail(e.Message + " was thrown"); } else { Assertion.Assert("InternalErrorException was thrown", true); } } finally { CompatibilityTestHelpers.CleanupDirectory(ObjectModelHelpers.TempProjectDir); } }
public void AddNewItemInclude_Empty() { Project p = new Project(); p.AddNewItem("include", String.Empty); }
public void RemoveItemDirtyAfterRemove() { string projectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("save.proj", String.Empty); try { Project p = new Project(); BuildItem buildItem = p.AddNewItem("n", "i"); p.Save(projectPath); Assertion.AssertEquals(false, p.IsDirty); p.RemoveItem(buildItem); Assertion.AssertEquals(true, p.IsDirty); } finally { CompatibilityTestHelpers.RemoveFile(projectPath); } }
public override void SaveTo(Uri location) { var projectPath = location.LocalPath; var projectDir = Path.GetDirectoryName(projectPath); var msBuildProject = new MsBuild.Project(); msBuildProject.DefaultToolsVersion = "4.0"; msBuildProject.DefaultTargets = "Build"; var propertyGroup = msBuildProject.AddNewPropertyGroup(false); propertyGroup.AddNewProperty("ProjectGuid", ProjectGuid.ToString("B").ToUpper()); propertyGroup.AddNewProperty("Configuration", "Debug"); propertyGroup.AddNewProperty("Platform", "x86"); propertyGroup.AddNewProperty("OutputType", "Library"); propertyGroup.AddNewProperty("RootNamespace", "VVVV.Nodes"); propertyGroup.AddNewProperty("AssemblyName", AssemblyName); propertyGroup.AddNewProperty("TargetFrameworkVersion", "v4.0"); propertyGroup.AddNewProperty("OutputPath", "bin\\Debug\\"); propertyGroup.AddNewProperty("DebugSymbols", "True"); propertyGroup.AddNewProperty("DebugType", "Full"); propertyGroup.AddNewProperty("Optimize", "False"); propertyGroup.AddNewProperty("CheckForOverflowUnderflow", "True"); propertyGroup.AddNewProperty("DefineConstants", "DEBUG;TRACE"); propertyGroup.AddNewProperty("AllowUnsafeBlocks", "True"); //add loaded reference paths var expandedVVVV45Path = msBuildProject.GetEvaluatedProperty("ReferencePath"); foreach (var refPath in ReferencePaths) { if (refPath != expandedVVVV45Path) { if (Path.IsPathRooted(refPath)) { propertyGroup.AddNewProperty("ReferencePath", PathUtils.MakeRelativePath(projectDir + @"\", refPath + @"\")); } else { propertyGroup.AddNewProperty("ReferencePath", refPath); } } } msBuildProject.AddNewImport("$(MSBuildBinPath)\\Microsoft.CSharp.Targets", null); //add reference items foreach (var reference in References) { var item = msBuildProject.AddNewItem("Reference", reference.Name); if (!reference.IsGlobal && !InReferencePaths(reference.Name)) { var hintPath = reference.GetRelativePath(); item.SetMetadata("HintPath", hintPath); } } foreach (var document in Documents) { msBuildProject.AddNewItem(document.CanBeCompiled ? "Compile" : "None", document.GetRelativePath()); } // Create the project directory if it doesn't exist yet. if (!Directory.Exists(projectDir)) { Directory.CreateDirectory(projectDir); } msBuildProject.Save(projectPath); base.SaveTo(location); }
public void EvaluatedItemsClonedReturns() { Project p = new Project(); p.AddNewItem("n", "v"); BuildItemGroup group1 = p.EvaluatedItems; Assertion.AssertEquals(true, p.IsDirty); BuildItemGroup group2 = p.EvaluatedItems; Assertion.AssertEquals(false, Object.ReferenceEquals(group1, group2)); }
public void AddFileToContentProject(String filename, bool shouldCompile, bool copyToOuputFolder, String processor, String importer) { try { foreach (var item in _currentProject.VSProj.EvaluatedItems) { if (item is Microsoft.Build.BuildEngine.BuildItem) { BuildItem buildItem = (BuildItem)item; if (buildItem.Name == "NestedContentProject") { string _name = buildItem.Include; _name = Path.Combine(_currentProject.Path, _name); Project p = new Project(); p.Load(_name); string _root = Path.GetDirectoryName(buildItem.Include); String action = "None"; if (shouldCompile == true) { action = "Compile"; } BuildItemGroup grp = p.GetEvaluatedItemsByName(action); string include = filename.Replace(_root, "").Replace("/", "\\"); if (include.StartsWith("\\")) { include = include.Substring(1); } bool found = false; foreach (BuildItem item2 in grp) { if (item2.Include == include) { found = true; break; } } if (found == false) { BuildItem item1 = p.AddNewItem(action, include); item1.SetMetadata("Name", Path.GetFileNameWithoutExtension(filename)); if (copyToOuputFolder == true) { item1.SetMetadata("CopyToOutputDirectory", "PreserveNewest"); } if (String.IsNullOrEmpty(importer) == false) { item1.SetMetadata("Importer", importer); } if (String.IsNullOrEmpty(processor) == false) { item1.SetMetadata("Processor", processor); } p.Save(_name); } p = null; } } } } catch (Exception err) { ShowErrorMessage(err); } }
public void GetEvaluatedItemsByNameIgnoringCondition() { Project p = new Project(); string name = "new"; BuildItem buildItem = p.AddNewItem(name, "i1"); p.AddNewItem(name, "i2"); p.SetProperty("condition", "false"); buildItem.Condition = "$(condition)"; BuildItemGroup foundGroup = p.GetEvaluatedItemsByNameIgnoringCondition(name); Assertion.AssertEquals(2, foundGroup.Count); }
/// <summary> /// Creates a temporary MSBuild content project in memory. /// </summary> void CreateBuildProject() { string projectPath = Path.Combine(buildDirectory, "content.contentproj"); string outputPath = Path.Combine(buildDirectory, "bin"); // Create the build engine. msBuildEngine = new Engine(); // Hook up our custom error logger. errorLogger = new ErrorLogger(); msBuildEngine.RegisterLogger(errorLogger); msBuildEngine.DefaultToolsVersion = "3.5"; // Create the build project. msBuildProject = new Project(msBuildEngine); msBuildProject.FullFileName = projectPath; msBuildProject.SetProperty("XnaPlatform", "Windows"); msBuildProject.SetProperty("XnaFrameworkVersion", "v3.1"); msBuildProject.SetProperty("Configuration", "Release"); msBuildProject.SetProperty("OutputPath", outputPath); // Register any custom importers or processors. foreach (string pipelineAssembly in pipelineAssemblies) { msBuildProject.AddNewItem("Reference", pipelineAssembly); } // Reference SkinnedModelPipeline. string applicationDirectory = AppDomain.CurrentDomain.BaseDirectory; string dllPath = Path.Combine(applicationDirectory, "SkinnedModelPipeline.dll"); string importDll = Path.GetFullPath(dllPath); this.msBuildProject.AddNewItem("Reference", importDll); // Include the standard targets file that defines // how to build XNA Framework content. msBuildProject.AddNewImport("$(MSBuildExtensionsPath)\\Microsoft\\XNA " + "Game Studio\\v3.1\\Microsoft.Xna.GameStudio" + ".ContentPipeline.targets", null); }
public void RemoveAllItemGroupsDirtyAfterRemove() { Project p = new Project(); p.AddNewItem("item", "i"); Assertion.AssertEquals(1, p.ItemGroups.Count); p.RemoveAllItemGroups(); Assertion.AssertEquals(0, p.ItemGroups.Count); }
//===================================================================== /// <summary> /// Call this method to perform the build on the project. /// </summary> /// <event cref="BuildStepChanged">This event fires when the /// current build step changes.</event> /// <event cref="BuildProgress">This event fires to report progress /// information.</event> public void Build() { Project msBuildProject; BuildItem buildItem; Version v; string helpFile, languageFile, scriptFile, message = null; int waitCount; System.Diagnostics.Debug.WriteLine("Build process starting\r\n"); try { Assembly asm = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location); this.ReportProgress(BuildStep.Initializing, "[{0}, version {1}]", fvi.ProductName, fvi.ProductVersion); buildStart = stepStart = DateTime.Now; msBuildExePath = Path.Combine(Engine.GlobalEngine.Toolsets[ project.MSBuildProject.ToolsVersion].ToolsPath, "MSBuild.exe"); // Base folder for SHFB shfbFolder = Path.GetDirectoryName(asm.Location) + @"\"; // Get the location of the template files templateFolder = shfbFolder + @"Templates\"; // Get the location of the web files webFolder = shfbFolder + @"\Web\"; // Make sure we start out in the project's output folder // in case the output folder is relative to it. projectFolder = Path.GetDirectoryName(originalProjectName); if(projectFolder.Length == 0) projectFolder = Directory.GetCurrentDirectory(); projectFolder += @"\"; Directory.SetCurrentDirectory(projectFolder); this.ReportProgress("Creating output and working folders..."); outputFolder = project.OutputPath; if(String.IsNullOrEmpty(outputFolder)) outputFolder = Directory.GetCurrentDirectory(); else outputFolder = Path.GetFullPath(outputFolder); if(!Directory.Exists(outputFolder)) Directory.CreateDirectory(outputFolder); if(outputFolder[outputFolder.Length - 1] != '\\') outputFolder += @"\"; // Create the log file. The log may be in a folder other than // the output so make sure it exists too. if(!Directory.Exists(Path.GetDirectoryName(this.LogFilename))) Directory.CreateDirectory(Path.GetDirectoryName(this.LogFilename)); swLog = new StreamWriter(this.LogFilename); swLog.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "\r\n<shfbBuild product=\"{0}\" version=\"{1}\" " + "projectFile=\"{2}\" started=\"{3}\">\r\n" + "<buildStep step=\"{4}\">", fvi.ProductName, fvi.ProductVersion, originalProjectName, DateTime.Now, BuildStep.Initializing); if(project.WorkingPath.Path.Length == 0) workingFolder = outputFolder + @"Working\"; else workingFolder = project.WorkingPath; if((project.HelpFileFormat & HelpFileFormat.Website) != 0) BuildProcess.VerifySafePath("OutputPath", outputFolder, projectFolder); // The output folder and the working folder cannot be the same if(workingFolder == outputFolder) throw new BuilderException("BE0030", "The OutputPath and " + "WorkingPath properties cannot be set to the same path"); // For MS Help 2, the HTML Help Name cannot contain spaces if((project.HelpFileFormat & HelpFileFormat.MSHelp2) != 0 && project.HtmlHelpName.IndexOf(' ') != -1) throw new BuilderException("BE0031", "For MS Help 2 " + "builds, the HtmlHelpName property cannot contain " + "spaces as they are not valid in the collection name."); // Check for the SHFBROOT environment variable. It may not be // present yet if a reboot hasn't occurred after installation. // In such cases, set it to the proper folder for this process // so that projects can be loaded and built. if(Environment.GetEnvironmentVariable("SHFBROOT") == null) { // We won't issue a warning since it may not be defined // in some build environments such as on a build server. // In such cases, it is passed in as a command line // option to MSBuild. Storing it in the environment here // lets the SHFB build projects work as expected. this.ReportProgress("The SHFBROOT system environment variable was " + "not found. This variable is usually created during installation " + "and may require a reboot. It has been defined temporarily " + "for this process as: SHFBROOT={0}", shfbFolder); Environment.SetEnvironmentVariable("SHFBROOT", shfbFolder); } if(project.PlugInConfigurations.Count != 0) this.LoadPlugIns(); this.ExecutePlugIns(ExecutionBehaviors.After); try { if(Directory.Exists(workingFolder)) { // Clear any data from a prior run this.ReportProgress(BuildStep.ClearWorkFolder, "Clearing working folder..."); BuildProcess.VerifySafePath("WorkingPath", workingFolder, projectFolder); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); try { Directory.Delete(workingFolder, true); } catch(IOException ioEx) { this.ReportProgress(" Not all prior output was removed from '{0}': {1}", workingFolder, ioEx.Message); } catch(UnauthorizedAccessException uaEx) { this.ReportProgress(" Not all prior output was removed from '{0}': {1}", workingFolder, uaEx.Message); } this.ExecutePlugIns(ExecutionBehaviors.After); } } // If the help file is open, it will fail to build so try // to get rid of it now before we get too far into it. helpFile = outputFolder + project.HtmlHelpName + ".chm"; if((project.HelpFileFormat & HelpFileFormat.HtmlHelp1) != 0 && File.Exists(helpFile)) File.Delete(helpFile); helpFile = Path.ChangeExtension(helpFile, ".hxs"); if((project.HelpFileFormat & HelpFileFormat.MSHelp2) != 0 && File.Exists(helpFile)) File.Delete(helpFile); helpFile = Path.ChangeExtension(helpFile, ".mshc"); if((project.HelpFileFormat & HelpFileFormat.MSHelpViewer) != 0 && File.Exists(helpFile)) File.Delete(helpFile); if((project.HelpFileFormat & HelpFileFormat.Website) != 0) { helpFile = outputFolder + "Index.aspx"; if(File.Exists(helpFile)) File.Delete(helpFile); helpFile = Path.ChangeExtension(helpFile, ".html"); if(File.Exists(helpFile)) File.Delete(helpFile); } } catch(IOException ex) { throw new BuilderException("BE0025", "Unable to remove prior build output: " + ex.Message); } catch { throw; } Directory.CreateDirectory(workingFolder); // Make sure we can find the tools this.FindTools(); if(!Directory.Exists(sandcastleFolder + @"Data\Reflection")) throw new BuilderException("BE0032", "Reflection data files do not exist yet"); // Make sure the HelpFileVersion property is in the form of // a real version number. try { if(project.HelpFileVersion.IndexOf('{') == -1) v = new Version(project.HelpFileVersion); else v = new Version(this.TransformText(project.HelpFileVersion)); if(v.Build == -1 || v.Revision == -1) throw new FormatException("The version number must specify all four parts. " + "Specify zero for unused parts."); } catch(Exception ex) { throw new BuilderException("BE0066", "The HelpFileVersion property value '" + project.HelpFileVersion + "' is not in the correct format (#.#.#.#)", ex); } this.GarbageCollect(); // Validate the documentation source information, gather // assembly and reference info, and copy XML comments files // to the working folder. this.ValidateDocumentationSources(); // Transform the shared builder content files language = project.Language; languageFile = "SharedBuilderContent_" + language.Name + ".xml"; this.ReportProgress(BuildStep.GenerateSharedContent, "Generating shared content files ({0}, {1})...", language.Name, language.DisplayName); // First we need to figure out which style is in effect. // Base it on whether the presentation style folder contains // "v2005", "hana", or "prototype". presentationParam = project.PresentationStyle.ToLower(CultureInfo.InvariantCulture); if(presentationParam.IndexOf("vs2005", StringComparison.Ordinal) != -1) presentationParam = "vs2005"; else if(presentationParam.IndexOf("hana", StringComparison.Ordinal) != -1) presentationParam = "hana"; else { if(presentationParam.IndexOf("prototype", StringComparison.Ordinal) == -1) this.ReportWarning("BE0001", "Unable to determine presentation style from folder " + "'{0}'. Assuming Prototype style.", project.PresentationStyle); presentationParam = "prototype"; } if(!File.Exists(templateFolder + @"..\SharedContent\" + languageFile)) { languageFile = "SharedBuilderContent_en-US.xml"; // Warn the user about the default being used this.ReportWarning("BE0002", "Shared builder content " + "for the '{0}, {1}' language could not be found. " + "Using 'en-US, English (US)' defaults.", language.Name, language.DisplayName); } // See if the user has translated the Sandcastle resources. // If not found, default to US English. languageFolder = presentationFolder + @"\Content\" + language.Name; if(Directory.Exists(languageFolder)) languageFolder = language.Name + @"\"; else { // Warn the user about the default being used. The // language will still be used for the help file though. if(language.Name != "en-US") this.ReportWarning("BE0003", "Sandcastle shared " + "content for the '{0}, {1}' language could not " + "be found. Using 'en-US, English (US)' " + "defaults.", language.Name, language.DisplayName); languageFolder = String.Empty; } if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); this.TransformTemplate(languageFile, templateFolder + @"..\SharedContent\", workingFolder); File.Move(workingFolder + languageFile, workingFolder + "SharedBuilderContent.xml"); // Presentation-style specific shared content languageFile = languageFile.Replace("Shared", presentationParam); this.TransformTemplate(languageFile, templateFolder + @"..\SharedContent\", workingFolder); File.Move(workingFolder + languageFile, workingFolder + "PresentationStyleBuilderContent.xml"); // Copy the stop word list languageFile = Path.ChangeExtension(languageFile.Replace(presentationParam + "BuilderContent", "StopWordList"), ".txt"); File.Copy(templateFolder + @"..\SharedContent\" + languageFile, workingFolder + "StopWordList.txt"); File.SetAttributes(workingFolder + "StopWordList.txt", FileAttributes.Normal); this.ExecutePlugIns(ExecutionBehaviors.After); } // Generate the API filter used by MRefBuilder this.GenerateApiFilter(); // Generate the reflection information this.ReportProgress(BuildStep.GenerateReflectionInfo, "Generating reflection information..."); reflectionFile = workingFolder + "reflection.org"; if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.TransformTemplate("MRefBuilder.config", templateFolder, workingFolder); scriptFile = this.TransformTemplate("GenerateRefInfo.proj", templateFolder, workingFolder); msBuildProject = new Project(Engine.GlobalEngine); msBuildProject.Load(scriptFile); // Add the references foreach(BuildItem item in referenceDictionary.Values) { buildItem = msBuildProject.AddNewItem(item.Name, item.Include); item.CopyCustomMetadataTo(buildItem); } // Add the assemblies to document foreach(string assemblyName in assembliesList) buildItem = msBuildProject.AddNewItem("Assembly", assemblyName); msBuildProject.Save(scriptFile); this.ExecutePlugIns(ExecutionBehaviors.Before); this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m GenerateRefInfo.proj"); this.ExecutePlugIns(ExecutionBehaviors.After); } reflectionInfo = new XmlDocument(); reflectionInfo.Load(reflectionFile); apisNode = reflectionInfo.SelectSingleNode("reflection/apis"); // Generate namespace summary information this.GenerateNamespaceSummaries(); // Remove unwanted items from the reflection information file this.ApplyVisibilityProperties(); // If there is nothing to document, stop the build if(apisNode.ChildNodes.Count == 0) throw new BuilderException("BE0033", "No APIs found to " + "document. See error topic in help file for details."); reflectionInfo = null; apisNode = null; // If this was a partial build used to obtain API information, // stop now. if(isPartialBuild) { commentsFiles.Save(); goto AllDone; // Yeah, I know it's evil but it's quick } // Expand <inheritdoc /> tags? if(commentsFiles.ContainsInheritedDocumentation) { commentsFiles.Save(); // Transform the reflection output. this.ReportProgress(BuildStep.GenerateInheritedDocumentation, "Generating inherited documentation..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.TransformTemplate("GenerateInheritedDocs.config", templateFolder, workingFolder); scriptFile = this.TransformTemplate("GenerateInheritedDocs.proj", templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.Before); this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m GenerateInheritedDocs.proj"); this.ExecutePlugIns(ExecutionBehaviors.After); } // This should always be last so that it overrides comments in the project XML comments files commentsFiles.Add(new XmlCommentsFile(workingFolder + "_InheritedDocs_.xml")); } this.GarbageCollect(); // Transform the reflection output. this.ReportProgress(BuildStep.TransformReflectionInfo, "Transforming reflection output..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { scriptFile = this.TransformTemplate("TransformManifest.proj", templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.Before); this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m TransformManifest.proj"); this.ExecutePlugIns(ExecutionBehaviors.After); } // Load the transformed file reflectionFile = reflectionFile.Replace(".org", ".xml"); reflectionInfo = new XmlDocument(); reflectionInfo.Load(reflectionFile); apisNode = reflectionInfo.SelectSingleNode("reflection/apis"); // Alter the help topic filenames if necessary this.ModifyHelpTopicFilenames(); // Backup the original reflection file for reference and save the changed file File.Copy(reflectionFile, Path.ChangeExtension(reflectionFile, ".bak"), true); reflectionInfo.Save(reflectionFile); commentsFiles.Save(); // Copy the standard help file content this.CopyStandardHelpContent(); // Copy conceptual content files if there are topics conceptualContent = new ConceptualContentSettings(project); if(conceptualContent.ContentLayoutFiles.Count != 0) { this.ReportProgress(BuildStep.CopyConceptualContent, "Copying conceptual content..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); conceptualContent.CopyContentFiles(this); this.ExecutePlugIns(ExecutionBehaviors.After); } this.ReportProgress(BuildStep.CreateConceptualTopicConfigs, "Creating conceptual topic configuration files..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); conceptualContent.CreateConfigurationFiles(this); this.ExecutePlugIns(ExecutionBehaviors.After); } } // Copy the additional content this.CopyAdditionalContent(); // Merge the conceptual and additional content TOC info this.MergeConceptualAndAdditionalContentTocInfo(); // Generate the intermediate table of contents file. This // must occur prior to running BuildAssembler as the MS Help // Viewer build component is dependent on the toc.xml file. this.ReportProgress(BuildStep.GenerateIntermediateTableOfContents, "Generating intermediate table of contents file..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { scriptFile = this.TransformTemplate("GenerateIntermediateTOC.proj", templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.Before); this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m GenerateIntermediateTOC.proj"); // Determine the API content placement this.DetermineApiContentPlacement(); // If there is conceptual content, generate the conceptual intermediate TOC if(toc != null) { this.ReportProgress("Generating conceptual content intermediate TOC file..."); toc.SaveToIntermediateTocFile((project.HelpFileFormat & HelpFileFormat.MSHelpViewer) != 0 ? this.RootContentContainerId : null, project.TocOrder, workingFolder + "_ConceptualTOC_.xml"); } this.ExecutePlugIns(ExecutionBehaviors.After); } // The June 2007 CTP removed the root namespace container from the TOC so we'll get // the default project page filename from the refelection information file. XmlNode defTopic = apisNode.SelectSingleNode("api[@id='R:Project']/file/@name"); if(defTopic != null) { namespacesTopic = defTopic.Value; // Use it as the default topic if one wasn't specified explicitly in the additional content if(defaultTopic == null) defaultTopic = @"html\" + namespacesTopic + ".htm"; } // Create the Sandcastle configuration file this.ReportProgress(BuildStep.CreateBuildAssemblerConfigs, "Creating Sandcastle configuration files..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); this.ReportProgress(" sandcastle.config"); // The configuration varies based on the style. However, // we'll use a common name (sandcastle.config). this.TransformTemplate(presentationParam + ".config", templateFolder, workingFolder); File.Move(workingFolder + presentationParam + ".config", workingFolder + "sandcastle.config"); // The conceptual content configuration file is common to // all styles. It is only created if needed. if(conceptualContent.ContentLayoutFiles.Count != 0) { this.ReportProgress(" conceptual.config"); this.TransformTemplate("conceptual.config", templateFolder, workingFolder); } this.ExecutePlugIns(ExecutionBehaviors.After); } // Merge the build component custom configurations this.MergeComponentConfigurations(); reflectionInfo = null; commentsFiles = null; apisNode = null; this.GarbageCollect(); // Build the conceptual help topics if(conceptualContent.ContentLayoutFiles.Count != 0) { this.ReportProgress(BuildStep.BuildConceptualTopics, "Building conceptual help topics..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { scriptFile = this.TransformTemplate("BuildConceptualTopics.proj", templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.Before); this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m BuildConceptualTopics.proj"); this.ExecutePlugIns(ExecutionBehaviors.After); } this.GarbageCollect(); } // Build the reference help topics this.ReportProgress(BuildStep.BuildReferenceTopics, "Building reference help topics..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { scriptFile = this.TransformTemplate("BuildReferenceTopics.proj", templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.Before); this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m BuildReferenceTopics.proj"); this.ExecutePlugIns(ExecutionBehaviors.After); } // Combine the conceptual and API intermediate TOC files into one this.CombineIntermediateTocFiles(); // The last part differs based on the help file format if((project.HelpFileFormat & HelpFileFormat.Website) != 0) { this.ReportProgress("\r\nClearing any prior web output"); // Purge all files and folders from the output path except for the working folder // and the build log. This is done first as the CHM and HxS files end up in the // same output folder. However, the website output is built last so that unnecessary // files are not compiled into the CHM and HxS files. Read-only and/or hidden files // and folders are ignored as they are assumed to be under source control. foreach(string file in Directory.GetFiles(outputFolder)) if(!file.EndsWith(Path.GetFileName(this.LogFilename), StringComparison.Ordinal)) if((File.GetAttributes(file) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) == 0) File.Delete(file); else this.ReportProgress(" Ignoring read-only/hidden file {0}", file); foreach(string folder in Directory.GetDirectories(outputFolder)) try { // Ignore the working folder if(!folder.EndsWith("Working", StringComparison.Ordinal)) if((File.GetAttributes(folder) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) == 0) Directory.Delete(folder, true); else this.ReportProgress(" Ignoring read-only/hidden folder {0}", folder); } catch(IOException ioEx) { this.ReportProgress(" Ignoring folder '{0}': {1}", folder, ioEx.Message); } catch(UnauthorizedAccessException uaEx) { this.ReportProgress(" Ignoring folder '{0}': {1}", folder, uaEx.Message); } } if((project.HelpFileFormat & (HelpFileFormat.HtmlHelp1 | HelpFileFormat.Website)) != 0) { this.ReportProgress(BuildStep.ExtractingHtmlInfo, "Extracting HTML info for HTML Help 1 and/or website..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { scriptFile = this.TransformTemplate("ExtractHtmlInfo.proj", templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.Before); this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m ExtractHtmlInfo.proj"); this.ExecutePlugIns(ExecutionBehaviors.After); } } if((project.HelpFileFormat & HelpFileFormat.HtmlHelp1) != 0) { // Generate the table of contents and set the default topic this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents, "Generating HTML Help 1 table of contents file..."); currentFormat = HelpFileFormat.HtmlHelp1; if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); // It got created in the ExtractingHtmlInfo step above // so there is actually nothing to do here. this.ExecutePlugIns(ExecutionBehaviors.After); } // Generate the help file index this.ReportProgress(BuildStep.GenerateHelpFileIndex, "Generating HTML Help 1 index file..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); // It got created in the ExtractingHtmlInfo step above // so there is actually nothing to do here. this.ExecutePlugIns(ExecutionBehaviors.After); } // Generate the help project file this.ReportProgress(BuildStep.GenerateHelpProject, "Generating HTML Help 1 project file..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); this.TransformTemplate("Help1x.hhp", templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.After); } // Build the HTML Help 1 help file this.ReportProgress(BuildStep.CompilingHelpFile, "Compiling HTML Help 1 file..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { scriptFile = this.TransformTemplate("Build1xHelpFile.proj", templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.Before); this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m Build1xHelpFile.proj"); this.GatherBuildOutputFilenames(); this.ExecutePlugIns(ExecutionBehaviors.After); } } if((project.HelpFileFormat & HelpFileFormat.MSHelp2) != 0) { // Generate the table of contents and set the default topic this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents, "Generating MS Help 2 table of contents file..."); currentFormat = HelpFileFormat.MSHelp2; if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { scriptFile = this.TransformTemplate("Generate2xTOC.proj", templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.Before); this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m Generate2xTOC.proj"); this.ExecutePlugIns(ExecutionBehaviors.After); } // Generate the help project files this.ReportProgress(BuildStep.GenerateHelpProject, "Generating MS Help 2 project files..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); string[] help2xFiles = Directory.GetFiles(templateFolder, "Help2x*.*"); foreach(string projectFile in help2xFiles) this.TransformTemplate(Path.GetFileName(projectFile), templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.After); } // Build the MS Help 2 help file this.ReportProgress(BuildStep.CompilingHelpFile, "Compiling MS Help 2 file..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { scriptFile = this.TransformTemplate("Build2xHelpFile.proj", templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.Before); this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m Build2xHelpFile.proj"); // Clean up the collection files this.CleanUpCollectionFiles(); this.GatherBuildOutputFilenames(); this.ExecutePlugIns(ExecutionBehaviors.After); } } if((project.HelpFileFormat & HelpFileFormat.MSHelpViewer) != 0) { // The following build steps are executed to allow plug-ins to handle any necessary processing // but nothing actually happens here: // // BuildStep.GenerateHelpFormatTableOfContents // BuildStep.GenerateHelpProject // // For the MS Help Viewer format, there is no project file to compile and the TOC layout is // generated when the help file is ultimately installed using metadata within each topic file. // All of the necessary TOC info is stored in the intermediate TOC file generated prior to // building the topics. The BuildAssembler MSHCComponent inserts the TOC info into each topic // as it is built. this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents, "Executing informational Generate Table of Contents " + "build step for plug-ins (not used for MS Help Viewer)"); currentFormat = HelpFileFormat.MSHelpViewer; if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); this.ExecutePlugIns(ExecutionBehaviors.After); } this.ReportProgress(BuildStep.GenerateHelpProject, "Executing informational Generate Help Project " + "build step for plug-ins (not used for MS Help Viewer)"); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); this.ExecutePlugIns(ExecutionBehaviors.After); } // Build the MS Help Viewer help file this.ReportProgress(BuildStep.CompilingHelpFile, "Generating MS Help Viewer file..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.TransformTemplate("HelpContentSetup.msha", templateFolder, workingFolder); // Rename the content setup file to use the help filename to keep them related and // so that multiple output files can be sent to the same output folder. File.Move(workingFolder + "HelpContentSetup.msha", workingFolder + project.HtmlHelpName + ".msha"); // Generate the example install and remove scripts this.TransformTemplate("InstallMSHC.bat", templateFolder, workingFolder); File.Move(workingFolder + "InstallMSHC.bat", workingFolder + "Install_" + project.HtmlHelpName + ".bat"); this.TransformTemplate("RemoveMSHC.bat", templateFolder, workingFolder); File.Move(workingFolder + "RemoveMSHC.bat", workingFolder + "Remove_" + project.HtmlHelpName + ".bat"); // Copy the launcher utility File.Copy(shfbFolder + "HelpLibraryManagerLauncher.exe", workingFolder + "HelpLibraryManagerLauncher.exe"); File.SetAttributes(workingFolder + "HelpLibraryManagerLauncher.exe", FileAttributes.Normal); scriptFile = this.TransformTemplate("BuildHelpViewerFile.proj", templateFolder, workingFolder); this.ExecutePlugIns(ExecutionBehaviors.Before); this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m BuildHelpViewerFile.proj"); this.GatherBuildOutputFilenames(); this.ExecutePlugIns(ExecutionBehaviors.After); } } if((project.HelpFileFormat & HelpFileFormat.Website) != 0) { // Generate the table of contents and set the default topic this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents, "Generating website table of contents file..."); currentFormat = HelpFileFormat.Website; if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); // It got created in the ExtractingHtmlInfo step above // so there is actually nothing to do here. this.ExecutePlugIns(ExecutionBehaviors.After); } this.GenerateWebsite(); } // All done if(project.CleanIntermediates) { this.ReportProgress(BuildStep.CleanIntermediates, "Removing intermediate files..."); if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) { this.ExecutePlugIns(ExecutionBehaviors.Before); try { Directory.Delete(workingFolder, true); } catch(IOException ioEx) { this.ReportProgress(" Not all build output was removed from '{0}': {1}", workingFolder, ioEx.Message); } catch(UnauthorizedAccessException uaEx) { this.ReportProgress(" Not all build output was removed from '{0}': {1}", workingFolder, uaEx.Message); } this.ExecutePlugIns(ExecutionBehaviors.After); } } AllDone: progressArgs.HasCompleted = true; TimeSpan runtime = DateTime.Now - buildStart; this.ReportProgress(BuildStep.Completed, "\r\nBuild completed successfully at {0:MM/dd/yyyy hh:mm tt}. " + "Total time: {1:00}:{2:00}:{3:00.0000}\r\n", DateTime.Now, Math.Floor(runtime.TotalSeconds / 3600), Math.Floor((runtime.TotalSeconds % 3600) / 60), (runtime.TotalSeconds % 60)); System.Diagnostics.Debug.WriteLine("Build process finished successfully\r\n"); } catch(ThreadAbortException ) { // Kill off the process, known child processes and the STDOUT // and STDERR threads too if necessary. if(currentProcess != null && !currentProcess.HasExited) { currentProcess.Kill(); foreach(Process p in Process.GetProcesses()) if(reKillProcess.IsMatch(p.ProcessName)) { System.Diagnostics.Debug.WriteLine("Killing " + p.ProcessName); p.Kill(); } } if(stdOutThread != null && stdOutThread.IsAlive) { stdOutThread.Abort(); waitCount = 0; while(waitCount < 5 && !stdOutThread.Join(1000)) waitCount++; } if(stdErrThread != null && stdErrThread.IsAlive) { stdErrThread.Abort(); waitCount = 0; while(waitCount < 5 && !stdErrThread.Join(1000)) waitCount++; } progressArgs.HasCompleted = true; this.ReportError(BuildStep.Canceled, "BE0064", "BUILD CANCELLED BY USER"); System.Diagnostics.Debug.WriteLine("Build process aborted\r\n"); } catch(Exception ex) { BuilderException bex = ex as BuilderException; System.Diagnostics.Debug.WriteLine(ex); progressArgs.HasCompleted = true; do { if(message != null) message += "\r\n"; message += ex.Message; ex = ex.InnerException; } while(ex != null); // NOTE: Message may contain format markers so pass it as a // format argument. if(bex != null) this.ReportError(BuildStep.Failed, bex.ErrorCode, "{0}", message); else this.ReportError(BuildStep.Failed, "BE0065", "BUILD FAILED: {0}", message); System.Diagnostics.Debug.WriteLine("Build process failed\r\n"); } finally { if(currentProcess != null) currentProcess.Dispose(); try { this.ExecutePlugIns(ExecutionBehaviors.Before); } catch(Exception ex) { // Not much we can do at this point... this.ReportProgress(ex.ToString()); } try { this.ExecutePlugIns(ExecutionBehaviors.After); if(loadedPlugIns != null) foreach(IPlugIn plugIn in loadedPlugIns.Values) plugIn.Dispose(); } catch(Exception ex) { // Not much we can do at this point... this.ReportProgress(ex.ToString()); } finally { this.GarbageCollect(); if(swLog != null) { swLog.WriteLine("</buildStep>\r\n</shfbBuild>"); swLog.Close(); swLog = null; } if(progressArgs.BuildStep == BuildStep.Completed && !project.KeepLogFile) File.Delete(this.LogFilename); } } }
public void AddNewItemInclude_Null() { Project p = new Project(); p.AddNewItem("item", null); }
public void RemoveItemLastInGroup() { Project p = new Project(); BuildItem buildItem = p.AddNewItem("n", "i"); Assertion.AssertEquals(1, p.ItemGroups.Count); p.RemoveItem(buildItem); Assertion.AssertEquals(0, p.ItemGroups.Count); }
public void AddNewItemEscaping() { Project p = new Project(); string escaped = @"%25%2a%3f%40%24%28%29%3b\"; string unescaped = @"%*?@$();\"; BuildItem buildItem1 = p.AddNewItem("escapedTrue", escaped, true); BuildItem buildItem2 = p.AddNewItem("escapedFalse", escaped, false); BuildItem buildItem3 = p.AddNewItem("unescapedTrue", unescaped, true); BuildItem buildItem4 = p.AddNewItem("unescapedFalse", unescaped, false); Assertion.AssertEquals(escaped, buildItem1.FinalItemSpec); Assertion.AssertEquals(unescaped, buildItem2.FinalItemSpec); Assertion.AssertEquals(unescaped, buildItem3.FinalItemSpec); Assertion.AssertEquals(@"\", buildItem4.FinalItemSpec); }