Ejemplo n.º 1
0
        public MSBuild.Project Save(MSBuild.ProjectCollection collection, string location)
        {
            location = Path.Combine(location, _name);
            Directory.CreateDirectory(location);

            var    project     = new MSBuild.Project(collection);
            string projectFile = Path.Combine(location, _name) + ProjectType.ProjectExtension;

            if (_isUserProject)
            {
                projectFile += ".user";
            }
            project.Save(projectFile);

            if (ProjectType != ProjectType.Generic)
            {
                var projGuid = Guid.NewGuid();
                project.SetProperty("ProjectTypeGuid", TypeGuid.ToString());
                project.SetProperty("Name", _name);
                project.SetProperty("ProjectGuid", projGuid.ToString("B"));
                project.SetProperty("SchemaVersion", "2.0");
                var group = project.Xml.AddPropertyGroup();
                group.Condition = " '$(Configuration)' == 'Debug' ";
                group.AddProperty("DebugSymbols", "true");
                group           = project.Xml.AddPropertyGroup();
                group.Condition = " '$(Configuration)' == 'Release' ";
                group.AddProperty("DebugSymbols", "false");
            }

            foreach (var processor in ProjectType.Processors)
            {
                processor.PreProcess(project);
            }

            foreach (var item in Items)
            {
                item.Generate(ProjectType, project);
            }

            foreach (var processor in ProjectType.Processors)
            {
                processor.PostProcess(project);
            }

            project.Save();

            return(project);
        }
Ejemplo n.º 2
0
        public override bool Execute()
        {
            try
            {
                _BE.Project input = new _BE.Project(m_inputFile);

                bool fFound = false;

                foreach (ProjectPropertyGroupElement bpg in input.Xml.PropertyGroups)
                {
                    foreach (ProjectPropertyElement bp in bpg.Properties)
                    {
                        if (string.Compare(bp.Name, "BuildNumber", true) == 0)
                        {
                            bpg.SetProperty(bp.Name, m_buildNumber);
                            fFound = true;
                            break;
                        }
                    }
                    if (fFound)
                    {
                        break;
                    }
                }

                input.Save(m_outputFile, Encoding.ASCII);
            }
            catch (Exception e)
            {
                Log.LogError("Error trying to create release info file {0} at {1}: ({2})", m_inputFile, m_outputFile, e.Message);
                return(false);
            }
            return(true);
        }
        public override bool Execute()
        {
            try
            {
                _BE.Project input = new _BE.Project(m_inputFile);

                bool fFound = false;

                foreach (ProjectPropertyGroupElement bpg in input.Xml.PropertyGroups)
                {
                    foreach (ProjectPropertyElement bp in bpg.Properties)
                    {
                        if (string.Compare(bp.Name, "BuildNumber", true) == 0)
                        {
                            bpg.SetProperty(bp.Name, m_buildNumber);
                            fFound = true;
                            break;
                        }
                    }
                    if (fFound) break;
                }

                input.Save(m_outputFile, Encoding.ASCII);
            }
            catch (Exception e)
            {
                Log.LogError("Error trying to create release info file {0} at {1}: ({2})", m_inputFile, m_outputFile, e.Message);
                return false;
            }
            return true;
        }
Ejemplo n.º 4
0
        internal static void generate(string filename, string version, string asmName, string ns, ProjectType type)
        {
            Project p = new Project();
            string typeDesc = null;

            p.Xml.DefaultTargets = "Build";
            createItemGroup(p, "ProjectConfigurations");
            createGlobals(ns, type, p, "Globals");
            p.Xml.AddImport(@"$(VCTargetsPath)\Microsoft.Cpp.Default.props");

            switch (type) {
                case ProjectType.ConsoleApp: typeDesc = "Application"; break;
                case ProjectType.XamlApp: typeDesc = "Application"; break;
                case ProjectType.ClassLibrary: typeDesc = "DynamicLibrary"; break;
                default:
                    throw new InvalidOperationException("unhandled projectType: " + type);
            }
            createCfgProp(p.Xml, typeDesc, true);
            createCfgProp(p.Xml, typeDesc, false);
            p.Xml.AddImport(@"$(VCTargetsPath)\Microsoft.Cpp.props");
            addPropertySheetImports(p.Xml);
            addPropertyGroup(p.Xml, makeCfgCondition(DEBUG, PLATFORM), new Blah2(b2));
            addPropertyGroup(p.Xml, makeCfgCondition(RELEASE, PLATFORM), new Blah2(b2));
            addItemDefs(p.Xml);

            const string C_TARGET_RULES = @"$(VCTargetsPath)\Microsoft.Cpp.targets";
            var v99 = p.Xml.CreateImportElement(C_TARGET_RULES);
            p.Xml.AppendChild(v99);
            p.Save(filename);
        }
Ejemplo n.º 5
0
        public MockVsHierarchy(int childrenSize, string name, Guid guid, MockVsHierarchy parent)
        {
            if (parent == null && MockVsSolution.Solution != null && MockVsSolution.Solution.Root != null)
            {
                _parent = MockVsSolution.Solution.Root;
            }
            else
            {
                _parent = parent;
            }
            Guid        = guid;
            SubProjects = new List <MockVsHierarchy>();
            FileName    = name;
            Children    = new List <string>();
            _folders    = new List <string>();
            AddChildren(childrenSize);
            if (guid != Guid.Empty && !Directory.Exists(FileName))
            {
#pragma warning disable 612,618
                _project = new Project(ProjectCollection.GlobalProjectCollection);
#pragma warning restore 612,618
                _project.Save(FileName);
                FileName = _project.ProjectFileLocation.File;
            }

            ExtObject = new MockEnvDteProject(this);
        }
Ejemplo n.º 6
0
 public void AddIceBuilderToProject(EnvDTE.Project p)
 {
     Microsoft.Build.Evaluation.Project project = MSBuildUtils.LoadedProject(p.FullName);
     if (MSBuildUtils.AddIceBuilderToProject(project))
     {
         if (DTEUtil.IsCppProject(p))
         {
             VCUtil.SetupSliceFilter(p);
         }
         else
         {
             String includeDirectories = ProjectUtil.GetProperty(p, PropertyNames.IncludeDirectories);
             if (String.IsNullOrEmpty(includeDirectories))
             {
                 ProjectUtil.SetProperty(p, PropertyNames.IncludeDirectories, @"$(IceHome)\slice");
             }
             else if (includeDirectories.IndexOf(@"$(IceHome)\slice") == -1)
             {
                 ProjectUtil.SetProperty(p, PropertyNames.IncludeDirectories,
                                         String.Format(@"$(IceHome)\slice;{0}", includeDirectories));
             }
             ProjectUtil.AddAssemblyReference(p, "Ice");
         }
         p.Save();
         IVsHierarchy hier        = DTEUtil.GetIVsHierarchy(p);
         Guid         projectGUID = Guid.Empty;
         IVsSolution.GetGuidOfProject(hier, out projectGUID);
         IVsSolution.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject, hier, 0);
         project.Save();
         IVsSolution4.ReloadProject(ref projectGUID);
     }
 }
Ejemplo n.º 7
0
		public static MSbuildResult BuildProject(MsBuildSettings settings, string projectFileName, DirectoryInfo dir)
		{
			var result = new MSbuildResult();
			var path = Path.Combine(dir.FullName, projectFileName);
			var project = new Project(path, null, null, new ProjectCollection());
			project.SetProperty("CscToolPath", settings.CompilerDirectory.FullName);
			var includes = new HashSet<string>(
				project.AllEvaluatedItems
				.Where(i => i.ItemType == "None" || i.ItemType == "Content")
				.Select(i => Path.GetFileName(i.EvaluatedInclude.ToLowerInvariant())));
			foreach (var dll in settings.WellKnownLibsDirectory.GetFiles("*.dll"))
				if (!includes.Contains(dll.Name.ToLowerInvariant()))
					project.AddItem("None", dll.FullName);
			project.Save();
			using (var stringWriter = new StringWriter())
			{
				var logger = new ConsoleLogger(LoggerVerbosity.Minimal, stringWriter.Write, color => { }, () => { });
				result.Success = SyncBuild(project, logger);
				if (result.Success)
					result.PathToExe = Path.Combine(project.DirectoryPath,
													project.GetPropertyValue("OutputPath"),
													project.GetPropertyValue("AssemblyName") + ".exe");
				else
					result.ErrorMessage = stringWriter.ToString();
				return result;
			}
		}
Ejemplo n.º 8
0
        public void TestBuildEngineAndProject()
        {
            UIThreadInvoker.Invoke((ThreadInvoker) delegate()
            {
                //Get the global service provider and the dte
                IServiceProvider sp = VsIdeTestHostContext.ServiceProvider;
                DTE dte             = (DTE)sp.GetService(typeof(DTE));

                string destination  = Path.Combine(TestContext.TestDir, TestContext.TestName);
                ProjectNode project = Utilities.CreateMyNestedProject(sp, dte, TestContext.TestName, destination, true);

                FieldInfo fi;
                PropertyInfo pi;
                pi = typeof(ProjectNode).GetProperty("BuildEngine", BindingFlags.Instance | BindingFlags.NonPublic);
                pi.SetValue(project, MSBuild.ProjectCollection.GlobalProjectCollection, new object[] { });
                fi = typeof(ProjectNode).GetField("buildEngine", BindingFlags.Instance | BindingFlags.NonPublic);
                Assert.AreEqual <MSBuild.ProjectCollection>(MSBuild.ProjectCollection.GlobalProjectCollection, fi.GetValue(project) as MSBuild.ProjectCollection);
                project.SetProjectFileDirty(false);

                MSBuild.Project newBuildProject = new MSBuild.Project(MSBuild.ProjectCollection.GlobalProjectCollection);
                newBuildProject.Save(Path.GetTempFileName());
                pi = typeof(ProjectNode).GetProperty("BuildProject", BindingFlags.Instance | BindingFlags.NonPublic);
                pi.SetValue(project, newBuildProject, new object[] { });
                fi = typeof(ProjectNode).GetField("buildProject", BindingFlags.Instance | BindingFlags.NonPublic);
                Assert.AreEqual <MSBuild.Project>(newBuildProject, fi.GetValue(project) as MSBuild.Project);
            });
        }
		public static void IncludeFileInCurrentProject(string approved)
		{
			var p = new Project(GetCurrentProjectFile(approved));
			if (!p.Items.Any(i => approved.EndsWith(i.UnevaluatedInclude)))
			{
				p.AddItem("Content", approved);
				p.Save();
			}
		}
Ejemplo n.º 10
0
 private static void addPostBuildEvent(string path)
 {
     Project project = new Project(path);
     project.SetProperty("PostBuildEvent",
                         string.Format(
                             @"""{0}"" "" $(TargetDir) "" "" $(TargetName) "" "" $(SolutionDir) """,
                             Process.GetCurrentProcess().MainModule.FileName));
     project.Save();
 }
        private void RemoveIceBuilderFromProject(IVsProject p)
        {
            String path = ProjectUtil.GetProjectFullPath(p);

            foreach (IVsProject p1 in _buildProjects)
            {
                if (path.Equals(ProjectUtil.GetProjectFullPath(p1)))
                {
                    _buildProjects.Remove(p1);
                    break;
                }
            }

            ProjectUtil.DeleteItems(
                ProjectUtil.GetGeneratedFiles(p).Aggregate(
                    new List <String>(),
                    (items, kv) =>
            {
                items.AddRange(kv.Value);
                return(items);
            }));

            if (DTEUtil.IsCSharpProject(p))
            {
                Directory.GetFiles(GetAssembliesDir(GetIceHome()), "*.dll")
                .ToList()
                .ForEach(item =>
                {
                    String name = Path.GetFileNameWithoutExtension(item);
                    if (ProjectUtil.HasAssemblyReference(DTEUtil.GetProject(p as IVsHierarchy), name))
                    {
                        ProjectUtil.RemoveAssemblyReference(DTEUtil.GetProject(p as IVsHierarchy), name);
                    }
                });
            }

            Microsoft.Build.Evaluation.Project project = MSBuildUtils.LoadedProject(path, DTEUtil.IsCppProject(p), true);
            MSBuildUtils.RemoveIceBuilderFromProject(project);
            ProjectUtil.SaveProject(p);

            Guid         projectGUID = Guid.Empty;
            IVsHierarchy hier        = p as IVsHierarchy;

            IVsSolution.GetGuidOfProject(hier, out projectGUID);
            IVsSolution.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject, hier, 0);
            project.Save();
            try
            {
                ProjectCollection.GlobalProjectCollection.UnloadProject(project);
            }
            catch (System.Exception)
            {
                //expected if the project is not in the global project collection
            }
            IVsSolution4.ReloadProject(ref projectGUID);
        }
Ejemplo n.º 12
0
 int IVsProject.AddItem(uint itemidLoc, VSADDITEMOPERATION dwAddItemOperation, string pszItemName, uint cFilesToOpen,
                        string[] rgpszFilesToOpen, IntPtr hwndDlgOwner, VSADDRESULT[] pResult)
 {
     if (Directory.Exists(rgpszFilesToOpen[0]))
     {
         AddProject(new MockVsHierarchy(rgpszFilesToOpen[0], this));
     }
     else
     {
         Children.Add(rgpszFilesToOpen[0]);
         if (_project != null)
         {
             FileInfo itemFileInfo = new FileInfo(rgpszFilesToOpen[0]);
             _project.Save(FileName);
             FileInfo projectFileInfo = new FileInfo(_project.ProjectFileLocation.File);
             string   itemName        = itemFileInfo.FullName.Substring(projectFileInfo.Directory.FullName.Length + 1);
             _project.AddItem("Compile", itemName);
             _project.Save(FileName);
         }
     }
     return(VSConstants.S_OK);
 }
Ejemplo n.º 13
0
        private static void UpdateCsprojFile(string fullPath, Project csproj)
        {
            try
            {
                var fileName = Path.GetFileName(fullPath);

                File.Delete(fullPath);
                csproj.Save(fileName);

                File.Move(csproj.FullPath, fullPath);
            }
            catch (IOException)
            {
                LogService.WriteError("Erro ao atualizar o arquivo " + fullPath);
            }
        }
Ejemplo n.º 14
0
        public void SaveProject(IVsProject project)
        {
            Microsoft.Build.Evaluation.Project msproject = project.GetMSBuildProject(true);
            IVsHierarchy hier        = project as IVsHierarchy;
            Guid         projectGUID = Guid.Empty;

            IVsSolution.GetGuidOfProject(hier, out projectGUID);
            IVsSolution4.UnloadProject(projectGUID, (uint)_VSProjectUnloadStatus.UNLOADSTATUS_UnloadedByUser);
            msproject.Save();
            try
            {
                ProjectCollection.GlobalProjectCollection.UnloadProject(msproject);
            }
            catch (Exception)
            {
                //expected if the project is not in the global project collection
            }
            IVsSolution4.ReloadProject(ref projectGUID);
        }
Ejemplo n.º 15
0
        private void RemoveIceBuilderFromProject(EnvDTE.Project p)
        {
            Microsoft.Build.Evaluation.Project project = MSBuildUtils.LoadedProject(p.FullName);
            MSBuildUtils.RemoveIceBuilderFromProject(project);
            foreach (EnvDTE.Project p1 in _buildProjects)
            {
                if (p.FullName.Equals(p.FullName))
                {
                    _buildProjects.Remove(p1);
                    break;
                }
            }


            ProjectUtil.DeleteItems(p,
                                    ProjectUtil.GetGeneratedFiles(p).Aggregate(
                                        new List <String>(),
                                        (items, kv) =>
            {
                items.AddRange(kv.Value);
                return(items);
            }));

            Directory.GetFiles(GetAssembliesDir(GetIceHome()), "*.dll")
            .ToList()
            .ForEach(item =>
            {
                String name = Path.GetFileNameWithoutExtension(item);
                if (ProjectUtil.HasAssemblyReference(p, name))
                {
                    ProjectUtil.RemoveAssemblyReference(p, name);
                }
            });
            p.Save();

            Guid         projectGUID = Guid.Empty;
            IVsHierarchy hier        = DTEUtil.GetIVsHierarchy(p);

            IVsSolution.GetGuidOfProject(hier, out projectGUID);
            IVsSolution.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject, hier, 0);
            project.Save();
            IVsSolution4.ReloadProject(ref projectGUID);
        }
        public MSBuild.Project Save(MSBuild.ProjectCollection collection, string location) {
            location = Path.Combine(location, _name);
            Directory.CreateDirectory(location);

            var project = new MSBuild.Project(collection);
            string projectFile = Path.Combine(location, _name) + ProjectType.ProjectExtension;
            if (_isUserProject) {
                projectFile += ".user";
            }
            project.Save(projectFile);

            if (ProjectType != ProjectType.Generic) {
                var projGuid = Guid;
                project.SetProperty("ProjectTypeGuid", TypeGuid.ToString());
                project.SetProperty("Name", _name);
                project.SetProperty("ProjectGuid", projGuid.ToString("B"));
                project.SetProperty("SchemaVersion", "2.0");
                var group = project.Xml.AddPropertyGroup();
                group.Condition = " '$(Configuration)' == 'Debug' ";
                group.AddProperty("DebugSymbols", "true");
                group = project.Xml.AddPropertyGroup();
                group.Condition = " '$(Configuration)' == 'Release' ";
                group.AddProperty("DebugSymbols", "false");
            }

            foreach (var processor in ProjectType.Processors) {
                processor.PreProcess(project);
            }

            foreach (var item in Items) {
                item.Generate(ProjectType, project);
            }

            foreach (var processor in ProjectType.Processors) {
                processor.PostProcess(project);
            }

            project.Save();

            return project;
        }
Ejemplo n.º 17
0
        public override bool Execute()
        {
            bool result = true;

            string file = Path.Combine(m_stubsPath, m_name + ".featureproj");

            try
            {
                _EVAL.Project proj = new _EVAL.Project();

                Microsoft.Build.Evaluation.ProjectCollection projCol = proj.ProjectCollection;

                ProjectPropertyGroupElement bpg = proj.Xml.AddPropertyGroup();
                bpg.AddProperty("FeatureName", m_name);
                bpg.AddProperty("Guid", System.Guid.NewGuid().ToString("B"));
                bpg.AddProperty("Description", "<Add Feature Description Here>");
                bpg.AddProperty("Groups", "");
                bpg.AddProperty(m_name.ToUpper().Replace(".", "_") + "_FEATUREPROJ", "True");

                ProjectItemGroupElement big = proj.Xml.AddItemGroup();
                big.AddItem("InteropFeature", Path.GetFileNameWithoutExtension(m_assemblyName).Replace('.', '_'));
                big.AddItem("DriverLibs", Path.GetFileNameWithoutExtension(m_assemblyName).Replace('.', '_') + ".$(LIB_EXT)");
                big.AddItem("MMP_DAT_CreateDatabase", "$(BUILD_TREE_CLIENT)\\pe\\$(ENDIANNESS)\\" + m_assemblyName);
                big.AddItem("RequiredProjects", Path.Combine(m_stubsPath, m_nativeProjectFile));


                proj.Save(file);

                // after save, unload the project, so that if rebuilds it is able to regenerate the project file.
                ProjectRootElement pre = proj.Xml;
                projCol.UnloadProject(proj);
                projCol.UnloadProject(pre);
            }
            catch (Exception e)
            {
                Log.LogError("Error trying to create feature project file \"" + file + "\": " + e.Message);
                result = false;
            }

            return(result);
        }
 public void AddIceBuilderToProject(IVsProject p)
 {
     Microsoft.Build.Evaluation.Project project = MSBuildUtils.LoadedProject(ProjectUtil.GetProjectFullPath(p), DTEUtil.IsCppProject(p), true);
     if (MSBuildUtils.AddIceBuilderToProject(project))
     {
         if (DTEUtil.IsCppProject(p))
         {
             VCUtil.SetupSliceFilter(DTEUtil.GetProject(p as IVsHierarchy));
         }
         else
         {
             String includeDirectories = ProjectUtil.GetProperty(p, PropertyNames.IncludeDirectories);
             if (String.IsNullOrEmpty(includeDirectories))
             {
                 ProjectUtil.SetProperty(p, PropertyNames.IncludeDirectories, @"$(IceHome)\slice");
             }
             else if (includeDirectories.IndexOf(@"$(IceHome)\slice") == -1)
             {
                 ProjectUtil.SetProperty(p, PropertyNames.IncludeDirectories,
                                         String.Format(@"$(IceHome)\slice;{0}", includeDirectories));
             }
             ProjectUtil.AddAssemblyReference(DTEUtil.GetProject(p as IVsHierarchy), "Ice");
         }
         ProjectUtil.SaveProject(p);
         IVsHierarchy hier        = p as IVsHierarchy;
         Guid         projectGUID = Guid.Empty;
         IVsSolution.GetGuidOfProject(hier, out projectGUID);
         IVsSolution.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject, hier, 0);
         project.Save();
         try
         {
             ProjectCollection.GlobalProjectCollection.UnloadProject(project);
         }
         catch (System.Exception)
         {
             //expected if the project is not in the global project collection
         }
         IVsSolution4.ReloadProject(ref projectGUID);
     }
 }
Ejemplo n.º 19
0
        public static void AddProjectFiles(FilePath ProjectFile, IReadOnlyList <FilePath> files, bool build = false)
        {
            var project       = new MSEV.Project(ProjectFile);
            var projectFolder = ProjectFile.Folder;

            foreach (var file in files)
            {
                var itemType     = StandardItemTypes.InferItemType(file.FileName);
                var relativePath = file.Value.Replace(projectFolder.FullPath, String.Empty);
                if (relativePath.StartsWith("\\"))
                {
                    relativePath = relativePath.Substring(1);
                }

                project.AddItem(itemType, relativePath);
            }
            project.Save();
            if (build)
            {
                project.Build();
            }
        }
Ejemplo n.º 20
0
        private void ToolStripButton3_Click(object sender, EventArgs e)
        {
            TreeNode node = treeView1.SelectedNode;

            if (node.ImageIndex == PROJECT || node.ImageIndex == FOLDER || node.ImageIndex == FOLDER_OPEN)
            {
                string path =
                    _filePath.Replace(Path.DirectorySeparatorChar + Path.GetFileName(_filePath) ?? string.Empty, "");
                string replace = node.FullPath?.Replace(Path.GetFileName(_filePath) ?? string.Empty, "");
                string target  = path + replace.Replace("\\", Path.DirectorySeparatorChar.ToString());
                if (Directory.Exists(target))
                {
                    StringDialog dialog = new StringDialog((text) => !string.IsNullOrEmpty(text));
                    dialog.Description = "Create Directory Name";
                    dialog.ShowDialog();
                    if (dialog.DialogResult == DialogResult.OK)
                    {
                        string newDir = target + Path.DirectorySeparatorChar + dialog.ResultString;
                        if (!Directory.Exists(newDir))
                        {
                            Directory.CreateDirectory(newDir);
                            string  name = replace.Split(Path.DirectorySeparatorChar)[1];
                            Project proj = _projects[name];
                            proj.AddItem("Folder", newDir.Replace(path + "\\" + name + "\\", "") + "\\");
                            proj.Save();

                            LoadSolution(_solution, _filePath);
                        }
                        else
                        {
                            MessageBox.Show("Created Directory");
                        }
                    }
                }
            }
        }
Ejemplo n.º 21
0
        //=====================================================================

        /// <summary>
        /// Call this method to perform the build on the project.
        /// </summary>
        public void Build()
        {
            Project msBuildProject = null;
            ProjectItem projectItem;
            string resolvedPath, helpFile, languageFile, scriptFile, hintPath, message = null;
            SandcastleProject originalProject = null;

            System.Diagnostics.Debug.WriteLine("Build process starting\r\n");

            try
            {
                taskRunner = new TaskRunner(this);

                // If the project isn't using final values suitable for the build, create a copy of the
                // project that is using final values.
                if(!project.UsingFinalValues)
                {
                    originalProject = project;
                    project = new SandcastleProject(originalProject.MSBuildProject);
                }

                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;

                // The version of MSBuild to use is based on the tools version set in the project
                msBuildExePath = Path.Combine(ProjectCollection.GlobalProjectCollection.Toolsets.First(
                    t => t.ToolsVersion == project.MSBuildProject.ToolsVersion).ToolsPath, "MSBuild.exe");

                // Get the location of the template files
                templateFolder = ComponentUtilities.ToolsFolder + @"Templates\";

                // 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 & HelpFileFormats.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");

                // Make sure we can find the tools
                this.FindTools();

                // 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}",
                        ComponentUtilities.ToolsFolder);

                    Environment.SetEnvironmentVariable("SHFBROOT", ComponentUtilities.ToolsFolder);
                }

                this.ReportProgress("Locating components in the following folder(s):");

                if(!String.IsNullOrEmpty(project.ComponentPath))
                    this.ReportProgress("    {0}", project.ComponentPath);

                this.ReportProgress("    {0}", Path.GetDirectoryName(project.Filename));

                this.ReportProgress("    {0}", ComponentUtilities.ComponentsFolder);
                this.ReportProgress("    {0}", ComponentUtilities.ToolsFolder);

                // Get the framework reflection data settings to use for the build
                reflectionDataDictionary = new ReflectionDataSetDictionary(new[] { project.ComponentPath,
                    Path.GetDirectoryName(project.Filename) });
                frameworkReflectionData = reflectionDataDictionary.CoreFrameworkByTitle(project.FrameworkVersion, true);

                if(frameworkReflectionData == null)
                    throw new BuilderException("BE0071", String.Format(CultureInfo.CurrentCulture,
                        "Unable to locate information for the project framework version '{0}' or a suitable " +
                        "redirected version on this system.  See error number help topic for details.",
                        project.FrameworkVersion));

                this.ReportProgress("Framework reflection data location: {0}", this.FrameworkReflectionDataFolder);

                if(!Directory.EnumerateFiles(this.FrameworkReflectionDataFolder, "*.xml").Any())
                    throw new BuilderException("BE0032", "Reflection data files for the selected framework " +
                        "do not exist yet (" + frameworkReflectionData.Title + ").  See help file for " +
                        "details about this error number.");

                // Warn if a different framework is being used for the build
                if(frameworkReflectionData.Title != project.FrameworkVersion)
                    this.ReportWarning("BE0072", "Project framework version '{0}' not found.  It has been " +
                        "redirected and will use '{1}' instead.", project.FrameworkVersion,
                        frameworkReflectionData.Title);

                // Get the composition container used to find build components in the rest of the build process
                componentContainer = ComponentUtilities.CreateComponentContainer(new[] { project.ComponentPath,
                    Path.GetDirectoryName(project.Filename) }, this.CancellationToken);

                syntaxGenerators = componentContainer.GetExports<ISyntaxGeneratorFactory,
                    ISyntaxGeneratorMetadata>().Select(sf => sf.Metadata).ToList();
                buildComponents = componentContainer.GetExports<BuildComponentFactory,
                    IBuildComponentMetadata>().GroupBy(c => c.Metadata.Id).Select(g => g.First()).ToDictionary(
                        key => key.Metadata.Id, value => value.Value);

                // Figure out which presentation style to use
                var style = componentContainer.GetExports<PresentationStyleSettings,
                    IPresentationStyleMetadata>().FirstOrDefault(s => s.Metadata.Id.Equals(
                        project.PresentationStyle, StringComparison.OrdinalIgnoreCase));

                if(style == null)
                    throw new BuilderException("BE0001", "The PresentationStyle property value of '" +
                        project.PresentationStyle + "' is not recognized as a valid presentation style definition");

                presentationStyle = style.Value;

                this.ReportProgress("Using presentation style '{0}' located in '{1}'", style.Metadata.Id,
                    Path.Combine(presentationStyle.Location, presentationStyle.BasePath ?? String.Empty));

                var psErrors = presentationStyle.CheckForErrors();

                if(psErrors.Any())
                    throw new BuilderException("BE0004", String.Format(CultureInfo.CurrentCulture,
                        "The selected presentation style ({0}) is not valid.  Reason(s):\r\n{1}",
                        style.Metadata.Id, String.Join("\r\n", psErrors)));

                // If the presentation style does not support one or more of the selected help file formats,
                // stop now.
                if((project.HelpFileFormat & ~presentationStyle.SupportedFormats) != 0)
                    throw new BuilderException("BE0074", String.Format(CultureInfo.CurrentCulture,
                        "The selected presentation style ({0}) does not support one or more of the selected " +
                        "help file formats.  Supported formats: {1}", style.Metadata.Id,
                        presentationStyle.SupportedFormats));

                // Create the substitution tag replacement handler now as we have everything it needs
                substitutionTags = new SubstitutionTagReplacement(this);

                // Load the plug-ins if necessary
                if(project.PlugInConfigurations.Count != 0 || presentationStyle.PlugInDependencies.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);
                        }
                    }

                    // For MS Help Viewer, the HTML Help Name cannot contain periods, ampersands, or pound signs
                    if((project.HelpFileFormat & HelpFileFormats.MSHelpViewer) != 0 &&
                      this.ResolvedHtmlHelpName.IndexOfAny(new[] { '.', '#', '&' }) != -1)
                        throw new BuilderException("BE0075", "For MS Help Viewer builds, the HtmlHelpName property " +
                            "cannot contain periods, ampersands, or pound signs as they are not valid in the " +
                            "help file name.");

                    // 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 + this.ResolvedHtmlHelpName + ".chm";

                    if((project.HelpFileFormat & HelpFileFormats.HtmlHelp1) != 0 && File.Exists(helpFile))
                        File.Delete(helpFile);

                    helpFile = Path.ChangeExtension(helpFile, ".mshc");

                    if((project.HelpFileFormat & HelpFileFormats.MSHelpViewer) != 0 && File.Exists(helpFile))
                        File.Delete(helpFile);

                    if((project.HelpFileFormat & HelpFileFormats.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);
                    }

                    helpFile = outputFolder + this.ResolvedHtmlHelpName + ".docx";

                    if((project.HelpFileFormat & HelpFileFormats.OpenXml) != 0 && File.Exists(helpFile))
                        File.Delete(helpFile);
                }
                catch(IOException ex)
                {
                    throw new BuilderException("BE0025", "Unable to remove prior build output: " + ex.Message);
                }
                catch
                {
                    throw;
                }

                if((project.HelpFileFormat & (HelpFileFormats.Website | HelpFileFormats.Markdown)) != 0)
                {
                    this.ReportProgress("-------------------------------");
                    this.ReportProgress("Clearing any prior web/markdown output...");

                    // Purge all files and folders from the output path except for the working folder and the
                    // build log.  Read-only and/or hidden files and folders are ignored as they are assumed to
                    // be under source control.
                    foreach(string file in Directory.EnumerateFiles(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.EnumerateDirectories(outputFolder))
                        try
                        {
                            // Ignore the working folder in case it wasn't removed above
                            if(!folder.Equals(workingFolder.Substring(0, workingFolder.Length - 1), StringComparison.OrdinalIgnoreCase))
                            {
                                // Some source control providers have a mix of read-only/hidden files within a
                                // folder that isn't read-only/hidden (i.e. Subversion).  In such cases, leave
                                // the folder alone.
                                if(Directory.EnumerateFileSystemEntries(folder, "*", SearchOption.AllDirectories).Any(
                                  f => (File.GetAttributes(f) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) != 0))
                                {
                                    this.ReportProgress("    Did not delete folder '{0}' as it contains " +
                                        "read-only or hidden folders/files", folder);
                                }
                                else
                                    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);
                        }
                }

                Directory.CreateDirectory(workingFolder);

                // 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 = Path.Combine(presentationStyle.ResolvePath(presentationStyle.ToolResourceItemsPath),
                    language.Name + ".xml");

                this.ReportProgress(BuildStep.GenerateSharedContent, "Generating shared content files ({0}, {1})...",
                    language.Name, language.DisplayName);

                if(!File.Exists(languageFile))
                {
                    languageFile = Path.Combine(presentationStyle.ResolvePath(presentationStyle.ToolResourceItemsPath),
                        "en-US.xml");

                    // Warn the user about the default being used
                    this.ReportWarning("BE0002", "Help file 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 = Path.Combine(presentationStyle.ResolvePath(presentationStyle.ResourceItemsPath),
                    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);

                    substitutionTags.TransformTemplate(Path.GetFileName(languageFile), Path.GetDirectoryName(languageFile),
                        workingFolder);
                    File.Move(workingFolder + Path.GetFileName(languageFile), workingFolder + "SHFBContent.xml");

                    // Copy the stop word list
                    languageFile = Path.Combine(ComponentUtilities.ToolsFolder, @"PresentationStyles\Shared\" +
                        @"StopWordList\" + Path.GetFileNameWithoutExtension(languageFile) +".txt");
                    File.Copy(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))
                {
                    substitutionTags.TransformTemplate("MRefBuilder.config", templateFolder, workingFolder);
                    scriptFile = substitutionTags.TransformTemplate("GenerateRefInfo.proj", templateFolder, workingFolder);

                    try
                    {
                        msBuildProject = new Project(scriptFile);

                        // Add the references
                        foreach(var r in referenceDictionary.Values)
                        {
                            projectItem = msBuildProject.AddItem(r.Item1, r.Item2, r.Item3)[0];

                            // Make sure hint paths are correct by adding the project folder to any relative
                            // paths.  Skip any containing MSBuild variable references.
                            if(projectItem.HasMetadata(BuildItemMetadata.HintPath))
                            {
                                hintPath = projectItem.GetMetadataValue(BuildItemMetadata.HintPath);

                                if(!Path.IsPathRooted(hintPath) && hintPath.IndexOf("$(",
                                  StringComparison.Ordinal) == -1)
                                {
                                    hintPath = FilePath.GetFullPath(Path.Combine(projectFolder, hintPath));

                                    // If the full path length would exceed the system maximums, make it relative
                                    // to keep it under the maximum lengths.
                                    if(hintPath.Length > 259 || Path.GetDirectoryName(hintPath).Length > 247)
                                        hintPath = FolderPath.AbsoluteToRelativePath(workingFolder, hintPath);

                                    projectItem.SetMetadataValue(BuildItemMetadata.HintPath, hintPath);
                                }
                            }
                        }

                        // Add the assemblies to document
                        foreach(string assemblyName in assembliesList)
                            msBuildProject.AddItem("Assembly", assemblyName);

                        msBuildProject.Save(scriptFile);
                    }
                    finally
                    {
                        // If we loaded it, we must unload it.  If not, it is cached and may cause problems later.
                        if(msBuildProject != null)
                        {
                            ProjectCollection.GlobalProjectCollection.UnloadProject(msBuildProject);
                            ProjectCollection.GlobalProjectCollection.UnloadProject(msBuildProject.Xml);
                        }
                    }

                    this.ExecutePlugIns(ExecutionBehaviors.Before);

                    // Silverlight build targets are only available for 32-bit builds regardless of the framework
                    // version and require the 32-bit version of MSBuild in order to load the target file correctly.
                    if(project.FrameworkVersion.StartsWith("Silverlight", StringComparison.OrdinalIgnoreCase))
                        taskRunner.Run32BitProject("GenerateRefInfo.proj", false);
                    else
                        taskRunner.RunProject("GenerateRefInfo.proj", false);

                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }

                // If this was a partial build used to obtain API information, stop now
                if(this.PartialBuildType == PartialBuildType.GenerateReflectionInfo)
                {
                    commentsFiles.Save();
                    goto AllDone;       // Yeah, I know it's evil but it's quick
                }

                // Transform the reflection output based on the document model and create the topic manifest
                this.ReportProgress(BuildStep.TransformReflectionInfo, "Transforming reflection output...");

                if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                {
                    scriptFile = substitutionTags.TransformTemplate("TransformManifest.proj", templateFolder, workingFolder);

                    this.ExecutePlugIns(ExecutionBehaviors.Before);

                    taskRunner.RunProject("TransformManifest.proj", false);

                    // Change the reflection file extension before running the ExecutionBehaviors.After plug-ins
                    // so that the plug-ins (if any) get the correct filename.
                    reflectionFile = Path.ChangeExtension(reflectionFile, ".xml");

                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }
                else
                    reflectionFile = Path.ChangeExtension(reflectionFile, ".xml");

                // If this was a partial build used to obtain information for namespace and namespace group
                // comments, stop now.
                if(this.PartialBuildType == PartialBuildType.TransformReflectionInfo)
                {
                    commentsFiles.Save();
                    goto AllDone;       // Yeah, I know it's evil but it's quick
                }

                // Load the transformed reflection information file
                reflectionFile = workingFolder + "reflection.xml";

                // If there is nothing to document, stop the build
                if(!ComponentUtilities.XmlStreamAxis(reflectionFile, "api").Any())
                    throw new BuilderException("BE0033", "No APIs found to document.  See error topic in " +
                        "help file for details.");

                // Generate namespace summary information
                this.GenerateNamespaceSummaries();

                // Expand <inheritdoc /> tags?
                if(commentsFiles.ContainsInheritedDocumentation)
                {
                    commentsFiles.Save();

                    // Transform the reflection output.
                    this.ReportProgress(BuildStep.GenerateInheritedDocumentation,
                        "Generating inherited documentation...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        substitutionTags.TransformTemplate("GenerateInheritedDocs.config", templateFolder, workingFolder);
                        scriptFile = substitutionTags.TransformTemplate("GenerateInheritedDocs.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("GenerateInheritedDocs.proj", true);
                        
                        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"));
                }

                commentsFiles.Save();

                this.EnsureOutputFoldersExist(null);

                // Copy conceptual content files if there are topics or tokens.  Tokens can be replaced in
                // XML comments files so we check for them too.
                if(this.ConceptualContent.ContentLayoutFiles.Count != 0 || this.ConceptualContent.TokenFiles.Count != 0)
                {
                    this.ReportProgress(BuildStep.CopyConceptualContent, "Copying conceptual content...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        this.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);
                        this.ConceptualContent.CreateConfigurationFiles(this);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }
                else    // Create an empty xmlComp folder required by the build configuration
                    Directory.CreateDirectory(Path.Combine(workingFolder, "xmlComp"));

                // 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 = substitutionTags.TransformTemplate("GenerateIntermediateTOC.proj", templateFolder,
                        workingFolder);

                    this.ExecutePlugIns(ExecutionBehaviors.Before);

                    taskRunner.RunProject("GenerateIntermediateTOC.proj", false);

                    // 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 & HelpFileFormats.MSHelpViewer) != 0 ?
                            this.RootContentContainerId : null, project.TocOrder, workingFolder + "_ConceptualTOC_.xml");
                    }

                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }

                // Create the Sandcastle configuration file
                this.ReportProgress(BuildStep.CreateBuildAssemblerConfigs, "Creating Sandcastle configuration files...");

                // Add referenced namespaces to the hash set.  These are used to ensure just the needed set of
                // reflection target files are loaded by BuildAssembler and nothing more to save some time and
                // memory.
                var rn = this.ReferencedNamespaces;

                // These are all of the valid namespaces we are interested in.  This prevents the methods below
                // from returning nested types as potential namespaces since they can't tell the difference.
                HashSet<string> validNamespaces = new HashSet<string>(Directory.EnumerateFiles(
                    this.FrameworkReflectionDataFolder, "*.xml", SearchOption.AllDirectories).Select(
                        f => Path.GetFileNameWithoutExtension(f)));

                // Get namespaces referenced in the XML comments of the documentation sources
                foreach(var n in commentsFiles.GetReferencedNamespaces(validNamespaces))
                    rn.Add(n);

                // Get namespaces referenced in the reflection data (plug-ins are responsible for adding
                // additional namespaces if they add other reflection data files).
                foreach(string n in GetReferencedNamespaces(reflectionFile, validNamespaces))
                    rn.Add(n);

                // Get namespaces from the Framework comments files of the referenced namespaces.  This adds
                // references for stuff like designer and support classes not directly referenced anywhere else.
                foreach(string n in frameworkReflectionData.GetReferencedNamespaces(language, rn, validNamespaces).ToList())
                    rn.Add(n);

                // If F# syntax is being generated, add some of the F# namespaces as the syntax sections generate
                // references to types that may not be there in non-F# projects.
                if(ComponentUtilities.SyntaxFiltersFrom(syntaxGenerators, project.SyntaxFilters).Any(
                  f => f.Id == "F#"))
                {
                    rn.Add("Microsoft.FSharp.Core");
                    rn.Add("Microsoft.FSharp.Control");
                }

                // If there are no referenced namespaces, add System as a default to prevent the build components
                // from loading the entire set.
                if(rn.Count == 0)
                    rn.Add("System");

                if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                {
                    this.ExecutePlugIns(ExecutionBehaviors.Before);

                    this.ReportProgress("    sandcastle.config");

                    // The configuration varies based on the style.  We'll use a common name (sandcastle.config).
                    resolvedPath = presentationStyle.ResolvePath(presentationStyle.ReferenceBuildConfiguration);
                    substitutionTags.TransformTemplate(Path.GetFileName(resolvedPath), Path.GetDirectoryName(resolvedPath),
                        workingFolder);

                    if(!Path.GetFileName(resolvedPath).Equals("sandcastle.config", StringComparison.OrdinalIgnoreCase))
                        File.Move(workingFolder + Path.GetFileName(resolvedPath), workingFolder + "sandcastle.config");

                    // The conceptual content configuration file is only created if needed.
                    if(this.ConceptualContent.ContentLayoutFiles.Count != 0)
                    {
                        this.ReportProgress("    conceptual.config");

                        resolvedPath = presentationStyle.ResolvePath(presentationStyle.ConceptualBuildConfiguration);

                        substitutionTags.TransformTemplate(Path.GetFileName(resolvedPath), Path.GetDirectoryName(resolvedPath),
                            workingFolder);

                        if(!Path.GetFileName(resolvedPath).Equals("conceptual.config", StringComparison.OrdinalIgnoreCase))
                            File.Move(workingFolder + Path.GetFileName(resolvedPath), workingFolder + "conceptual.config");
                    }

                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }

                // Merge the build component custom configurations
                this.MergeComponentConfigurations();

                commentsFiles = null;

                // Build the conceptual help topics
                if(this.ConceptualContent.ContentLayoutFiles.Count != 0)
                {
                    this.ReportProgress(BuildStep.BuildConceptualTopics, "Building conceptual help topics...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        scriptFile = substitutionTags.TransformTemplate("BuildConceptualTopics.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("BuildConceptualTopics.proj", false);
                        
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                // Build the reference help topics
                this.ReportProgress(BuildStep.BuildReferenceTopics, "Building reference help topics...");

                if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                {
                    scriptFile = substitutionTags.TransformTemplate("BuildReferenceTopics.proj", templateFolder,
                        workingFolder);

                    this.ExecutePlugIns(ExecutionBehaviors.Before);
                                        
                    taskRunner.RunProject("BuildReferenceTopics.proj", false);
                    
                    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 & (HelpFileFormats.HtmlHelp1 | HelpFileFormats.Website)) != 0)
                {
                    this.ReportProgress(BuildStep.ExtractingHtmlInfo,
                        "Extracting HTML info for HTML Help 1 and/or website...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        scriptFile = substitutionTags.TransformTemplate("ExtractHtmlInfo.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("ExtractHtmlInfo.proj", true);

                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                // Copy the standard help file content.  This is done just before compiling the help so that
                // template files from the presentation style can take advantage of tag substitution.  By this
                // point, we should have everything we could possibly need.
                this.CopyStandardHelpContent();

                if((project.HelpFileFormat & HelpFileFormats.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 = HelpFileFormats.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);
                        substitutionTags.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 = substitutionTags.TransformTemplate("Build1xHelpFile.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("Build1xHelpFile.proj", true);
                        
                        this.GatherBuildOutputFilenames();
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                if((project.HelpFileFormat & HelpFileFormats.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 = HelpFileFormats.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))
                    {
                        substitutionTags.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 + this.ResolvedHtmlHelpName + ".msha");

                        // Generate the example install and remove scripts
                        substitutionTags.TransformTemplate("InstallMSHC.bat", templateFolder, workingFolder);
                        File.Move(workingFolder + "InstallMSHC.bat", workingFolder + "Install_" +
                            this.ResolvedHtmlHelpName + ".bat");

                        substitutionTags.TransformTemplate("RemoveMSHC.bat", templateFolder, workingFolder);
                        File.Move(workingFolder + "RemoveMSHC.bat", workingFolder + "Remove_" +
                            this.ResolvedHtmlHelpName + ".bat");

                        // Copy the launcher utility
                        File.Copy(ComponentUtilities.ToolsFolder + "HelpLibraryManagerLauncher.exe",
                            workingFolder + "HelpLibraryManagerLauncher.exe");
                        File.SetAttributes(workingFolder + "HelpLibraryManagerLauncher.exe", FileAttributes.Normal);

                        scriptFile = substitutionTags.TransformTemplate("BuildHelpViewerFile.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("BuildHelpViewerFile.proj", true);

                        this.GatherBuildOutputFilenames();
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                if((project.HelpFileFormat & HelpFileFormats.Website) != 0)
                {
                    // Generate the table of contents and set the default topic
                    this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents,
                        "Generating website table of contents file...");

                    currentFormat = HelpFileFormats.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();
                }

                if((project.HelpFileFormat & HelpFileFormats.OpenXml) != 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 Open XML format, there is no project file to compile and the TOC layout is
                    // generated when the document is opened.  All of the necessary TOC info is stored in the
                    // intermediate TOC file generated prior to building the topics.  The process used to merge
                    // the topics into a single document uses it to define the order in which the topics are
                    // combined.

                    this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents, "Executing informational " +
                        "Generate Table of Contents build step for plug-ins (not used for Open XML)");

                    currentFormat = HelpFileFormats.OpenXml;

                    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 Open XML)");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    // Build the Open XML document
                    this.ReportProgress(BuildStep.CompilingHelpFile, "Generating Open XML document file...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        scriptFile = substitutionTags.TransformTemplate("BuildOpenXmlFile.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("BuildOpenXmlFile.proj", true);

                        this.GatherBuildOutputFilenames();
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                if((project.HelpFileFormat & HelpFileFormats.Markdown) != 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 Markdown format, there is no project file to compile and the TOC layout is
                    // generated by the build task.  All of the necessary TOC info is stored in the intermediate
                    // TOC file generated prior to building the topics.  The build task uses it to find the
                    // topics to finalize and generate the sidebar TOC file.
                    this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents, "Executing informational " +
                        "Generate Table of Contents build step for plug-ins (not used for Markdown)");

                    currentFormat = HelpFileFormats.Markdown;

                    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 Markdown)");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    // Generate the markdown content
                    this.ReportProgress(BuildStep.CompilingHelpFile, "Generating markdown content...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        scriptFile = substitutionTags.TransformTemplate("GenerateMarkdownContent.proj",
                            templateFolder, workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("GenerateMarkdownContent.proj", true);

                        this.GatherBuildOutputFilenames();
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                // 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:
                TimeSpan runtime = DateTime.Now - buildStart;

                this.ReportProgress(BuildStep.Completed, "\r\nBuild completed successfully at {0}.  " +
                    "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(OperationCanceledException )
            {
                buildCancelling = true;

                this.ReportError(BuildStep.Canceled, "BE0064", "BUILD CANCELLED BY USER");

                System.Diagnostics.Debug.WriteLine("Build process aborted\r\n");
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);

                var agEx = ex as AggregateException;

                if(agEx != null)
                    foreach(var inEx in agEx.InnerExceptions)
                    {
                        if(message != null)
                            message += "\r\n\r\n";

                        message += inEx.Message + "\r\n" + inEx.StackTrace;
                    }

                var bex = ex as BuilderException;

                do
                {
                    if(message != null)
                        message += "\r\n\r\n";

                    message += ex.Message + "\r\n" + ex.StackTrace;
                    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
            {
                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(componentContainer != null)
                        componentContainer.Dispose();
                }
                catch(Exception ex)
                {
                    // Not much we can do at this point...
                    this.ReportProgress(ex.ToString());
                }
                finally
                {
                    if(swLog != null)
                    {
                        swLog.WriteLine("</buildStep>\r\n</shfbBuild>");
                        swLog.Close();
                        swLog = null;
                    }

                    // If we created a copy of the project, dispose of it and return to the original
                    if(originalProject != null)
                    {
                        project.Dispose();
                        project = originalProject;
                    }

                    if(this.CurrentBuildStep == BuildStep.Completed && !project.KeepLogFile)
                        File.Delete(this.LogFilename);
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Adds references to this container from a MSBuild project.
        /// </summary>
        public void LoadReferencesFromBuildProject(MSBuild.Project buildProject)
        {
            XSharpProjectPackage.Instance.UIThread.MustBeCalledFromUIThread();
            List <ReferenceNode> duplicatedNode = new List <ReferenceNode>();
            BuildResult          buildResult    = this.ProjectMgr.Build(MsBuildTarget.ResolveAssemblyReferences);

            var children = new List <ReferenceNode>();

            foreach (string referenceType in SupportedReferenceTypes)
            {
                bool isAssemblyReference = referenceType == ProjectFileConstants.Reference;
                if (isAssemblyReference && !buildResult.IsSuccessful)
                {
                    continue;
                }

                foreach (var item in MSBuildProject.GetItems(buildProject, referenceType))
                {
                    ProjectElement element = new ProjectElement(this.ProjectMgr, item, false);

                    ReferenceNode node = CreateReferenceNode(referenceType, element);

                    if (node != null)
                    {
                        // Make sure that we do not want to add the item twice to the ui hierarchy
                        // We are using here the UI representation of the Node namely the Caption to find that out, in order to
                        // avoid different representation problems.
                        // Example :<Reference Include="EnvDTE80, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
                        //		  <Reference Include="EnvDTE80" />
                        bool found = false;
                        for (HierarchyNode n = this.FirstChild; n != null && !found; n = n.NextSibling)
                        {
                            if (String.Compare(n.Caption, node.Caption, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            this.AddChild(node);
                            children.Add(node);
                        }
                        else
                        {
                            duplicatedNode.Add(node);
                        }
                    }
                }
            }
            // Now manage duplicates
            if (duplicatedNode.Count > 0)
            {
                // Make a backup first
                string original   = buildProject.FullPath;
                string backupName = Path.ChangeExtension(original, ".backup");
                if (Utilities.DeleteFileSafe(backupName))
                {
                    File.Copy(original, backupName);
                }
                foreach (ReferenceNode node in duplicatedNode)
                {
                    //this.RemoveChild( node );
                    node.Remove(false);
                }
                buildProject.Save(original);
            }
            var references = buildResult.ProjectInstance.GetItems(ProjectFileConstants.ReferencePath);

            //var references = MSBuildProjectInstance.GetItems(buildResult.ProjectInstance, ProjectFileConstants.ReferencePath);
            foreach (var reference in references)
            {
                string fullName = MSBuildItem.GetEvaluatedInclude(reference);
                string name     = Path.GetFileNameWithoutExtension(fullName);
                foreach (var child in children)
                {
                    if (child is XSharpAssemblyReferenceNode && child.Caption == name)
                    {
                        var xChild = child as XSharpAssemblyReferenceNode;
                        xChild.AssemblyPath = fullName;
                        xChild.SetHintPathAndPrivateValue(buildResult.ProjectInstance, reference);
                    }
                }
            }
        }
        internal void CreateSolutionDirProj(MFSolution solution)
        {
            string solutionDir = @"$(SPOCLIENT)\Solutions\" + solution.Name;
            string fullpath = ExpandEnvVars(Path.Combine(solutionDir, "dotnetmf.proj"), "");

            Project proj = LoadProject(fullpath);

            proj.ProjectCollection.UnloadProject(proj);

            proj = new Project();
            proj.Xml.DefaultTargets = "Build";

            try
            {
                ProjectPropertyGroupElement bpg = proj.Xml.AddPropertyGroup();
                bpg.AddProperty("Directory", RemoveSpoClient(solutionDir));
                bpg.AddProperty("MFSettingsFile", Path.Combine(solutionDir, solution.Name + ".settings"));

                ProjectItemGroupElement big = proj.Xml.AddItemGroup();
                foreach (MFProject mfproj in solution.Projects)
                {
                    if (!string.IsNullOrEmpty(mfproj.Directory) && !string.IsNullOrEmpty(mfproj.ProjectPath))
                    {
                        ProjectItemElement bi = big.AddItem("RequiredProjects", Path.Combine(Path.GetFileName(mfproj.Directory), Path.GetFileName(mfproj.ProjectPath)));
                    }
                }

                proj.Xml.AddImport(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Settings");
                proj.Xml.AddImport(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Targets");

                proj.Save(fullpath);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error: loading LibCat file: " + fullpath + "\r\n", e.Message);
            }
        }
        internal void SaveSolutionProj(MFSolution solution)
        {
            if (!string.IsNullOrEmpty(solution.ProjectPath))
            {
                try
                {
                    //if(File.Exists(solution.ProjectPath)
                    string fullpath = ExpandEnvVars(solution.ProjectPath, "");

                    Project proj = LoadProject(fullpath);
                    proj.ProjectCollection.UnloadProject(proj);
                    
                    proj = new Project();
                    proj.Xml.DefaultTargets = "Build";

                    string dir = Path.GetDirectoryName(fullpath);

                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    ProjectPropertyGroupElement mainGrp = proj.Xml.AddPropertyGroup();

                    mainGrp.AddProperty("Author", solution.Author);
                    mainGrp.AddProperty("Description", solution.Description);
                    mainGrp.AddProperty("Documentation", solution.Documentation);
                    mainGrp.AddProperty("PlatformGuid", solution.Guid);

                    if (solution.DefaultISA != null && solution.DefaultISA.Name != null)
                    {
                        ProjectPropertyElement bp = mainGrp.AddProperty("INSTRUCTION_SET", solution.DefaultISA.Name);
                        bp.Condition = solution.DefaultISA.Conditional;
                    }
                    mainGrp.AddProperty("TARGETPLATFORM", solution.Name);
                    mainGrp.AddProperty("PLATFORM", solution.Name);
                    mainGrp.AddProperty("IsSolutionWizardVisible", solution.IsSolutionWizardVisible.ToString());
                    mainGrp.AddProperty("ENDIANNESS", solution.ENDIANNESS.ToString());

                    Dictionary<string,object> nameLookup = new Dictionary<string,object>();

                    foreach (MFProperty prop in solution.Properties)
                    {
                        switch (prop.Name.ToLower())
                        {
                            case "author":
                            case "description":
                            case "documentation":
                            case "platformguid":
                            case "targetplatform":
                            case "platform":
                            case "issolutionwizardvisible":
                            case "endianness":
                            case "tcp_ip_stack":
                            case "instruction_set":
                                // these properties are reset in this method - this prevents duplication
                                break;

                            default:
                                string key = prop.Name.ToLower();
                                if(!nameLookup.ContainsKey(key))
                                {
                                    ProjectPropertyElement bp = mainGrp.AddProperty(prop.Name, prop.Value);
                                    bp.Condition = prop.Condition;
                                    nameLookup[key] = bp;
                                }
                                break;
                        }
                    }


                    MFProject defProj = null;

                    foreach (MFProject prj in solution.Projects)
                    {
                        if (prj.IsClrProject)
                        {
                            defProj = prj;
                            break;
                        }
                    }

                    if (defProj != null)
                    {
                        ///
                        /// If we have the LWIP feature project then we need to add the following property to the 
                        /// solutions settings file
                        /// 
                        bool AddLWIP = false;
                        foreach (MFComponent f in defProj.Features)
                        {
                            if (f.Name.Equals("Network (RTIP)", StringComparison.InvariantCultureIgnoreCase))
                            {
                                AddLWIP = false;
                                break;
                            }
                            else if (f.Name.Equals("Network (LWIP)", StringComparison.InvariantCultureIgnoreCase))
                            {
                                AddLWIP = true;
                            }
                        }
                        if (AddLWIP)
                        {
                            mainGrp.AddProperty("TCP_IP_STACK", "LWIP");
                        }
                    }

                    ProjectItemGroupElement big = proj.Xml.AddItemGroup();

                    string solPath = RemoveSpoClient(Path.GetDirectoryName(solution.ProjectPath));
                    bool fFoundSolPath = false;

                    foreach (MFBuildFile item in solution.Items)
                    {
                        if (string.Equals(item.ItemName, "IncludePaths", StringComparison.InvariantCultureIgnoreCase) &&
                            string.Equals(item.File, solPath, StringComparison.InvariantCultureIgnoreCase))
                        {
                            fFoundSolPath = true;
                        }

                        ProjectItemElement bi = big.AddItem(item.ItemName, item.File);
                        bi.Condition = item.Condition;
                    }

                    if (!fFoundSolPath)
                    {
                        big.AddItem("IncludePaths", solPath);
                    }

                    Processor prc = null;

                    if (!string.IsNullOrEmpty(solution.Processor.Guid))
                    {
                        prc = m_helper.FindProcessor(solution.Processor.Guid);
                    }
                    else
                    {
                        prc = m_helper.FindProcessorByName(solution.Processor.Name);
                        if (prc != null)
                        {
                            solution.Processor.Guid = prc.Guid;
                            solution.Processor.Name = prc.Name;
                            solution.Processor.ProjectPath = prc.ProjectPath;
                        }
                    }

                    if (prc != null)
                    {
                        proj.Xml.AddImport(prc.ProjectPath);
                    }

                    proj.Save(fullpath);

                    
                    if (solution.m_cloneSolution != null)
                    {
                        string cloneRoot = Path.GetDirectoryName(ExpandEnvVars(solution.m_cloneSolution.ProjectPath, "")) + "\\";
                        string newRoot = Path.GetDirectoryName(ExpandEnvVars(solution.ProjectPath, "")) + "\\";
                        CopyClonedFile(cloneRoot + "platform_selector.h", newRoot + "platform_selector.h", solution.m_cloneSolution.Name, solution.Name);

                        ///
                        /// Copy the LWIP_selector file for the cloned solution
                        /// 
                        if (File.Exists(cloneRoot + "lwip_selector.h"))
                        {
                            CopyClonedFile(cloneRoot + "lwip_selector.h", newRoot + "lwip_selector.h", solution.m_cloneSolution.Name, solution.Name);
                        }
                        //CopyClonedFile(cloneRoot + "dotnetmf.proj", newRoot + "dotnetmf.proj", solution.m_cloneSolution.Name, solution.Name);
                        //CopyClonedFiles(cloneRoot + "DeviceCode\\", newRoot + "DeviceCode\\", solution.m_cloneSolution.Name, solution.Name);
                    }

                    ///
                    /// copy the generic lwip_selector file in the case the cloned solution doesn't have one or we are creating a
                    /// new solution with LWIP
                    /// 
                    if (!File.Exists(Path.Combine(dir, "lwip_selector.h")))
                    {
                        string lwipSel = ExpandEnvVars("$(SPOCLIENT)\\DeviceCode\\PAL\\LWIP\\Config\\lwip_selector.h", "");
                        if (File.Exists(lwipSel) && defProj != null)
                        {
                            foreach (MFComponent f in defProj.Features)
                            {
                                if (f.Name.Equals("Network (LWIP)", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    CopyClonedFile(lwipSel, Path.Combine(dir, "lwip_selector.h"), "<TEMPLATE>", solution.Name);
                                    break;
                                }
                            }
                        }
                    }

                    string platSelectorFile = Path.Combine(dir, "platform_selector.h");
                    bool fNewSelector = false;

                    if (!File.Exists(platSelectorFile))
                    {
                        Processor proc = m_helper.FindProcessor(solution.Processor.Guid);

                        if(proc != null)
                        {
                            string template = Path.GetDirectoryName(ExpandEnvVars(proc.ProjectPath, "")) + "\\" + proc.Name + "_template_selector.h";
                            string newRoot = Path.GetDirectoryName(ExpandEnvVars(solution.ProjectPath, "")) + "\\";

                            if (File.Exists(template))
                            {
                                CopyClonedFile(template, newRoot + "platform_selector.h", "<TEMPLATE>", solution.Name);
                                fNewSelector = true;
                            }
                        }
                    }

                    // only modify if we are cloning or creating a new solution
                    if (File.Exists(platSelectorFile))
                    {
                        if (fNewSelector || (solution.m_cloneSolution != null))
                        {
                            FileAttributes attribs = File.GetAttributes(platSelectorFile);

                            if (0 != (attribs & FileAttributes.ReadOnly))
                            {
                                throw new Exception("File Access Exception: File " + platSelectorFile + " is not accessible");
                            }

                            string tmpFile = Path.GetTempFileName();
                            using (TextWriter tw = File.CreateText(tmpFile))
                            {
                                using (TextReader tr = File.OpenText(platSelectorFile))
                                {
                                    string data = tr.ReadToEnd();

                                    Regex rx = new Regex("#define\\s+SYSTEM_CLOCK_HZ\\s+[^\\r^\\n]+", RegexOptions.Singleline);
                                    data = rx.Replace(data, "#define SYSTEM_CLOCK_HZ                 " + solution.SystemClockSpeed.ToString());

                                    rx = new Regex("#define\\s+SLOW_CLOCKS_PER_SECOND\\s+[^\\r^\\n]+", RegexOptions.Singleline);
                                    data = rx.Replace(data, "#define SLOW_CLOCKS_PER_SECOND          " + solution.SlowClockSpeed.ToString());

                                    rx = new Regex("#define\\s+SRAM1_MEMORY_Base\\s+[^\\r^\\n]+", RegexOptions.Singleline);
                                    data = rx.Replace(data, "#define SRAM1_MEMORY_Base   0x" + solution.RamBase.ToString("X08"));

                                    rx = new Regex("#define\\s+SRAM1_MEMORY_Size\\s+[^\\r^\\n]+", RegexOptions.Singleline);
                                    data = rx.Replace(data, "#define SRAM1_MEMORY_Size   0x" + solution.RamLength.ToString("X08"));

                                    rx = new Regex("#define\\s+FLASH_MEMORY_Base\\s+[^\\r^\\n]+", RegexOptions.Singleline);
                                    data = rx.Replace(data, "#define FLASH_MEMORY_Base   0x" + solution.FlashBase.ToString("X08"));

                                    rx = new Regex("#define\\s+FLASH_MEMORY_Size\\s+[^\\r^\\n]+", RegexOptions.Singleline);
                                    data = rx.Replace(data, "#define FLASH_MEMORY_Size   0x" + solution.FlashLength.ToString("X08"));

                                    rx = new Regex("#define\\s+DEBUG_TEXT_PORT\\s+[^\\s]+", RegexOptions.Singleline);
                                    data = rx.Replace(data, "#define DEBUG_TEXT_PORT    " + solution.DebuggerPort);

                                    rx = new Regex("#define\\s+STDIO\\s+[\\w\\d_]+");
                                    data = rx.Replace(data, "#define STDIO              " + solution.DebuggerPort);

                                    rx = new Regex("#define\\s+DEBUGGER_PORT\\s+[^\\s]+", RegexOptions.Singleline);
                                    data = rx.Replace(data, "#define DEBUGGER_PORT      " + solution.DebuggerPort);

                                    rx = new Regex("#define\\s+MESSAGING_PORT\\s+[^\\s]+", RegexOptions.Singleline);
                                    data = rx.Replace(data, "#define MESSAGING_PORT     " + solution.DebuggerPort);

                                    rx = new Regex("#define\\s+RUNTIME_MEMORY_PROFILE__[\\w]+", RegexOptions.Singleline);
                                    data = rx.Replace(data, "#define RUNTIME_MEMORY_PROFILE__" + solution.MemoryProfile);

                                    tw.Write(data);
                                }
                            }

                            File.Delete(platSelectorFile);
                            File.Move(tmpFile, platSelectorFile);
                        }
                    }
                    else
                    {
                        using (TextWriter tw = File.CreateText(platSelectorFile))
                        {
                            tw.WriteLine(string.Format("#ifndef _PLATFORM_{0}_SELECTOR_H_\r\n#define _PLATFORM_{0}_SELECTOR_H_ 1", solution.Name));

                            tw.WriteLine(string.Format("#define HAL_SYSTEM_NAME                 \"{0}\"", solution.Name));
                            tw.WriteLine(string.Format("#define PLATFORM_{0}    ", prc.Name.ToUpper()));
                            tw.WriteLine(string.Format("#define PLATFORM_{0}_{1}", prc.PlatformFamily.ToUpper(), prc.Name.ToUpper()));
                            tw.WriteLine(string.Format("#define PLATFORM_{0}_{1}", prc.PlatformFamily.ToUpper(), solution.Name.ToUpper()));
                            if (0 == string.Compare(prc.Name, "MC9328", true))
                            {
                                tw.WriteLine("#define PLATFORM_ARM_MC9328MXL");
                            }

                            tw.WriteLine("#define PLATFORM_SUPPORTS_SOFT_REBOOT   TRUE");

                            tw.WriteLine(string.Format("#define SYSTEM_CLOCK_HZ                 {0}", solution.SystemClockSpeed));
                            tw.WriteLine(string.Format("#define SLOW_CLOCKS_PER_SECOND          {0}", solution.SlowClockSpeed));
                            tw.WriteLine("#define CLOCK_COMMON_FACTOR             1");
                            tw.WriteLine("#define SLOW_CLOCKS_TEN_MHZ_GCD         1");
                            tw.WriteLine("#define SLOW_CLOCKS_MILLISECOND_GCD     1");

                            tw.WriteLine(string.Format("#define SRAM1_MEMORY_Base               0x{0:X08}", solution.RamBase));
                            tw.WriteLine(string.Format("#define SRAM1_MEMORY_Size               0x{0:X08}", solution.RamLength));
                            tw.WriteLine(string.Format("#define FLASH_MEMORY_Base               0x{0:X08}", solution.FlashBase));
                            tw.WriteLine(string.Format("#define FLASH_MEMORY_Size               0x{0:X08}", solution.FlashLength));

                            tw.WriteLine(@"
#define TXPROTECTRESISTOR               RESISTOR_DISABLED
#define RXPROTECTRESISTOR               RESISTOR_DISABLED
#define CTSPROTECTRESISTOR              RESISTOR_DISABLED
#define RTSPROTECTRESISTOR              RESISTOR_DISABLED
");

                            tw.WriteLine(@"
#define GLOBAL_LOCK(x)             SmartPtr_IRQ x
#define DISABLE_INTERRUPTS()       SmartPtr_IRQ::ForceDisabled()
#define ENABLE_INTERRUPTS()        SmartPtr_IRQ::ForceEnabled()
#define INTERRUPTS_ENABLED_STATE() SmartPtr_IRQ::GetState()
#define GLOBAL_LOCK_SOCKETS(x)     SmartPtr_IRQ x

#if defined(_DEBUG)
#define ASSERT_IRQ_MUST_BE_OFF()   ASSERT(!SmartPtr_IRQ::GetState())
#define ASSERT_IRQ_MUST_BE_ON()    ASSERT( SmartPtr_IRQ::GetState())
#else
#define ASSERT_IRQ_MUST_BE_OFF()
#define ASSERT_IRQ_MUST_BE_ON()
#endif

#define TOTAL_USART_PORT       1
#define COM1                   ConvertCOM_ComHandle(0)
#define COM2                   ConvertCOM_ComHandle(1)

#define TOTAL_USB_CONTROLLER   1
#define USB1                   ConvertCOM_UsbHandle(0)

#define TOTAL_SOCK_PORT        0

#define TOTAL_DEBUG_PORT       1
#define COM_DEBUG              ConvertCOM_DebugHandle(0)

#define COM_MESSAGING          ConvertCOM_MessagingHandle(0)

#define USART_TX_IRQ_INDEX(x)       ( (x) ? 0 : 0 )     // TODO set right indexes
#define USART_DEFAULT_PORT          COM1
#define USART_DEFAULT_BAUDRATE      115200

#define USB_IRQ_INDEX               0                   // TODO set right index


#define PLATFORM_DEPENDENT_TX_USART_BUFFER_SIZE    512  // there is one TX for each usart port
#define PLATFORM_DEPENDENT_RX_USART_BUFFER_SIZE    512  // there is one RX for each usart port
#define PLATFORM_DEPENDENT_USB_QUEUE_PACKET_COUNT  32  // there is one queue for each pipe of each endpoint and the size of a single packet is sizeof(USB_PACKET64) == 68 bytes
");


                            tw.WriteLine(string.Format("#define DEBUG_TEXT_PORT         {0}", solution.DebuggerPort));
                            tw.WriteLine(string.Format("#define STDIO                   {0}", solution.DebuggerPort));
                            tw.WriteLine(string.Format("#define DEBUGGER_PORT           {0}", solution.DebuggerPort));
                            tw.WriteLine(string.Format("#define MESSAGING_PORT          {0}", solution.DebuggerPort));

                            tw.WriteLine(string.Format("#define RUNTIME_MEMORY_PROFILE__{0} 1", solution.MemoryProfile));

                            tw.WriteLine("#include <processor_selector.h>");

                            tw.WriteLine(string.Format("#endif // _PLATFORM_{0}_SELECTOR_H_ 1", solution.Name));
                        }
                    }

                    //foreach (MFProject prj in solution.Projects)
                    //{
                    //    SaveProjectProj(prj);
                    //}
                }
                catch
                {
                    Console.WriteLine("Error: Unable to save solution file " + solution.ProjectPath);
                }
            }
        }
        internal void SaveProcessorProj(Processor proc)
        {
            if (!string.IsNullOrEmpty(proc.ProjectPath))
            {
                try
                {
                    string fullpath = ExpandEnvVars(proc.ProjectPath, "");

                    Project proj = LoadProject(fullpath);
                    proj.ProjectCollection.UnloadProject(proj);

                    proj = new Project();
                    proj.Xml.DefaultTargets = "Build";

                    Dictionary<string, string> tbl = new Dictionary<string, string>();
                    tbl["PlatformFamily"] = "PLATFORM_FAMILY";

                    ProjectPropertyGroupElement bpg = SaveStringProps(proj, proc, tbl);

                    if (!string.IsNullOrEmpty(proc.DefaultISA))
                    {
                        ProjectPropertyElement bp = bpg.AddProperty("INSTRUCTION_SET", proc.DefaultISA);
                        bp.Condition = "'$(INSTRUCTION_SET)'==''";
                    }


                    foreach (MFProperty prop in proc.Properties)
                    {
                        ProjectPropertyElement bp = bpg.AddProperty(prop.Name, prop.Value);
                        bp.Condition = prop.Condition;
                    }

                    bpg.AddProperty("TARGETPROCESSOR", proc.Name);
                    bpg.AddProperty("TARGETCODEBASE", proc.Name);
                    bpg.AddProperty("TARGETCODEBASETYPE", "Native");

                    SaveBuildToolRef(proc.BuildToolOptions, proj);

                    ProjectItemGroupElement big = proj.Xml.AddItemGroup();
                    big.AddItem("IncludePaths", RemoveSpoClient(Path.GetDirectoryName(proc.ProjectPath)));

                    //ProjectPropertyGroupElement bpg = proj.Xml.AddPropertyGroup();

                    //bpg.AddProperty("PKUI_Processor", SerializeXml(proc));

                    proj.Save(fullpath);
                }
                catch(Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("Error: Unable to save procesor file " + proc.ProjectPath + "\r\n" + e.Message);
                }
            }
        }
        private void SaveDependentLibs(Project proj, List<MFComponent> deps)
        {
            foreach (MFComponent comp in deps)
            {
                if (comp.ComponentType == MFComponentType.Library)
                {
                    ProjectItemGroupElement big = proj.Xml.AddItemGroup();
                    Library lib = null;

                    if (!string.IsNullOrEmpty(comp.ProjectPath) && Path.GetExtension(comp.ProjectPath).ToUpper() == ".PROJ")
                    {
                        lib = LoadLibraryProj(comp.ProjectPath, Path.GetDirectoryName(proj.FullPath), true);
                    }

                    if (lib == null)
                    {
                        lib = m_helper.FindLibrary(comp);
                    }

                    if (lib != null)
                    {
                        string tag = "DriverLibs";
                        string condProj = comp.Conditional;
                        string condLib = comp.Conditional;

                        if (lib.PlatformIndependent)
                        {
                            tag = "PlatformIndependentLibs";
                        }

                        // normalize the path (no xxx\..\yyy in the path)
                        if (string.IsNullOrEmpty(lib.ProjectPath))
                        {
                            lib.ProjectPath = comp.ProjectPath;
                        }

                        string fullpath = ExpandEnvVars(lib.ProjectPath, "");
                        fullpath = Path.GetFullPath(fullpath);
                        fullpath = ConvertPathToEnv(fullpath);

                        ProjectItemElement bi2 = big.AddItem("RequiredProjects", fullpath);
                        bi2.Condition = condProj;

                        ProjectItemElement bi = big.AddItem(tag, lib.LibraryFile);
                        bi.Condition = condLib;

                        proj.Save(proj.FullPath);
                    }
                    else
                    {
                        Console.WriteLine("Error: unknown library dependency while saving project file " + comp.Name);
                    }
                }
                else
                {
                    Console.WriteLine("Error: unexpected component dependency while saving project file " + comp.Name);
                }
            }
        }
        public override bool Execute()
        {

            bool result = true;

            string file = Path.Combine(m_stubsPath, m_name + ".featureproj");

            try
            {

                _EVAL.Project proj = new _EVAL.Project();

                Microsoft.Build.Evaluation.ProjectCollection  projCol = proj.ProjectCollection;

                ProjectPropertyGroupElement bpg = proj.Xml.AddPropertyGroup(); 
                bpg.AddProperty("FeatureName", m_name);
                bpg.AddProperty("Guid", System.Guid.NewGuid().ToString("B"));
                bpg.AddProperty("Description", "<Add Feature Description Here>");
                bpg.AddProperty("Groups", "");

                ProjectItemGroupElement big = proj.Xml.AddItemGroup();
                big.AddItem("InteropFeature", Path.GetFileNameWithoutExtension(m_assemblyName).Replace('.', '_'));
                big.AddItem("DriverLibs", Path.GetFileNameWithoutExtension(m_assemblyName).Replace('.', '_') + ".$(LIB_EXT)");
                big.AddItem("MMP_DAT_CreateDatabase", "$(BUILD_TREE_CLIENT)\\pe\\$(ENDIANNESS)\\" + m_assemblyName);
                big.AddItem("RequiredProjects", Path.Combine(m_stubsPath, m_nativeProjectFile));

            
                proj.Save(file);

                // after save, unload the project, so that if rebuilds it is able to regenerate the project file.   
                ProjectRootElement pre = proj.Xml;
                projCol.UnloadProject(proj);
                projCol.UnloadProject(pre);

            }
            catch (Exception e)
            {
                Log.LogError("Error trying to create feature project file \"" + file + "\": " + e.Message);
                result = false;
            }               

            return result;
        }
        public static string createProjectFile(this string projectName, string sourceFile, string pathToAssemblies, string targetDir, List<string> extraEmbebbedResources, Action<List<string>> beforeAddingReferences, Action<List<string>> beforeEmbedingFiles)
        {
            var apiCreateExe = new API_Create_Exe();
            if (sourceFile.empty())
                return null;

            sourceFile.file_Copy(targetDir);
            var assemblyFiles = pathToAssemblies.files(false,"*.dll","*.exe");

            var projectFile =  targetDir.pathCombine(projectName + ".csproj");

            var projectCollection = new ProjectCollection();

            var outputPath = "bin";
            Project project = new Project(projectCollection);
            project.SetProperty("DefaultTargets", "Build");

            var propertyGroup = project.Xml.CreatePropertyGroupElement();
            project.Xml.InsertAfterChild(propertyGroup, project.Xml.LastChild);
            //propertyGroup.AddProperty("TargetFrameworkVersion", "v4.0");
            propertyGroup.AddProperty("TargetFrameworkVersion", "v4.5");
            propertyGroup.AddProperty("ProjectGuid", Guid.NewGuid().str());
            propertyGroup.AddProperty("OutputType", "WinExe");
            propertyGroup.AddProperty("OutputPath", outputPath);
            propertyGroup.AddProperty("AssemblyName", projectName);
            propertyGroup.AddProperty("PlatformTarget", "x86");

            var targets = project.Xml.AddItemGroup();
            targets.AddItem("Compile", sourceFile.fileName());

            var references = project.Xml.AddItemGroup();
            references.AddItem("Reference", "mscorlib");
            references.AddItem("Reference", "System");
            references.AddItem("Reference", "System.Core");
            references.AddItem("Reference", "System.Windows.Forms");

            beforeAddingReferences.invoke(assemblyFiles);
            foreach(var assemblyFile in assemblyFiles)
            {
                var assembly =  assemblyFile.fileName().assembly(); // first load from local AppDomain (so that we don't lock the dll in the target folder)
                if (assembly.isNull())
                    assembly  =  assemblyFile.assembly();
                //only load the O2 assemblies
                if (assembly.str().lower().contains("o2") || assembly.str().lower().contains("fluentsharp"))
                {
                    var item = references.AddItem("Reference",assemblyFile.fileName_WithoutExtension());
                    item.AddMetadata("HintPath",assemblyFile.fileName());
                    item.AddMetadata("Private",@"False");
                }
            }

            var gzAssemblyFiles = new List<string>();
            beforeEmbedingFiles.invoke(assemblyFiles);

            var embeddedResources = project.Xml.AddItemGroup();

            foreach(var assemblyFile in gzAssemblyFiles)
                embeddedResources.AddItem("EmbeddedResource",assemblyFile.fileName());

            var defaultIcon = "O2Logo.ico";
            extraEmbebbedResources.add(assemblyFiles);

            foreach(var extraResource in extraEmbebbedResources)
            {
                if (extraResource.extension(".dll") || extraResource.extension(".exe"))
                {
                    //ignore these since they are already embded in the FluentSharp.REPL.exe dll
                    if(extraEmbebbedResources.fileNames().contains("FluentSharp.REPL.exe") &&
                       (extraResource.contains("Mono.Cecil.dll" )))
                    {
                        continue;
                    }
                    var gzFile = targetDir.pathCombine(extraResource.fileName() + ".gz");
                    extraResource.fileInfo().compress(gzFile);
                    extraResource.file_Copy(targetDir);
                    embeddedResources.AddItem("EmbeddedResource",gzFile.fileName());
                }
                else
                {
                    extraResource.file_Copy(targetDir);
                    embeddedResources.AddItem("EmbeddedResource",extraResource.fileName());
                    if (extraResource.extension(".ico"))
                        defaultIcon = extraResource;
                }
            }

            //add two extra folders (needs refactoring)
            Action<string> addSpecialResources =
                (resourceFolder)=>{
                                      var folder = targetDir.pathCombine(resourceFolder);
                                      if (folder.dirExists())
                                      {
                                          "found {0} Folder so adding it as a zip:{1}".debug(resourceFolder, folder);
                                          var zipFile = folder.zip_Folder(folder + ".zip");
                                          embeddedResources.AddItem("EmbeddedResource",zipFile.fileName());
                                          if (folder.files("*.ico").size()>0)
                                          {
                                              var icon = folder.files("*.ico").first();
                                              "Found default application ICON: {0}".debug(icon);
                                              defaultIcon = icon;
                                          }
                                      }
                };
            addSpecialResources("O2.Platform.Scripts");

            //now add the icon
            propertyGroup.AddProperty("ApplicationIcon", defaultIcon);

            var importElement = project.Xml.CreateImportElement(@"$(MSBuildToolsPath)\Microsoft.CSharp.targets");
            project.Xml.InsertAfterChild(importElement, project.Xml.LastChild);

            project.Save(projectFile);

            var o2Logo = apiCreateExe.path_O2Logo_Icon();
            o2Logo.file_Copy(targetDir);

            return projectFile;
        }
Ejemplo n.º 29
0
        private void UpdateProjectFileReferenceHintPaths(DirectoryInfo solutionRoot, Project project, string projectPath, IEnumerable<KeyValuePair<string, List<IPackage>>> resolvedMappings, ICollection<ProjectItem> references)
        {
            foreach (var mapping in resolvedMappings)
            {
                var referenceMatch = references.FirstOrDefault(r => ResolveProjectReferenceItemByAssemblyName(r, mapping.Key));
                if (referenceMatch != null)
                {
                    var includeName = referenceMatch.EvaluatedInclude.Contains(',') ? referenceMatch.EvaluatedInclude.Split(',')[0] : referenceMatch.EvaluatedInclude;
                    var includeVersion = referenceMatch.EvaluatedInclude.Contains(',') ? referenceMatch.EvaluatedInclude.Split(',')[1].Split('=')[1] : null;
                    var package = mapping.Value.OrderBy(p => p.GetFiles().Count()).First();

                    LogHintPathRewriteMessage(package, includeName, includeVersion);

                    var fileLocation = GetFileLocationFromPackage(package, mapping.Key);
                    var newHintPathFull  = Path.Combine(solutionRoot.FullName, "packages", package.Id, fileLocation);
                    var newHintPathRelative = String.Format(GetRelativePath(projectPath, newHintPathFull));
                    //TODO make version available, currently only works for non versioned package directories...
                    referenceMatch.SetMetadataValue("HintPath", newHintPathRelative);
                }
            }
            project.Save();
        }
Ejemplo n.º 30
0
        public void RemoveMetadataImported()
        {
            Assert.Throws<InvalidOperationException>(() =>
            {
                string file = null;

                try
                {
                    file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                    Project import = new Project();
                    ProjectItem item = import.AddItem("i", "i1")[0];
                    item.SetMetadataValue("m", "m0");
                    import.Save(file);

                    ProjectRootElement xml = ProjectRootElement.Create();
                    xml.AddImport(file);
                    Project project = new Project(xml);

                    item = Helpers.GetFirst(project.GetItems("i"));

                    item.RemoveMetadata("m");
                }
                finally
                {
                    File.Delete(file);
                }
            }
           );
        }
Ejemplo n.º 31
0
        private void CreateNuGetScaffolding(SharedPackageRepository sharedPackagesRepository, List<ManifestDependency> manifestDependencies, IEnumerable<KeyValuePair<string, List<IPackage>>> resolvedMappings, FileInfo projectFileInfo, Project project, List<string> projectDependencies)
        {
            //Now, create the packages.config for the resolved packages, and update the repositories.config
            Console.WriteLine("Creating packages.config");
            var packagesConfigFilePath = Path.Combine(projectFileInfo.Directory.FullName + "\\", "packages.config");
            var packagesConfig = new PackageReferenceFile(packagesConfigFilePath);
            foreach (var referenceMapping in resolvedMappings)
            {
                //TODO We shouldnt need to resolve this twice....
                var package = referenceMapping.Value.OrderBy(p => p.GetFiles().Count()).First();
                if (!packagesConfig.EntryExists(package.Id, package.Version))
                    packagesConfig.AddEntry(package.Id, package.Version);
                if (NuSpec && manifestDependencies.All(m => m.Id != package.Id))
                {
                    manifestDependencies.Add(new ManifestDependency {Id = package.Id});
                }
            }

            //This is messy...refactor
            //For any resolved project dependencies, add a manifest dependency if we are doing nuspecs
            if (NuSpec)
            {
                foreach (var projectDependency in projectDependencies)
                {
                    if (manifestDependencies.All(m => m.Id != projectDependency))
                    {
                        manifestDependencies.Add(new ManifestDependency {Id = projectDependency});
                    }
                }
            }
            //Register the packages.config
            sharedPackagesRepository.RegisterRepository(packagesConfigFilePath);

            //Add the packages.config to the project content, otherwise later versions of the VSIX fail...
            if (!project.GetItems("None").Any(i => i.UnevaluatedInclude.Equals("packages.config")))
            {
                project.Xml.AddItemGroup().AddItem("None", "packages.config");
                project.Save();
            }
        }
Ejemplo n.º 32
0
        private List<IPackage> UpdateTargetsInternal()
        {
            var projectCollection = new ProjectCollection();
            var project = new Project(projectCollection);

            var commonPropertyGroup = project.Xml.AddPropertyGroup();
            var target = project.Xml.AddTarget("CheckPackages");
            project.Xml.InitialTargets = "CheckPackages";

            var packages = GetRootPackagesInDependencyOrder();
            foreach (var package in packages)
            {

                if (package.Tags != null && package.Tags.Contains("internal"))
                {
                    continue; // We don't want to polute the Common.targets file with internal packages
                }

                var packageVar = GetPackageVersionVariable(package.Id);
                var packageTarget = String.Format(@"$(MSBuildThisFileDirectory)..\{0}\{1}.{2}\Targets\{1}.targets", RepositoryPath, package.Id, "$(" + packageVar + ")");

                // Add import
                // <Import Project="..\Packages\Paradox$(SiliconStudioPackageParadoxVersion)\Targets\Paradox.targets" Condition="Exists('..\Packages\Paradox.$(SiliconStudioPackageParadoxVersion)\Targets\Paradox.targets')" />
                var importElement = project.Xml.AddImport(packageTarget);
                importElement.Condition = String.Format(@"Exists('{0}')", packageTarget);

                // Add common properties
                var packageVarSaved = packageVar + "Saved";
                var packageVarInvalid = packageVar + "Invalid";
                var packageVarRevision = packageVar + "Revision";

                // <SiliconStudioPackageParadoxVersionSaved>$(SiliconStudioPackageParadoxVersion)</SiliconStudioPackageParadoxVersionSaved>
                commonPropertyGroup.AddProperty(packageVarSaved, "$(" + packageVar + ")");

                // List all the correspondances: Major.minor -> latest installed explicit version

                // Get all the related versions of the same package also installed, and order by Major.Minor
                var allMajorVersions = LocalRepository.FindPackagesById(package.Id).GroupBy(p => p.Version.Version.Major, p => p);
                foreach (var major in allMajorVersions)
                {
                    var majorVersion = major.Key;
                    var minorPkg = major.GroupBy(p => p.Version.Version.Minor, p => p);
                    foreach (var minor in minorPkg)
                    {
                        var latestPackage = minor.First();
                        // <SiliconStudioPackageParadoxVersionRevision Condition="'$(SiliconStudioPackageParadoxVersion)' == '0.5'">0.5.0-alpha09</SiliconStudioPackageParadoxVersionRevision>
                        var revisionVersionProperty = commonPropertyGroup.AddProperty(packageVarRevision, latestPackage.Version.ToString());
                        revisionVersionProperty.Condition = "'$(" + packageVar + ")' == '" + majorVersion + "." + minor.Key + "'";
                    }
                }

                // Replace the version Major.minor by the full revision name
                // <SiliconStudioPackageParadoxVersion>$(SiliconStudioPackageParadoxVersionRevision)</SiliconStudioPackageParadoxVersion>
                commonPropertyGroup.AddProperty(packageVar, "$(" + packageVarRevision + ")");

                // <SiliconStudioPackageParadoxVersionInvalid Condition="'$(SiliconStudioPackageParadoxVersion)' == '' or !Exists('..\Packages\Paradox.$(SiliconStudioPackageParadoxVersion)\Targets\Paradox.targets')">true</SiliconStudioPackageParadoxVersionInvalid>
                commonPropertyGroup.AddProperty(packageVarInvalid, "true").Condition = "'$(" + packageVar + ")' == '' or !" + importElement.Condition;

                // <SiliconStudioPackageParadoxVersion Condition="'$(SiliconStudioPackageParadoxVersionInvalid)' == 'true'">1.0.0-alpha01</SiliconStudioPackageParadoxVersion>
                // Special case: if major version 1.0 still exists, use it as default (new projects should be created with props file)
                var defaultPackageVersion = LocalRepository.FindPackagesById(package.Id).Select(x => x.Version).FirstOrDefault(x => x.Version.Major == 1 && x.Version.Minor == 0) ?? package.Version;
                var invalidProperty = commonPropertyGroup.AddProperty(packageVar, defaultPackageVersion.ToString());
                invalidProperty.Condition = "'$(" + packageVarInvalid + ")' == 'true'";

                // Add in CheckPackages target
                // <Warning Condition="$(SiliconStudioPackageParadoxVersionInvalid) == 'true'"  Text="Package Paradox $(SiliconStudioPackageParadoxVersionSaved) not found. Use version $(SiliconStudioPackageParadoxVersion) instead"/>
                // Disable Warning and use only Message for now
                // TODO: Provide a better diagnostic message (in case the version is really not found or rerouted to a newer version)
                var warningTask = target.AddTask("Message");
                warningTask.Condition = invalidProperty.Condition;
                warningTask.SetParameter("Text", String.Format("Package {0} with version [$({1})] not found. Use version $({2}) instead", package.Id, packageVarSaved, packageVar));
            }

            var targetFile = Path.Combine(RootDirectory, DefaultTargets);
            if (File.Exists(targetFile))
            {
                File.Delete(targetFile);
            }
            project.Save(targetFile);

            return packages;
        }
Ejemplo n.º 33
0
        protected virtual MSBuild.Project CreateUserBuildProject()
        {
            if (!File.Exists(UserFileName))
            {
                MSBuild.Project userBuildProject = new MSBuild.Project();
                userBuildProject.Save(UserFileName);
            }

            return BuildEngine.LoadProject(UserFileName);
        }
Ejemplo n.º 34
0
        public void SavingProjectClearsDirtyBit()
        {
            string contents = ObjectModelHelpers.CleanupFileContents(@"<Project xmlns='msbuildnamespace'/>");
            Project project = new Project(XmlReader.Create(new StringReader(contents)));

            Assert.True(project.Xml.HasUnsavedChanges); // Not dirty for saving
            Assert.False(project.IsDirty); // "1" // was evaluated on load

            string file = null;
            try
            {
                file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                project.Save(file);
            }
            finally
            {
                if (file != null)
                {
                    File.Delete(file);
                }
            }

            Assert.False(project.Xml.HasUnsavedChanges); // Not dirty for saving
            Assert.True(project.IsDirty); // "2" // Dirty for reevaluation, because the project now has gotten a new file name
        }
        internal void SaveLibraryProj(Library lib)
        {
            if (!string.IsNullOrEmpty(lib.ProjectPath))
            {
                string fullpath = ExpandEnvVars(lib.ProjectPath, "");

                Project proj = LoadProject(fullpath);

                proj.ProjectCollection.UnloadProject(proj);

                proj = new Project();
                proj.Xml.DefaultTargets = "Build";

                try
                {
                    // save properties first
                    Dictionary<string, string> tbl = new Dictionary<string, string>();
                    tbl["Name"] = "AssemblyName";
                    tbl["Guid"] = "ProjectGuid";

                    ProjectPropertyGroupElement bpg = SaveStringProps(proj, lib, tbl);

                    List<MFProperty> delayedProps = new List<MFProperty>();
                    foreach (MFProperty prop in lib.Properties)
                    {
                        if (!prop.Name.Contains("$(") && !prop.Condition.Contains("$("))
                        {
                            ProjectPropertyElement bp = bpg.AddProperty(prop.Name, prop.Value);
                            bp.Condition = prop.Condition;
                        }
                        else
                        {
                            delayedProps.Add(prop);
                        }
                    }
                    bpg.AddProperty("PlatformIndependentBuild", lib.PlatformIndependent.ToString().ToLower());
                    bpg.AddProperty("Version", lib.Version.Major + "." + lib.Version.Minor + "." + lib.Version.Revision + "." + lib.Version.Build);
                    
                    // add standard import
                    proj.Xml.AddImport(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Settings");

                    proj.Save(fullpath);

                    bpg = proj.Xml.AddPropertyGroup();
                    foreach (MFProperty prop in delayedProps)
                    {
                        ProjectPropertyElement bp = bpg.AddProperty(prop.Name, prop.Value);
                        bp.Condition = prop.Condition;
                    }

                    // add item group
                    SaveCompileItems(proj, lib.FastCompileFiles, lib.HeaderFiles, lib.SourceFiles, lib.OtherFiles, lib.IncludePaths);

                    ProjectItemGroupElement big = proj.Xml.AddItemGroup();
                    foreach (MFComponent cmp in lib.Dependencies)
                    {
                        switch (cmp.ComponentType)
                        {
                            case MFComponentType.Library:
                                Library l = m_helper.FindLibrary(cmp);
                                if (l != null)
                                {
                                    ProjectItemElement bi = big.AddItem("RequiredProjects", ConvertPathToEnv(l.ProjectPath));
                                    bi.Condition = cmp.Conditional;
                                }
                                else if(!string.IsNullOrEmpty(cmp.ProjectPath))
                                {
                                    ProjectItemElement bi = big.AddItem("RequiredProjects", ConvertPathToEnv(cmp.ProjectPath));
                                    bi.Condition = cmp.Conditional;                                    
                                }
                                break;
                            case MFComponentType.LibraryCategory:
                                ProjectImportElement pie = proj.Xml.AddImport(cmp.ProjectPath);
                                pie.Condition = cmp.Conditional;
                                break;
                            default:
                                System.Diagnostics.Debug.Assert(false);
                                break;
                        }
                    }

                    foreach(ProjectTargetElement targ in lib.Targets)
                    {
                        ProjectTargetElement t = proj.Xml.AddTarget(targ.Name);

                        t.Condition = targ.Condition;
                        t.DependsOnTargets = targ.DependsOnTargets;
                        t.Inputs = targ.Inputs;
                        t.Outputs = targ.Outputs;

                        foreach (ProjectTaskElement task in targ.Tasks)
                        {
                            ProjectTaskElement tsk = t.AddTask(task.Name);
                            tsk.Condition = task.Condition;
                            tsk.ContinueOnError = task.ContinueOnError;

                            foreach (KeyValuePair<string,string> param in task.Parameters)
                            {
                                tsk.SetParameter(param.Key, param.Value);
                            }
                        }
                    }

                    proj.Xml.AddImport(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Targets");
                    
                    proj.Save(fullpath);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("Error: saving Library file: " + fullpath + "\r\n", e.Message);
                }
            }
        }
Ejemplo n.º 36
0
        public void RemoveSeveralItemsExpandExpression()
        {
            string projectOriginalContents = ObjectModelHelpers.CleanupFileContents(@"
                <Project ToolsVersion='msbuilddefaulttoolsversion' DefaultTargets='Build' xmlns='msbuildnamespace'>
                    <ItemGroup>
                        <i Include='i1;i2' />
                        <j Include='@(i);j2' />
                    </ItemGroup>
                </Project>
                ");
            Project project = new Project(XmlReader.Create(new StringReader(projectOriginalContents)));

            project.RemoveItems(project.GetItems("j").Take(2));
            Assert.Equal(3, project.Items.Count());

            StringWriter writer = new StringWriter();
            project.Save(writer);

            string projectExpectedContents = ObjectModelHelpers.CleanupFileContents(@"
                <Project ToolsVersion='msbuilddefaulttoolsversion' DefaultTargets='Build' xmlns='msbuildnamespace'>
                    <ItemGroup>
                        <i Include='i1;i2' />
                        <j Include='j2' />
                    </ItemGroup>
                </Project>
                ");

            Helpers.CompareProjectXml(projectExpectedContents, writer.ToString());
        }
        internal void SaveProjectProj(MFProject mfproj)
        {
            if (!string.IsNullOrEmpty(mfproj.ProjectPath))
            {
                try
                {
                    string fullpath = ExpandEnvVars(mfproj.ProjectPath, "");
                    string dir = Path.GetDirectoryName(fullpath);

                    // normalize the path (no xxx\..\yyy)
                    fullpath = Path.GetFullPath(fullpath);
                    mfproj.ProjectPath = ConvertPathToEnv(fullpath);

                    Project proj = LoadProject(fullpath);

                    // clear the project
                    proj.ProjectCollection.UnloadProject(proj);

                    proj = new Project();
                    proj.Xml.DefaultTargets = "Build";

                    proj.FullPath = fullpath;

                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    mfproj.Directory = RemoveSpoClient(Path.GetDirectoryName(fullpath));

                    Dictionary<string, string> tbl = new Dictionary<string, string>();
                    tbl["Name"] = "AssemblyName";
                    tbl["SettingsFile"] = "MFSettingsFile";
                    tbl["Guid"] = "ProjectGuid";

                    ProjectPropertyGroupElement bpg = SaveStringProps(proj, mfproj, tbl);

                    ProjectImportElement pi = proj.Xml.AddImport(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Settings");

                    if (mfproj.IsClrProject)
                    {
                        proj.Xml.AddImport(@"$(SPOCLIENT)\tools\Targets\Microsoft.SPOT.Build.Targets");
                    }

                    proj.Save(fullpath);

                    bpg = proj.Xml.AddPropertyGroup();
                    foreach (MFProperty prop in mfproj.Properties)
                    {
                        if(!tbl.ContainsKey(prop.Name) || tbl[prop.Name] != prop.Value)
                        {
                            ProjectPropertyElement bp = bpg.AddProperty(prop.Name, prop.Value);
                            bp.Condition = prop.Condition;
                            tbl[prop.Name] = prop.Value;
                        }
                    }

                    if (mfproj.BuildTool != null)
                    {
                        List<BuildToolRef> lst = new List<BuildToolRef>();
                        lst.Add(mfproj.BuildTool);
                        SaveBuildToolRef(lst, proj);
                    }

                    if (mfproj.ScatterFile != null)
                    {
                        bpg.AddProperty("EXEScatterFileDefinition", mfproj.ScatterFile.File);
                    }

                    ProjectItemGroupElement bigCompile = proj.Xml.AddItemGroup();

                    // copy from cloned solution if necessary
                    SaveCompileItems(proj, mfproj.FastCompileFiles, mfproj.HeaderFiles, mfproj.SourceFiles, mfproj.OtherFiles, mfproj.IncludePaths);

                    ProjectItemGroupElement big = null;
                    foreach (MFComponent feat in mfproj.Features)
                    {
                        ProjectImportElement pie = proj.Xml.AddImport(feat.ProjectPath);
                        pie.Condition = feat.Conditional;
                    }

                    proj.Save(fullpath);

                    big = null;
                    foreach (string interop in mfproj.InteropFeatures)
                    {
                        if (big == null)
                        {
                            big = proj.Xml.AddItemGroup();
                        }

                        big.AddItem("InteropFeature", interop);
                    }
                    if (mfproj.IsClrProject)
                    {
                        proj.Xml.AddImport(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Interop.Settings");
                    }

                    proj.Save(fullpath);

                    SaveDependentLibs(proj, mfproj.Libraries);

                    big = null;
                    foreach (string asm in mfproj.ExtraAssemblies)
                    {
                        if (big == null)
                        {
                            big = proj.Xml.AddItemGroup();
                        }

                        big.AddItem("MMP_DAT_CreateDatabase", asm);
                    }

                    foreach (ProjectTargetElement targ in mfproj.Targets)
                    {
                        ProjectTargetElement t = proj.Xml.AddTarget(targ.Name);

                        t.Condition = targ.Condition;
                        t.DependsOnTargets = targ.DependsOnTargets;
                        t.Inputs = targ.Inputs;
                        t.Outputs = targ.Outputs;

                        foreach (ProjectTaskElement task in targ.Tasks)
                        {
                            ProjectTaskElement tsk = t.AddTask(task.Name);
                            tsk.Condition = task.Condition;
                            tsk.ContinueOnError = task.ContinueOnError;

                            foreach (KeyValuePair<string,string> param in task.Parameters)
                            {
                                tsk.SetParameter(param.Key, param.Value);
                            }
                        }
                    }

                    proj.Xml.AddImport(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Targets");

                    proj.Save(fullpath);

                    // post process project file to assure proper placement of imports
                    XmlDocument doc = new XmlDocument();
                    doc.Load(fullpath);

                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                    nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003");

                    XmlNode root = doc.DocumentElement;

                    string expr = "descendant::ns:PropertyGroup";
                    XmlNode dst = root.SelectSingleNode(expr, nsmgr);
                    expr = @"descendant::ns:Import";
                    XmlNodeList imports = root.SelectNodes(expr, nsmgr);

                    XmlNode sysSettings = null;
                    XmlNode bldTargs = null;
                    XmlNode intSettings = null;
                    List<XmlNode> featureProjs = new List<XmlNode>();

                    foreach (XmlNode n in imports)
                    {
                        string prj = n.Attributes["Project"].InnerText;

                        if (prj.Equals(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Settings", StringComparison.OrdinalIgnoreCase))
                        {
                            sysSettings = n;
                        }
                        else if (prj.Equals(@"$(SPOCLIENT)\tools\Targets\Microsoft.SPOT.Build.Targets", StringComparison.OrdinalIgnoreCase))
                        {
                            bldTargs = n;
                        }
                        else if (prj.Equals(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Interop.Settings", StringComparison.OrdinalIgnoreCase))
                        {
                            intSettings = n;
                        }
                        else if (prj.EndsWith(".featureproj", StringComparison.OrdinalIgnoreCase))
                        {
                            featureProjs.Add(n);
                        }
                    }

                    //[@ns:Project='$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Settings']
                    root.RemoveChild(sysSettings);
                    dst = root.InsertAfter(sysSettings, dst);

                    if (mfproj.IsClrProject)
                    {
                        //expr = @"descendant::ns:Import[@ns:Project='$(SPOCLIENT)\tools\Targets\Microsoft.SPOT.Build.Targets']";
                        //src = root.SelectSingleNode(expr, nsmgr);
                        root.RemoveChild(bldTargs);
                        root.InsertAfter(bldTargs, dst);

                        expr = "descendant::ns:ItemGroup/ns:Compile";
                        dst = root.SelectSingleNode(expr, nsmgr).ParentNode;
                        //expr = "descendant::ns:Import[@ns:Project='*.featureproj']";
                        //XmlNodeList list = root.SelectNodes(expr, nsmgr);
                        foreach (XmlNode n in featureProjs)
                        {
                            root.RemoveChild(n);
                            dst = root.InsertAfter(n, dst);
                        }
                        //expr = @"descendant::ns:Import[@ns:Project='$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Interop.Settings']";
                        //src = root.SelectSingleNode(expr, nsmgr);
                        root.RemoveChild(intSettings);
                        root.InsertAfter(intSettings, dst);
                    }

                    doc.Save(fullpath);
                }
                catch
                {
                    Console.WriteLine("Error: Invalid project file " + mfproj.ProjectPath);
                }
            }
        }
Ejemplo n.º 38
0
        public void ImportSelfIgnored()
        {
            string file = null;

            try
            {
                ProjectCollection collection = new ProjectCollection();
                MockLogger logger = new MockLogger();
                collection.RegisterLogger(logger);

                Project project = new Project(collection);
                project.Xml.AddImport("$(MSBuildProjectFullPath)");

                file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                project.Save(file);
                project.ReevaluateIfNecessary();

                logger.AssertLogContains("MSB4210"); // selfimport
            }
            finally
            {
                File.Delete(file);
            }
        }
        internal bool SaveLibraryCategoryProj(LibraryCategory libCat)
        {
            string fullpath = ExpandEnvVars(libCat.ProjectPath, "");

            Project proj = LoadProject(fullpath);

            proj.ProjectCollection.UnloadProject(proj);
                
            proj = new Project();
            proj.Xml.DefaultTargets = "Build";
            bool fRet = false;

            try
            {
                if (string.IsNullOrEmpty(fullpath))
                {
                    fullpath = Path.Combine(Environment.GetEnvironmentVariable("SPOCLIENT"), @"framework\features\" + libCat.Name + ".libcatproj");
                }

                if (libCat.LibraryProjCache.Count > 0)
                {
                    ProjectItemGroupElement big = proj.Xml.AddItemGroup();

                    foreach (string libRef in libCat.LibraryProjCache)
                    {
                        big.AddItem("LibraryCollection", libRef);
                    }
                }

                List<string> save = libCat.LibraryProjCache;
                libCat.LibraryProjCache = null;

                ProjectPropertyGroupElement bpg = proj.Xml.AddPropertyGroup();

                bpg.AddProperty(PKUI_LibCatTag, SerializeXml(libCat));

                libCat.LibraryProjCache = save;

                proj.Save(fullpath);

                fRet = true;
            }
            catch( Exception e )
            {
                System.Diagnostics.Debug.WriteLine("Error: failure saving LibCat file: " + fullpath + "\r\n", e.Message);
            }
            return fRet;
        }
Ejemplo n.º 40
0
        public void DoubleImportIndirectIgnored()
        {
            string file = null;
            string file2 = null;
            string file3 = null;

            try
            {
                ProjectCollection collection = new ProjectCollection();
                MockLogger logger = new MockLogger();
                collection.RegisterLogger(logger);

                file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                file2 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                file3 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();

                Project project = new Project(collection);
                project.Xml.AddImport(file2);
                project.Xml.AddImport(file3);
                project.Save(file);

                Project project2 = new Project(collection);
                project.Xml.AddImport(file3);
                project2.Save(file2);

                Project project3 = new Project(collection);
                project3.Save(file3);

                project.ReevaluateIfNecessary();

                logger.AssertLogContains("MSB4011"); // duplicate import
            }
            finally
            {
                File.Delete(file);
                File.Delete(file2);
                File.Delete(file3);
            }
        }
Ejemplo n.º 41
0
        public void TestRunPythonCommand() {
            var expectedSearchPath = string.Format("['{0}', '{1}']",
                TestData.GetPath(@"TestData").Replace("\\", "\\\\"),
                TestData.GetPath(@"TestData\HelloWorld").Replace("\\", "\\\\")
            );

            var proj = new Project(TestData.GetPath(@"TestData\Targets\Commands4.pyproj"));

            foreach (var version in PythonPaths.Versions) {
                var verStr = version.Version.ToVersion().ToString();
                proj.SetProperty("InterpreterId", version.Id.ToString("B"));
                proj.SetProperty("InterpreterVersion", verStr);
                proj.RemoveItems(proj.ItemsIgnoringCondition.Where(i => i.ItemType == "InterpreterReference").ToArray());
                proj.AddItem("InterpreterReference", string.Format("{0:B}\\{1}", version.Id, verStr));
                proj.Save();
                proj.ReevaluateIfNecessary();

                var log = new StringLogger(LoggerVerbosity.Minimal);
                Assert.IsTrue(proj.Build("CheckCode", new ILogger[] { new ConsoleLogger(LoggerVerbosity.Detailed), log }));
                
                Console.WriteLine();
                Console.WriteLine("Output from {0:B} {1}", version.Id, version.Version.ToVersion());
                foreach (var line in log.Lines) {
                    Console.WriteLine("* {0}", line.TrimEnd('\r', '\n'));
                }

                var logLines = log.Lines.Last().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                Assert.AreEqual(2, logLines.Length);
                Assert.AreEqual(version.Version.ToVersion().ToString(), logLines[0].Trim());
                Assert.AreEqual(expectedSearchPath, logLines[1].Trim());
            }
        }
Ejemplo n.º 42
0
        public void TransformsUseCorrectDirectory_Basic()
        {
            string file = null;

            string projectFileContent = ObjectModelHelpers.CleanupFileContents(@"
                    <Project xmlns='msbuildnamespace'>
                        <ItemGroup>
                            <IntermediateAssembly Include='obj\i386\foo.dll'/>
                            <BuiltProjectOutputGroupKeyOutput Include=""@(IntermediateAssembly->'%(FullPath)')""/>
                        </ItemGroup>
                    </Project>");

            ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)));

            Project project = new Project(xml);

            try
            {
                file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                project.Save(file);
                project.ReevaluateIfNecessary();

                Assert.Equal(Path.Combine(Path.GetTempPath(), @"obj\i386\foo.dll"), project.GetItems("BuiltProjectOutputGroupKeyOutput").First().EvaluatedInclude);
            }
            finally
            {
                File.Delete(file);
            }
        }
Ejemplo n.º 43
0
        private void AssertWhiteSpacePreservation(string projectContents, string updatedProject,
            Action<ProjectRootElement, Project> act)
        {
            var projectElement =
                ProjectRootElement.Create(
                    XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(projectContents))),
                    ProjectCollection.GlobalProjectCollection,
                    true);

            var project = new Project(projectElement);

            act(projectElement, project);

            var writer = new StringWriter();
            project.Save(writer);

            var expected = @"<?xml version=""1.0"" encoding=""utf-16""?>" +
                           ObjectModelHelpers.CleanupFileContents(updatedProject);
            var actual = writer.ToString();

            VerifyAssertLineByLine(expected, actual);
        }
Ejemplo n.º 44
0
        public void SetPropertyImported()
        {
            Assert.Throws<InvalidOperationException>(() =>
            {
                string file = null;

                try
                {
                    file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
                    Project import = new Project();
                    import.SetProperty("p", "v0");
                    import.Save(file);

                    ProjectRootElement xml = ProjectRootElement.Create();
                    xml.AddImport(file);
                    Project project = new Project(xml);

                    ProjectProperty property = project.GetProperty("p");
                    property.UnevaluatedValue = "v1";
                }
                finally
                {
                    File.Delete(file);
                }
            }
           );
        }