Example #1
0
		/// <summary>
		/// Creates an <see cref="IDocumenterConfig"/> object for this documenter type
		/// </summary>
		/// <param name="project">A project to associate the config with</param>
		/// <returns>A config object</returns>
		public IDocumenterConfig CreateConfig( Project project )
		{
			IDocumenterConfig config = CreateConfig();
			config.SetProject( project );

			return config;
		}
Example #2
0
		/// <summary>Allows the user to associate a summaries with the
		/// namespaces found in the assemblies that are being 
		/// documented.</summary>
		public NamespaceSummariesForm(Project project)
		{
			_Project = project;

			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

		}
Example #3
0
		/// <summary>
		/// Constructor for the solution settings form.  Sets the property grid
		/// to the MSDN Documenter's configuration properties.
		/// </summary>
		/// <param name="project">an NDoc project for the currently loaded solution.</param>
		public SolutionSettingsForm(NDoc.Core.Project project)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			ndocProject = project;
			msdnDocumenter = new MsdnDocumenter();

			this.SetStyle(ControlStyles.DoubleBuffer, true);
			propertyGrid.SelectedObject = ndocProject.GetDocumenter(msdnDocumenter.Name).Config;
		}
Example #4
0
		/// <summary>
		/// Builds the specified project.
		/// </summary>
		/// <param name="project">Project.</param>
		public override void Build(Project project)
		{
			OnDocBuildingStep(0, "Initializing...");

			try
			{
				OnDocBuildingStep(10, "Merging XML documentation...");

				// Will hold the name of the file name containing the XML doc
				string tempFileName = null;

				try 
				{
					// determine temp file name
					tempFileName = Path.GetTempFileName();
					// Let the Documenter base class do it's thing.
					MakeXmlFile(project, tempFileName);

					// Load the XML documentation into XPATH doc.
					using (FileStream tempFile = File.Open(tempFileName, FileMode.Open, FileAccess.Read)) 
					{
						xpathDocument = new XPathDocument(tempFile);
					}
				}
				finally
				{
					if (tempFileName != null && File.Exists(tempFileName)) 
					{
						File.Delete(tempFileName);
					}
				}

				OnDocBuildingStep(30, "Loading XSLT files...");

				stylesheets = StyleSheetCollection.LoadStyleSheets(String.Empty);

				OnDocBuildingStep(40, "Generating XML files...");
				MakeXmlForAssemblies();
			}
			catch (Exception ex)
			{
				throw new DocumenterException(ex.Message, ex);
			}
			finally
			{
				xpathDocument = null;
				stylesheets = null;
			}
		}
Example #5
0
		/// <summary>Allows the user to associate a summaries with the
		/// namespaces found in the assemblies that are being 
		/// documented.</summary>
		public NamespaceSummariesForm(Project project)
		{
			_Project = project;

			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			foreach (string namespaceName in _Project.GetNamespaces())
			{
				namespaceComboBox.Items.Add(namespaceName);
			}

			namespaceComboBox.SelectedIndex = 0;
		}
Example #6
0
		/// <summary>See <see cref="IDocumenter"/>.</summary>
		public override string CanBuild(Project project, bool checkInputOnly)
		{
			string result = base.CanBuild(project, checkInputOnly); 
			if (result != null)
			{
				return result;
			}
			
			result = _HtmlHelp1Documenter.CanBuild( project, checkInputOnly );
			if (result != null)
			{
				return result;
			}	
	
			return null;
		}
Example #7
0
		/// <summary>
		/// Builds the project using the specified <see cref="IDocumenter"/>
		/// </summary>
		/// <param name="documenter">The <see cref="IDocumenter"/> to use</param>
		/// <param name="project">The <see cref="Project"/> to build</param>
		public void Build( IDocumenter documenter, Project project )
		{
			Debug.Assert( documenter != null );
			Debug.Assert( project != null );

			Debug.Assert( m_workerThread == null );

			m_documenter = documenter;
			m_project = project;

			m_workerThread = new Thread( new ThreadStart( ThreadProc ) );
			m_workerThread.Name = "Build";
			m_workerThread.IsBackground = true;
			m_workerThread.Priority = ThreadPriority.Normal;

			m_workerThread.Start();
		}
Example #8
0
		/// <summary>See IDocumenter.</summary>
		public override void Build(Project project)
		{
			OnDocBuildingStep(0, "Building XML documentation...");

			XmlDocumenterConfig config = (XmlDocumenterConfig)Config;

			string tempFileName = null;
			
			try 
			{
				// Determine temp file name
				tempFileName = Path.GetTempFileName();
				// Let the Documenter base class do it's thing.
				MakeXmlFile(project, tempFileName);

				OnDocBuildingStep(50, "Saving XML documentation...");

				string outputFileName = project.GetFullPath(config.OutputFile);

				string directoryName = Path.GetDirectoryName(outputFileName);

				if (directoryName != null && directoryName.Length > 0)
				{
					if (!Directory.Exists(directoryName))
					{
						Directory.CreateDirectory(directoryName);
					}
				}

				if (File.Exists(outputFileName)) 
				{
					File.Delete(outputFileName);
				}

				File.Move(tempFileName, outputFileName);

				OnDocBuildingStep(100, "Done.");
			} 
			finally 
			{
				if (tempFileName != null && File.Exists(tempFileName)) 
				{
					File.Delete(tempFileName);
				}
			}
		}
Example #9
0
		/// <summary>See <see cref="IDocumenter"/>.</summary>
		public override void Build(Project project)
		{
			//set the config such that the MSDN compiler only creates the CHM
			//if the user wants the web output they certainly don't need this component
			MyConfig.OutputTarget = OutputType.HtmlHelp;

			//first build the CHM file
			OnDocBuildingStep( 0, "Building Html Help 1..." );
			_HtmlHelp1Documenter.DocBuildingStep += new DocBuildingEventHandler( _HtmlHelp1Documenter_DocBuildingStep );
			_HtmlHelp1Documenter.Build( project );

			string outputDir = MyConfig.OutputDirectory;

			//then get rid of all help 1 inputs
			OnDocBuildingStep( 50, "Cleaning Html Help 1 intermediate files..." );
			CleanCHMIntermediates();

			//then convert the CHM to an HxC project
			OnDocBuildingStep( 55, "Converting to Html Help 2..." );
			ConvertCHMFile();

			//then convert the CHM to an HxC project
			if ( MyConfig.AugmentXmlDataIslands )
			{
				OnDocBuildingStep( 60, "Augmenting Xml data islands..." );
				HxAugmenter.Augment( new DirectoryInfo( WorkingPath ), MyConfig.HtmlHelpName );
			}

			//then compile the HxC into and HxS
			OnDocBuildingStep( 75, "Compiling Html Help 2 Files..." );
			CompileHxCFile();

			// do clean up and final registration steps
			OnDocBuildingStep( 99, "Finishing up..." );
			if ( MyConfig.DeleteCHM )
				File.Delete( InputCHMPath );
	
			if ( MyConfig.RegisterTitleWithNamespace )
				RegisterTitle();
			else if ( MyConfig.RegisterTitleAsCollection )
				RegisterCollection();

		}
Example #10
0
        /// <summary>
        /// Returns the documenter for the given project.
        /// </summary>
        /// <exception cref="BuildException">
        /// Documenter <paramref name="documenterName" /> is not found.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="project" /> is <see langword="null" />.
        /// </exception>
        private IDocumenter CheckAndGetDocumenter(NDoc.Core.Project project, string documenterName)
        {
            IDocumenter documenter = null;

            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            StringCollection documenters = new StringCollection();

            foreach (IDocumenter d in project.Documenters)
            {
                documenters.Add(d.Name);

                // ignore case when comparing documenter names
                if (string.Compare(d.Name, documenterName, true, CultureInfo.InvariantCulture) == 0)
                {
                    documenter = (IDocumenter)d;
                    break;
                }
            }

            // throw an exception if the documenter could not be found.
            if (documenter == null)
            {
                if (documenters.Count == 0)
                {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                           ResourceUtils.GetString("NA2024"), documenterName), Location);
                }
                else
                {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                           ResourceUtils.GetString("NA2025"), documenterName,
                                                           StringUtils.Join(", ", documenters)), Location);
                }
            }
            return(documenter);
        }
Example #11
0
		/// <summary>Associates this config with a <see cref="Project"/>.</summary>
		/// <param name="project">A <see cref="Project"/> to associate with this config.</param>
		public void SetProject(Project project)
		{
			_Project = project;
		}
Example #12
0
        /// <summary>
        /// Generates an NDoc project and builds the documentation.
        /// </summary>
        protected override void ExecuteTask()
        {
            // ensure base directory is set, even if fileset was not initialized
            // from XML
            if (Assemblies.BaseDirectory == null) {
                Assemblies.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }
            if (Summaries.BaseDirectory == null) {
                Summaries.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }
            if (ReferencePaths.BaseDirectory == null) {
                ReferencePaths.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }

            // Make sure there is at least one included assembly.  This can't
            // be done in the Initialize() method because the files might
            // not have been built at startup time.
            if (Assemblies.FileNames.Count == 0) {
                throw new BuildException(ResourceUtils.GetString("NA2020"), Location);
            }

            // create NDoc Project
            NDoc.Core.Project project = null;

            try {
                project = new NDoc.Core.Project();
            } catch (Exception ex) {
                throw new BuildException(ResourceUtils.GetString("NA2021"), Location, ex);
            }

            // set-up probe path, meaning list of directories where NDoc searches
            // for documenters
            // by default, NDoc scans the startup path of the app, so we do not
            // need to add this explicitly
            string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
            if (privateBinPath != null) {
                // have NDoc also probe for documenters in the privatebinpath
                foreach (string relativePath in privateBinPath.Split(Path.PathSeparator)) {
                    project.AppendProbePath(Path.Combine(
                        AppDomain.CurrentDomain.BaseDirectory, relativePath));
                }
            }

            // check for valid documenters (any other validation can be done by NDoc itself at project load time)
            foreach (XmlNode node in _docNodes) {
                //skip non-nant namespace elements and special elements like comments, pis, text, etc.
                if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) {
                    continue;
                }

                string documenterName = node.Attributes["name"].Value;
                CheckAndGetDocumenter(project, documenterName);
            }

            // write documenter project settings to temp file
            string projectFileName = Path.GetTempFileName();
            Log(Level.Verbose, ResourceUtils.GetString("String_WritingProjectSettings"), projectFileName);

            XmlTextWriter writer = new XmlTextWriter(projectFileName, Encoding.UTF8);
            writer.Formatting = Formatting.Indented;
            writer.WriteStartDocument();
            writer.WriteStartElement("project");

            // write assemblies section
            writer.WriteStartElement("assemblies");
            foreach (string assemblyPath in Assemblies.FileNames) {
                string docPath = Path.ChangeExtension(assemblyPath, ".xml");
                writer.WriteStartElement("assembly");
                writer.WriteAttributeString("location", assemblyPath);
                if (File.Exists(docPath)) {
                    writer.WriteAttributeString("documentation", docPath);
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            // write summaries section
            StringBuilder sb = new StringBuilder();
            foreach (string summaryPath in Summaries.FileNames) {
                // write out the namespace summary nodes
                try {
                    XmlTextReader tr = new XmlTextReader(summaryPath);
                    tr.MoveToContent();   // skip XmlDeclaration  and Processing Instructions
                    sb.Append(tr.ReadOuterXml());
                    tr.Close();
                } catch (IOException ex) {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                        ResourceUtils.GetString("NA2022"), summaryPath), Location, ex);
                }
            }
            writer.WriteRaw(sb.ToString());

            // write out the documenters section
            writer.WriteStartElement("documenters");
            foreach (XmlNode node in _docNodes) {
                //skip non-nant namespace elements and special elements like comments, pis, text, etc.
                if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) {
                    continue;
                }
                writer.WriteRaw(node.OuterXml);
            }
            writer.WriteEndElement();

            // end project element
            writer.WriteEndElement();
            writer.Close();

            try {
                // read NDoc project file
                Log(Level.Verbose, ResourceUtils.GetString("String_NDocProjectFile"),
                    Path.GetFullPath(projectFileName));
                project.Read(projectFileName);

                // add additional directories to search for referenced assemblies
                if (ReferencePaths.DirectoryNames.Count > 0) {
                    foreach (string directory in ReferencePaths.DirectoryNames) {
                        project.ReferencePaths.Add(new ReferencePath(directory));
                    }
                }

                foreach (XmlNode node in _docNodes) {
                    //skip non-nant namespace elements and special elements like comments, pis, text, etc.
                    if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) {
                        continue;
                    }

                    string documenterName = node.Attributes["name"].Value;
                    IDocumenter documenter =  CheckAndGetDocumenter(project, documenterName);

                    // hook up events for feedback during the build
                    documenter.DocBuildingStep += new DocBuildingEventHandler(OnDocBuildingStep);
                    documenter.DocBuildingProgress += new DocBuildingEventHandler(OnDocBuildingProgress);

                    // build documentation
                    documenter.Build(project);
                }
            } catch (Exception ex) {
                throw new BuildException(ResourceUtils.GetString("NA2023"), Location, ex);
            }
        }
Example #13
0
		/// <summary>
		/// <see cref="BaseDocumenter.Build"/>
		/// </summary>
		/// <param name="project"></param>
		public override void Build(Project project)
		{		
			Workspace workspace = new LatexWorkspace( WorkingPath );
			workspace.Clean();
			workspace.Prepare();

#if NO_RESOURCES
			// copy all of the xslt source files into the workspace
			DirectoryInfo xsltSource = new DirectoryInfo( Path.GetFullPath(Path.Combine(
				Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"..\..\..\Documenter\Latex\xslt") ) );
                				
			foreach ( FileInfo f in xsltSource.GetFiles( "*.xslt" ) )
			{
				string fname = Path.Combine( workspace.ResourceDirectory, f.Name );
				f.CopyTo( fname, true );
				File.SetAttributes( fname, FileAttributes.Normal );
			}
#else
		
			EmbeddedResources.WriteEmbeddedResources(
				this.GetType().Module.Assembly,
				"NDoc.Documenter.Latex.xslt",
				workspace.ResourceDirectory );
#endif

			string xmlBuffer = MakeXml(project);

			// Create the output directory if it doesn't exist...

			if (!Directory.Exists(LatexConfig.OutputDirectory))
			{
				Directory.CreateDirectory(LatexConfig.OutputDirectory);
			}
			else
			{
				// Delete temp files in the output directory.
				
				OnDocBuildingStep(5, "Deleting temp files from last time...");

				foreach (string s in c_TempFileExtensions)
				{
					File.Delete(LatexConfig.TexFileBaseName + s);
				}				
			}
						
			OnDocBuildingStep(10, "Scanning document text...");

			XmlDocument doc = new XmlDocument();
			doc.LoadXml(xmlBuffer);
			MakeTextTeXCompatible(doc);
			
			WriteTeXDocument(workspace, doc);
			CompileTexDocument();
			workspace.RemoveResourceDirectory();
		}
Example #14
0
		/// <summary>See <see cref="IDocumenter"/>.</summary>
		public override void Build(Project project)
		{
			this.workspace = new JavaDocWorkspace( this.WorkingPath );
			workspace.Clean();
			workspace.Prepare();

			workspace.AddResourceDirectory( "xslt" );
			workspace.AddResourceDirectory( "css" );

// Define this when you want to edit the stylesheets
// without having to shutdown the application to rebuild.
#if NO_RESOURCES
			// copy all of the xslt source files into the workspace
			DirectoryInfo xsltSource = new DirectoryInfo( Path.GetFullPath(Path.Combine(
				System.Windows.Forms.Application.StartupPath, @"..\..\..\Documenter\JavaDoc\xslt") ) );
                				
			foreach ( FileInfo f in xsltSource.GetFiles( "*.xslt" ) )
			{
				string fname = Path.Combine( Path.Combine( workspace.ResourceDirectory, "xslt" ), f.Name );
				f.CopyTo( fname, true );
				File.SetAttributes( fname, FileAttributes.Normal );
			}

			DirectoryInfo cssSource = new DirectoryInfo( Path.GetFullPath(Path.Combine(
				System.Windows.Forms.Application.StartupPath, @"..\..\..\Documenter\JavaDoc\css") ) );
                				
			foreach ( FileInfo f in cssSource.GetFiles( "*.css" ) )
			{
				string cssname = Path.Combine( Path.Combine( workspace.ResourceDirectory, "css" ), f.Name );
				f.CopyTo( cssname, true );
				File.SetAttributes( cssname, FileAttributes.Normal );
			}

#else
				EmbeddedResources.WriteEmbeddedResources(
					this.GetType().Module.Assembly,
					"NDoc.Documenter.JavaDoc.css",
					Path.Combine( this.workspace.ResourceDirectory, "css" ) );

				EmbeddedResources.WriteEmbeddedResources(
					this.GetType().Module.Assembly,
					"NDoc.Documenter.JavaDoc.xslt",
					Path.Combine( this.workspace.ResourceDirectory, "xslt") );
#endif

			string outcss = Path.Combine(MyConfig.OutputDirectory, "JavaDoc.css");
			File.Copy(Path.Combine(workspace.ResourceDirectory, @"css\JavaDoc.css"), outcss, true);
			File.SetAttributes(outcss, FileAttributes.Archive);

			try
			{
				// determine temp file name
				tempFileName = Path.GetTempFileName();
				// Let the Documenter base class do it's thing.
				MakeXmlFile(project, tempFileName);

				WriteOverviewSummary();
				WriteNamespaceSummaries();
			}
			finally
			{
				if (tempFileName != null && File.Exists(tempFileName)) 
				{
					File.Delete(tempFileName);
				}
				workspace.RemoveResourceDirectory();
			}

		}
Example #15
0
		/// <summary>See <see cref="IDocumenter"/>.</summary>
		public override string CanBuild(Project project, bool checkInputOnly)
		{
			string result = base.CanBuild(project, checkInputOnly); 
			if (result != null) { return result; }
			if (checkInputOnly) { return null; }

			// test if output file is open
			string path = this.MainOutputFile;
			string temp = Path.Combine(MyConfig.OutputDirectory, "~lhtml.tmp");

			try
			{
				if (File.Exists(path))
				{
					//if we can move the file, then it is not open...
					File.Move(path, temp);
					File.Move(temp, path);
				}
			}
			catch (Exception)
			{
				result = "The output file is probably open.\nPlease close it and try again.";
			}

			return result;
		}
Example #16
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="documenter"></param>
		/// <param name="project"></param>
		public BuildWorker(IDocumenter documenter, Project project)
		{
			m_documenter = documenter;
			m_project = project;
		}
Example #17
0
        /// <summary>
        /// Generates an NDoc project and builds the documentation.
        /// </summary>
        protected override void ExecuteTask()
        {
            // ensure base directory is set, even if fileset was not initialized
            // from XML
            if (Assemblies.BaseDirectory == null)
            {
                Assemblies.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }
            if (Summaries.BaseDirectory == null)
            {
                Summaries.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }
            if (ReferencePaths.BaseDirectory == null)
            {
                ReferencePaths.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }

            // Make sure there is at least one included assembly.  This can't
            // be done in the Initialize() method because the files might
            // not have been built at startup time.
            if (Assemblies.FileNames.Count == 0)
            {
                throw new BuildException(ResourceUtils.GetString("NA2020"), Location);
            }

            // create NDoc Project
            NDoc.Core.Project project = null;

            try {
                project = new NDoc.Core.Project();
            } catch (Exception ex) {
                throw new BuildException(ResourceUtils.GetString("NA2021"), Location, ex);
            }

            // set-up probe path, meaning list of directories where NDoc searches
            // for documenters
            // by default, NDoc scans the startup path of the app, so we do not
            // need to add this explicitly
            string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;

            if (privateBinPath != null)
            {
                // have NDoc also probe for documenters in the privatebinpath
                foreach (string relativePath in privateBinPath.Split(Path.PathSeparator))
                {
                    project.AppendProbePath(Path.Combine(
                                                AppDomain.CurrentDomain.BaseDirectory, relativePath));
                }
            }

            // check for valid documenters (any other validation can be done by NDoc itself at project load time)
            foreach (XmlNode node in _docNodes)
            {
                //skip non-nant namespace elements and special elements like comments, pis, text, etc.
                if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant")))
                {
                    continue;
                }

                string documenterName = node.Attributes["name"].Value;
                CheckAndGetDocumenter(project, documenterName);
            }

            // write documenter project settings to temp file
            string projectFileName = Path.GetTempFileName();

            Log(Level.Verbose, ResourceUtils.GetString("String_WritingProjectSettings"), projectFileName);

            XmlTextWriter writer = new XmlTextWriter(projectFileName, Encoding.UTF8);

            writer.Formatting = Formatting.Indented;
            writer.WriteStartDocument();
            writer.WriteStartElement("project");

            // write assemblies section
            writer.WriteStartElement("assemblies");
            foreach (string assemblyPath in Assemblies.FileNames)
            {
                string docPath = Path.ChangeExtension(assemblyPath, ".xml");
                writer.WriteStartElement("assembly");
                writer.WriteAttributeString("location", assemblyPath);
                if (File.Exists(docPath))
                {
                    writer.WriteAttributeString("documentation", docPath);
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            // write summaries section
            StringBuilder sb = new StringBuilder();

            foreach (string summaryPath in Summaries.FileNames)
            {
                // write out the namespace summary nodes
                try {
                    XmlTextReader tr = new XmlTextReader(summaryPath);
                    tr.MoveToContent();   // skip XmlDeclaration  and Processing Instructions
                    sb.Append(tr.ReadOuterXml());
                    tr.Close();
                } catch (IOException ex) {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                           ResourceUtils.GetString("NA2022"), summaryPath), Location, ex);
                }
            }
            writer.WriteRaw(sb.ToString());

            // write out the documenters section
            writer.WriteStartElement("documenters");
            foreach (XmlNode node in _docNodes)
            {
                //skip non-nant namespace elements and special elements like comments, pis, text, etc.
                if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant")))
                {
                    continue;
                }
                writer.WriteRaw(node.OuterXml);
            }
            writer.WriteEndElement();

            // end project element
            writer.WriteEndElement();
            writer.Close();

            try {
                // read NDoc project file
                Log(Level.Verbose, ResourceUtils.GetString("String_NDocProjectFile"),
                    Path.GetFullPath(projectFileName));
                project.Read(projectFileName);

                // add additional directories to search for referenced assemblies
                if (ReferencePaths.DirectoryNames.Count > 0)
                {
                    foreach (string directory in ReferencePaths.DirectoryNames)
                    {
                        project.ReferencePaths.Add(new ReferencePath(directory));
                    }
                }

                foreach (XmlNode node in _docNodes)
                {
                    //skip non-nant namespace elements and special elements like comments, pis, text, etc.
                    if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant")))
                    {
                        continue;
                    }

                    string      documenterName = node.Attributes["name"].Value;
                    IDocumenter documenter     = CheckAndGetDocumenter(project, documenterName);

                    // hook up events for feedback during the build
                    documenter.DocBuildingStep     += new DocBuildingEventHandler(OnDocBuildingStep);
                    documenter.DocBuildingProgress += new DocBuildingEventHandler(OnDocBuildingProgress);

                    // build documentation
                    documenter.Build(project);
                }
            } catch (Exception ex) {
                throw new BuildException(ResourceUtils.GetString("NA2023"), Location, ex);
            }
        }
Example #18
0
		/// <summary>See <see cref="IDocumenter.CanBuild">CanBuild</see>.</summary>
		public virtual string CanBuild(Project project, bool checkInputOnly)
		{
			StringBuilder xfiles = new StringBuilder();
			foreach (AssemblySlashDoc asd in project.AssemblySlashDocs)
			{
				if (!File.Exists(asd.Assembly.Path))
				{
					xfiles.Append("\n" + asd.Assembly.Path);
				}
				if (asd.SlashDoc.Path.Length>0)
				{
					if (!File.Exists(asd.SlashDoc.Path))
					{
						xfiles.Append("\n" + asd.SlashDoc.Path);
					}
				}
			}

			if (xfiles.Length > 0)
			{
				return "One of more source files not found:\n" + xfiles.ToString();
			}
			else
			{
				return null;
			}
		}
Example #19
0
		public static int Main(string[] args)
		{
			try
			{
				WriteLogoBanner();

				project = new Project();
				IDocumenterInfo info = InstalledDocumenters.GetDocumenter("MSDN");
				if (info == null)
				{
					//MSDN documenterConfig not found, pick the first one available.
					if (InstalledDocumenters.Documenters.Count > 0)
					{
						info = (IDocumenterInfo)InstalledDocumenters.Documenters[0];
					}
					else
					{
						throw new ApplicationException("Could not find any documenter assemblies.");
					}
				}
				project.ActiveDocumenter = info;
				documenterConfig = project.ActiveConfig;

				int maxDepth = 20; //to limit recursion depth
				bool propertiesSet = false;
				bool projectSet = false;

				if (args.Length==0)
				{
					WriteUsage();
					return 1;
				}

				if (args[0].ToLower().StartsWith("-help"))
				{
					WriteHelp(args);
					return 1;
				}

				foreach (string arg in args)
				{
					if (arg.StartsWith("-"))
					{
						if (string.Compare(arg, "-verbose", true) == 0)
						{
							Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
							verbose = true;
						}
						else
						{
							string[] pair = arg.Split('=');

							if (pair.Length == 2)
							{
								string name = pair[0].Substring(1);
								string val = pair[1];

								switch (name.ToLower())
								{
									case "documenter":
										if (propertiesSet)
										{
											throw new ApplicationException("The documenter name must be specified before any documenter specific options.");
										}
										if (projectSet)
										{
											throw new ApplicationException("The documenter name must be specified before the project file.");
										}
										info = InstalledDocumenters.GetDocumenter(val.Replace("_"," "));

										if (info == null)
										{
											throw new ApplicationException("The specified documenter name is invalid.");
										}
										project.ActiveDocumenter = info;
										documenterConfig = project.ActiveConfig;
										break;
									case "project":
										if (propertiesSet)
										{
											throw new ApplicationException("The project file must be specified before any documenter specific options.");
										}
										Console.WriteLine("using project file " + val);
										project.Read(val);
										project.ActiveDocumenter = info;
										documenterConfig = project.ActiveConfig;
										projectSet = true;
										Directory.SetCurrentDirectory(Path.GetDirectoryName(val));
										Debug.WriteLine(Directory.GetCurrentDirectory());
										break;
									case "recurse":
										string[] recPair = val.Split(',');
										if (2 == recPair.Length)
										{
											maxDepth = Convert.ToInt32(recPair[1]);
										}
										RecurseDir(recPair[0], maxDepth);
										break;
									case "namespacesummaries":
										using(StreamReader streamReader = new StreamReader(val))
										{
											XmlTextReader reader = new XmlTextReader(streamReader);
											reader.MoveToContent();
											project.Namespaces.Read(reader);
											reader.Close();
											streamReader.Close();
										}
										break;
									case "referencepath":
										project.ReferencePaths.Add(new ReferencePath(val));
										break;
									default:
										documenterConfig.SetValue(name, val);
										propertiesSet = true;
										break;
								}
							}
						}
					}
					else if (arg.IndexOf(',') != -1)
					{
						string[] pair = arg.Split(',');

						if (pair.Length == 2)
						{
							project.AssemblySlashDocs.Add(
								new AssemblySlashDoc(pair[0], pair[1]));
						}
					}
					else
					{
						string doc = Path.ChangeExtension(arg, ".xml");
						if (File.Exists(doc))
						{
							project.AssemblySlashDocs.Add(
								new AssemblySlashDoc(arg, doc));
						}
						else
						{
							project.AssemblySlashDocs.Add(
								new AssemblySlashDoc(arg, ""));
						}
					}
				}

				if (project.AssemblySlashDocs.Count == 0)
				{
					Console.WriteLine("[Error] Build cannot proceed; No assemblies were specified, or none could be found.");
					//WriteUsage();
					return 1;
				}
				else
				{
					startDateTime = DateTime.UtcNow;
					IDocumenter documenter = documenterConfig.CreateDocumenter();
					documenter.DocBuildingStep += new DocBuildingEventHandler(DocBuildingStepHandler);
					documenter.Build(project);
					TimeSpan ts = DateTime.UtcNow - startDateTime;
					Console.WriteLine(String.Format("Total build time {0:f1} s", ts.TotalSeconds));
					return 0;
				}

			}
			catch( Exception except )
			{
				string errorText= BuildExceptionText(except);
				Console.WriteLine(errorText);
				System.Diagnostics.Trace.WriteLine(errorText);
				return 2;
			}
		}
		/// <summary>See <see cref="IDocumenter"/>.</summary>
		public override string CanBuild( Project project, bool checkInputOnly )
		{
			string result = base.CanBuild(project, checkInputOnly); 
			if (result != null)
				return result;

			if ( !HxObject.HxCompIsInstalled )
				return "Could not find Html Help 2 compiler. Please make sure VSHIK 2003 is properly installed";

			if ( MyConfig.OutputDirectory == null )
				return "The output directory must be set";

			// validate the namespace map
			string NamespaceMappingFilePath=MyConfig.UseHelpNamespaceMappingFile;
			if ( NamespaceMappingFilePath.Length != 0 )
			{
				if ( !File.Exists( NamespaceMappingFilePath ) )
					return string.Format( "Could not find the namespace mapping file: {0}", NamespaceMappingFilePath );

				try
				{
					NamespaceMapper mapper = new NamespaceMapper( NamespaceMappingFilePath );
				}
				catch ( Exception e )
				{
					StringBuilder sb = new StringBuilder();
					sb.AppendFormat( "The namespace mapping file {0} failed to validate.\n", NamespaceMappingFilePath );
					sb.Append( "Make sure that it conforms to the NamespaceMap.xsd schema that can be found in the NDoc installation directory.\n" );
					sb.AppendFormat( "Parse error={0}", e.Message );
					return sb.ToString();
				}
			}

			// validate that all of the additional content resources are present
			string IntroductionPage = MyConfig.IntroductionPage;
			if ( IntroductionPage.Length != 0 && !File.Exists( IntroductionPage ) )
				return string.Format( "The IntroductionPage file {0} could not be found", IntroductionPage );

			string AboutPageIconPage = MyConfig.AboutPageIconPage;
			if ( AboutPageIconPage.Length != 0 && !File.Exists( AboutPageIconPage ) )
				return string.Format( "The AboutPageIconPage file {0} could not be found", AboutPageIconPage );

			string AboutPageInfo = MyConfig.AboutPageInfo;
			if ( AboutPageInfo.Length != 0 && !File.Exists( AboutPageInfo ) )
				return string.Format( "The AboutPageInfo file {0} could not be found", AboutPageInfo );

			string NavFailPage = MyConfig.NavFailPage;
			if ( NavFailPage.Length != 0 && !File.Exists( NavFailPage ) )
				return string.Format( "The NavFailPage file {0} could not be found", NavFailPage );

			string EmptyIndexTermPage = MyConfig.EmptyIndexTermPage;
			if ( EmptyIndexTermPage.Length != 0 && !File.Exists( EmptyIndexTermPage ) )
				return string.Format( "The EmptyIndexTermPage file {0} could not be found", EmptyIndexTermPage );

			string ExtensibilityStylesheet = MyConfig.ExtensibilityStylesheet;
			if ( ExtensibilityStylesheet.Length != 0 && !File.Exists( ExtensibilityStylesheet ) )
				return string.Format( "The Extensibility Stylesheet file {0} could not be found", ExtensibilityStylesheet );

			string AdditionalContentResourceDirectory = MyConfig.AdditionalContentResourceDirectory;
			if ( AdditionalContentResourceDirectory.Length != 0 && !Directory.Exists( AdditionalContentResourceDirectory ) )
				return string.Format( "The Additional Content Resource Directory {0} could not be found", AdditionalContentResourceDirectory );

			// make sure we have a collection namespace
			if ( ( MyConfig.GenerateCollectionFiles || MyConfig.RegisterTitleWithNamespace ) && MyConfig.CollectionNamespace.Length == 0 )
				return "If GenerateCollectionFiles or RegisterTitleWithNamespace is true, a valid CollectionNamespace is required";

			// test if we can write to the output file
			if ( !checkInputOnly ) 
			{
				string temp = Path.Combine( MyConfig.OutputDirectory, "~HxS.tmp" );

				try
				{

					if ( File.Exists( MainOutputFile ) )
					{
						//if we can move the file, then it is not open...
						File.Move( MainOutputFile, temp );
						File.Move( temp, MainOutputFile );
					}
				}
				catch ( Exception )
				{
					result = "The compiled HTML Help file is probably open.\nPlease close it and try again.";
				}
			}

			return result;
		}
		/// <summary>See <see cref="IDocumenter"/>.</summary>
		public override void Build(Project project)
		{
			if ( !HxObject.HxCompIsInstalled )
				throw new DocumenterException( "Could not find Html Help 2 compiler. Please make sure VSHIK 2003 is properly installed" );

			try
			{
#if DEBUG
				int start = Environment.TickCount;
#endif
				OnDocBuildingStep( 0, "Initializing..." );

				Workspace workspace = new NativeHtmlHelp2Workspace( WorkingPath );
				workspace.Clean();
				workspace.Prepare();

				UnPackResources( workspace );

				// set up the includes file
				IncludeFile includes = IncludeFile.CreateFrom( Path.Combine( workspace.ResourceDirectory, "includes.hxf" ), "includes" );
				// attach to this event so resource directories get included in the include file
				workspace.ContentDirectoryAdded += new ContentEventHandler( includes.AddDirectory ); 

				// create and save the named url index
				CreateNamedUrlIndex( workspace );

				// save the includes file
				includes.Save( workspace.WorkingDirectory );

				// set up the table of contents
				TOCFile toc = TOCFile.CreateFrom( Path.Combine( workspace.ResourceDirectory, "project.HxT" ), MyConfig.HtmlHelpName );
				toc.LangId = MyConfig.LangID;

				// set up the project file
				ProjectFile HxProject = CreateProjectFile( workspace );
				HxProject.TOCFile = toc.FileName;
				HxProject.Save( workspace.WorkingDirectory );

				// get the ndoc xml
				OnDocBuildingStep( 10, "Merging XML documentation..." );

				// Will hold the name of the file name containing the XML doc
				string tempFileName = null;

				HtmlFactory factory = null;

				try 
				{
					// determine temp file name
					tempFileName = Path.GetTempFileName();
					// Let the Documenter base class do it's thing.
					MakeXmlFile(project, tempFileName);

					GC.Collect();
					GC.WaitForPendingFinalizers();
					GC.Collect();

					// create and intialize a HtmlFactory
					ExternalHtmlProvider htmlProvider = new ExternalHtmlProvider(
						MyConfig.HeaderHtml, MyConfig.FooterHtml);
					factory = new HtmlFactory(tempFileName, 
						workspace.ContentDirectory, htmlProvider, MyConfig);
				} 
				finally 
				{
					if (tempFileName != null && File.Exists(tempFileName)) 
					{
						File.Delete(tempFileName);
					}
				}

				// generate all the html content - builds the toc along the way
				using( new TOCBuilder( toc, factory ) )
					MakeHtml( workspace, factory );

				toc.Save( workspace.WorkingDirectory );

				//then compile the HxC into an HxS
				OnDocBuildingStep( 65, "Compiling Html Help 2 Files..." );
				CompileHxCFile( workspace );

				// copy outputs to the final build location
				workspace.SaveOutputs( "*.Hxs" );
				workspace.SaveOutputs( "*.HxI" );

				// do clean up and final registration steps
				OnDocBuildingStep( 95, "Finishing up..." );

				if ( MyConfig.RegisterTitleWithNamespace )
					RegisterTitleWithCollection( workspace );
				else if ( MyConfig.RegisterTitleAsCollection )
					RegisterTitleAsCollection( workspace );

				// create collection level files
				if( MyConfig.GenerateCollectionFiles )
					CreateCollectionFiles( workspace );

				workspace.RemoveResourceDirectory();
				if ( MyConfig.CleanIntermediates )
					workspace.CleanIntermediates();

#if DEBUG
				Trace.WriteLine( string.Format( "It took a total of {0} seconds", ( Environment.TickCount - start ) / 1000 ) );
#endif
				Trace.WriteLine( "Build complete" );
			}
			catch ( Exception e )
			{
				throw new DocumenterException( "An error occured while creating the documentation", e );
			}
		}
Example #22
0
		private void ThreadProc()
		{
			GC.Collect();
			Debug.WriteLine("Memory before build: " + GC.GetTotalMemory(false).ToString());

			try
			{
				m_documenter.DocBuildingStep += new DocBuildingEventHandler(m_documenter_DocBuildingStep);
				// Build the documentation.
				m_documenter.Build(m_project);
			}
			catch ( Exception ex )
			{
				if ( App.GetInnermostException( ex ) is ThreadAbortException )
					m_buildStatus.BuildCancelled();
				else
					m_buildStatus.BuildException( ex );
			}
			finally
			{
				m_documenter.DocBuildingStep -= new DocBuildingEventHandler(m_documenter_DocBuildingStep);

				m_buildStatus.BuildComplete();

				m_project = null;
				m_documenter = null;
				lock( this )
					m_workerThread = null;

				GC.Collect();
				Debug.WriteLine("Memory after build: " + GC.GetTotalMemory(false).ToString());
			}
		}
Example #23
0
		/// <summary>See <see cref="IDocumenter.Build">IDocumenter.Build</see>.</summary>
		abstract public void Build(Project project);
Example #24
0
		/// <summary>See <see cref="IDocumenter"/>.</summary>
		public override void Build(Project project)
		{
			try
			{
				OnDocBuildingStep(0, "Initializing...");

				this.workspace = new LinearHtmlWorkspace( this.WorkingPath );
				workspace.Clean();
				workspace.Prepare();

				workspace.AddResourceDirectory( "xslt" );

// Define this when you want to edit the stylesheets
// without having to shutdown the application to rebuild.
#if NO_RESOURCES
				// copy all of the xslt source files into the workspace
				DirectoryInfo xsltSource = new DirectoryInfo( Path.GetFullPath(Path.Combine(
					System.Windows.Forms.Application.StartupPath, @"..\..\..\Documenter\LinearHtml\xslt") ) );

				foreach ( FileInfo f in xsltSource.GetFiles( "*.xslt" ) )
				{
					string destPath = Path.Combine( Path.Combine( workspace.ResourceDirectory, "xslt" ), f.Name );
					// change to allow overwrite if clean-up failed last time
					if (File.Exists(destPath)) File.SetAttributes( destPath, FileAttributes.Normal );
					f.CopyTo( destPath, true );
					// set attributes to allow delete later
					File.SetAttributes( destPath, FileAttributes.Normal );
				}

#else
				EmbeddedResources.WriteEmbeddedResources(this.GetType().Module.Assembly,
					"NDoc.Documenter.LinearHtml.xslt",
					Path.Combine(workspace.ResourceDirectory, "xslt"));
#endif

				// Create the html output directory if it doesn't exist.
				if (!Directory.Exists(MyConfig.OutputDirectory))
				{
					Directory.CreateDirectory(MyConfig.OutputDirectory);
				}

				// Write the embedded css files to the html output directory
				EmbeddedResources.WriteEmbeddedResources(this.GetType().Module.Assembly,
					"NDoc.Documenter.LinearHtml.css", MyConfig.OutputDirectory);

				// Write the external files (FilesToInclude) to the html output directory
				foreach( string srcFile in MyConfig.FilesToInclude.Split( '|' ) )
				{
					if ((srcFile == null) || (srcFile.Length == 0))
						continue;

					string dstFile = Path.Combine(MyConfig.OutputDirectory, Path.GetFileName(srcFile));
					File.Copy(srcFile, dstFile, true);
					File.SetAttributes(dstFile, FileAttributes.Archive);
				}

				OnDocBuildingStep(10, "Merging XML documentation...");

				// Will hold the name of the file name containing the XML doc
				string tempFileName = null;

				// Will hold the DOM representation of the XML doc
				XmlDocument xmlDocumentation = null;

				try 
				{
					// determine temp file name
					tempFileName = Path.GetTempFileName();
					// Let the Documenter base class do it's thing.
					MakeXmlFile(project, tempFileName);
					// Load the XML into DOM
					xmlDocumentation = new XmlDocument();
					xmlDocumentation.Load(tempFileName);
				} 
				finally 
				{
					if (tempFileName != null && File.Exists(tempFileName)) 
					{
						File.Delete(tempFileName);
					}
				}

#if USE_XML_DOCUMENT
				xPathNavigator = xmlDocumentation.CreateNavigator();
#else
				XmlTextWriter tmpWriter = new XmlTextWriter(new MemoryStream(), Encoding.UTF8);
				xmlDocumentation.WriteTo(tmpWriter);
				tmpWriter.Flush();
				tmpWriter.BaseStream.Position = 0;
				this.Load(tmpWriter.BaseStream);
#endif

				// check for documentable types
				XmlNodeList typeNodes = xmlDocumentation.SelectNodes("/ndoc/assembly/module/namespace/*[name()!='documentation']");

				if (typeNodes.Count == 0)
				{
					throw new DocumenterException("There are no documentable types in this project.\n\nAny types that exist in the assemblies you are documenting have been excluded by the current visibility settings.\nFor example, you are attempting to document an internal class, but the 'DocumentInternals' visibility setting is set to False.\n\nNote: C# defaults to 'internal' if no accessibilty is specified, which is often the case for Console apps created in VS.NET...");
				}

				// create and write the html
				OnDocBuildingStep(50, "Generating HTML page...");
				MakeHtml(this.MainOutputFile);
				OnDocBuildingStep(100, "Done.");
				workspace.Clean();
			}
			catch(Exception ex)
			{
				throw new DocumenterException(ex.Message, ex);
			}
		}
Example #25
0
		/// <summary>
		/// Loads the namespaces from assemblies.
		/// </summary>
		/// <param name="project">Project.</param>
		public void LoadNamespacesFromAssemblies(Project project)
		{
			//let's try to create this in a new AppDomain
			AppDomain appDomain = null;
			try
			{
				appDomain = AppDomain.CreateDomain("NDocNamespaces");
				ReflectionEngine re = (ReflectionEngine)   
					appDomain.CreateInstanceAndUnwrap(typeof(ReflectionEngine).Assembly.FullName, 
					typeof(ReflectionEngine).FullName, false, BindingFlags.Public | BindingFlags.Instance, 
					null, new object[0], CultureInfo.InvariantCulture, new object[0], 
					AppDomain.CurrentDomain.Evidence);
				ReflectionEngineParameters rep = new ReflectionEngineParameters(project);
				foreach (AssemblySlashDoc assemblySlashDoc in project.AssemblySlashDocs)
				{
					if (assemblySlashDoc.Assembly.Path.Length > 0)
					{
						string assemblyFullPath = assemblySlashDoc.Assembly.Path;
						if (File.Exists(assemblyFullPath))
						{
							SortedList namespaces = re.GetNamespacesFromAssembly(rep, assemblyFullPath);
							foreach (string ns in namespaces.GetKeyList())
							{
								if (_namespaces == null)
									_namespaces = new SortedList();
								if ((!_namespaces.ContainsKey(ns)))
								{
									_namespaces.Add(ns, null);
								}
							}
						}
					}
				}
			}
			finally
			{
				if (appDomain != null) AppDomain.Unload(appDomain);
			}
		}
Example #26
0
        /// <summary>
        /// Builds the documentation.
        /// </summary>
        public override void Build(NDoc.Core.Project project)
        {
            int buildStepProgress = 0;

            OnDocBuildingStep(buildStepProgress, "Initializing...");

            _resourceDirectory = Path.Combine(Path.Combine(Environment.GetFolderPath(
                                                               Environment.SpecialFolder.ApplicationData), "NDoc"), "NAnt");

            // get assembly in which documenter is defined
            Assembly assembly = this.GetType().Module.Assembly;

            // write xslt files to resource directory
            EmbeddedResources.WriteEmbeddedResources(assembly, "Documenter.xslt",
                                                     Path.Combine(_resourceDirectory, "xslt"));

            // create the html output directories
            try {
                Directory.CreateDirectory(OutputDirectory);
                Directory.CreateDirectory(Path.Combine(OutputDirectory, "elements"));
                Directory.CreateDirectory(Path.Combine(OutputDirectory, "functions"));
                Directory.CreateDirectory(Path.Combine(OutputDirectory, "types"));
                Directory.CreateDirectory(Path.Combine(OutputDirectory, "tasks"));
                Directory.CreateDirectory(Path.Combine(OutputDirectory, "enums"));
                Directory.CreateDirectory(Path.Combine(OutputDirectory, "filters"));
            } catch (Exception ex) {
                throw new DocumenterException("The output directories could not"
                                              + " be created.", ex);
            }

            buildStepProgress += 10;
            OnDocBuildingStep(buildStepProgress, "Merging XML documentation...");

            // load the stylesheets that will convert the master xml into html pages
            MakeTransforms();

            // will hold the file name containing the NDoc generated XML
            string tempFile = null;

            try {
                // determine temporary file name
                tempFile = Path.GetTempFileName();

                // create the master XML document
                MakeXmlFile(project, tempFile);

                // create a xml document that will be transformed using xslt
                using (FileStream fs = new FileStream(tempFile, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                    _xmlDocumentation = new XmlDocument();
                    _xmlDocumentation.Load(fs);
                }
            } finally {
                // ensure temporary file is removed
                if (tempFile != null)
                {
                    File.Delete(tempFile);
                }
            }

            // build the file mapping
            buildStepProgress += 15;
            OnDocBuildingStep(buildStepProgress, "Building mapping...");

            // create arguments for nant index page transform
            XsltArgumentList indexArguments = CreateXsltArgumentList();

            // add extension object for NAnt utilities
            NAntXsltUtilities indexUtilities = NAntXsltUtilities.CreateInstance(
                _xmlDocumentation, (NAntDocumenterConfig)Config);

            // add extension object to Xslt arguments
            indexArguments.AddExtensionObject("urn:NAntUtil", indexUtilities);

            buildStepProgress += 15;
            OnDocBuildingStep(buildStepProgress, "Creating Task Index Page...");

            // transform nant task index page transform
            TransformAndWriteResult(_xsltTaskIndex, indexArguments, "tasks/index.html");

            buildStepProgress += 10;
            OnDocBuildingStep(buildStepProgress, "Creating Type Index Page...");

            // transform nant type index page transform
            TransformAndWriteResult(_xsltTypeIndex, indexArguments, "types/index.html");

            buildStepProgress += 10;
            OnDocBuildingStep(buildStepProgress, "Creating Filter Index Page...");

            // transform nant type index page transform
            TransformAndWriteResult(_xsltFilterIndex, indexArguments, "filters/index.html");

            OnDocBuildingStep(buildStepProgress, "Creating Function Index Page...");
            // transform nant function index page transform
            TransformAndWriteResult(_xsltFunctionIndex, indexArguments, "functions/index.html");

            buildStepProgress += 10;
            OnDocBuildingStep(buildStepProgress, "Generating Task Documents...");

            // generate a page for each marked task
            XmlNodeList typeNodes = _xmlDocumentation.SelectNodes("//class[starts-with(substring(@id, 3, string-length(@id) - 2), '" + NamespaceFilter + "')]");

            foreach (XmlNode typeNode in typeNodes)
            {
                ElementDocType elementDocType = indexUtilities.GetElementDocType(typeNode);
                DocumentType(typeNode, elementDocType, indexUtilities);
            }

            OnDocBuildingStep(buildStepProgress, "Generating Function Documents...");

            // generate a page for each function - TODO - change the XPath expression to select more functions
            XmlNodeList functionNodes = _xmlDocumentation.SelectNodes("//method[attribute/@name = 'NAnt.Core.Attributes.FunctionAttribute' and ancestor::class[starts-with(substring(@id, 3, string-length(@id) - 2), '" + NamespaceFilter + "')]]");

            foreach (XmlElement function in functionNodes)
            {
                DocumentFunction(function, indexUtilities);
            }

            OnDocBuildingStep(100, "Complete");
        }
Example #27
0
		/// <summary>See <see cref="IDocumenter"/>.</summary>
		public override void Build(Project project)
		{
			try
			{
				OnDocBuildingStep(0, "Initializing...");

				//Get an Encoding for the current LangID
				CultureInfo ci = new CultureInfo(MyConfig.LangID);
				currentFileEncoding = Encoding.GetEncoding(ci.TextInfo.ANSICodePage);

				// the workspace class is responsible for maintaining the outputdirectory
				// and compile intermediate locations
				workspace = new MsdnWorkspace( Path.GetFullPath( MyConfig.OutputDirectory ) );
				workspace.Clean();
				workspace.Prepare();

				// Write the embedded css files to the html output directory
				EmbeddedResources.WriteEmbeddedResources(
					this.GetType().Module.Assembly,
					"NDoc.Documenter.Msdn.css",
					workspace.WorkingDirectory);

				// Write the embedded icons to the html output directory
				EmbeddedResources.WriteEmbeddedResources(
					this.GetType().Module.Assembly,
					"NDoc.Documenter.Msdn.images",
					workspace.WorkingDirectory);

				// Write the embedded scripts to the html output directory
				EmbeddedResources.WriteEmbeddedResources(
					this.GetType().Module.Assembly,
					"NDoc.Documenter.Msdn.scripts",
					workspace.WorkingDirectory);

				if ( ((string)MyConfig.AdditionalContentResourceDirectory).Length > 0 )			
					workspace.ImportContentDirectory( MyConfig.AdditionalContentResourceDirectory );

				// Write the external files (FilesToInclude) to the html output directory

				foreach( string srcFilePattern in MyConfig.FilesToInclude.Split( '|' ) )
				{
					if ((srcFilePattern == null) || (srcFilePattern.Length == 0))
						continue;

					string path = Path.GetDirectoryName(srcFilePattern);
					string pattern = Path.GetFileName(srcFilePattern);
 
					// Path.GetDirectoryName can return null in some cases.
					// Treat this as an empty string.
					if (path == null)
						path = string.Empty;
 
					// Make sure we have a fully-qualified path name
					if (!Path.IsPathRooted(path))
						path = Path.Combine(Environment.CurrentDirectory, path);
 
					// Directory.GetFiles does not accept null or empty string
					// for the searchPattern parameter. When no pattern was
					// specified, assume all files (*) are wanted.
					if ((pattern == null) || (pattern.Length == 0))
						pattern = "*";
 
					foreach(string srcFile in Directory.GetFiles(path, pattern))
					{
						string dstFile = Path.Combine(workspace.WorkingDirectory, Path.GetFileName(srcFile));
						File.Copy(srcFile, dstFile, true);
						File.SetAttributes(dstFile, FileAttributes.Archive);
					}
				}
				OnDocBuildingStep(10, "Merging XML documentation...");

				// Will hold the name of the file name containing the XML doc
				string tempFileName = null;

				try 
				{
					// determine temp file name
					tempFileName = Path.GetTempFileName();
					// Let the Documenter base class do it's thing.
					MakeXmlFile(project, tempFileName);

					// Load the XML documentation into DOM and XPATH doc.
					using (FileStream tempFile = File.Open(tempFileName, FileMode.Open, FileAccess.Read)) 
					{
						FilteringXmlTextReader fxtr = new FilteringXmlTextReader(tempFile);
						xmlDocumentation = new XmlDocument();
						xmlDocumentation.Load(fxtr);

						tempFile.Seek(0,SeekOrigin.Begin);
						XmlTextReader reader = new XmlTextReader(tempFile);
						xpathDocument = new XPathDocument(reader, XmlSpace.Preserve);
					}
				}
				finally
				{
					if (tempFileName != null && File.Exists(tempFileName)) 
					{
						File.Delete(tempFileName);
					}
				}

				XmlNodeList typeNodes = xmlDocumentation.SelectNodes("/ndoc/assembly/module/namespace/*[name()!='documentation']");
				if (typeNodes.Count == 0)
				{
					throw new DocumenterException("There are no documentable types in this project.\n\nAny types that exist in the assemblies you are documenting have been excluded by the current visibility settings.\nFor example, you are attempting to document an internal class, but the 'DocumentInternals' visibility setting is set to False.\n\nNote: C# defaults to 'internal' if no accessibilty is specified, which is often the case for Console apps created in VS.NET...");
				}

				XmlNodeList namespaceNodes = xmlDocumentation.SelectNodes("/ndoc/assembly/module/namespace");
				int[] indexes = SortNodesByAttribute(namespaceNodes, "name");

				XmlNode defaultNamespace = namespaceNodes[indexes[0]];;

				string defaultNamespaceName = (string)defaultNamespace.Attributes["name"].Value;
				string defaultTopic = defaultNamespaceName + ".html";

				// setup for root page
				string rootPageFileName = null;
				string rootPageTOCName = "Overview";

				if ((MyConfig.RootPageFileName != null) && (MyConfig.RootPageFileName != string.Empty))
				{
					rootPageFileName = MyConfig.RootPageFileName;
					defaultTopic = "default.html";

					// what to call the top page in the table of contents?
					if ((MyConfig.RootPageTOCName != null) && (MyConfig.RootPageTOCName != string.Empty))
					{
						rootPageTOCName = MyConfig.RootPageTOCName;
					}
				}

				htmlHelp = new HtmlHelp(
					workspace.WorkingDirectory,
					MyConfig.HtmlHelpName,
					defaultTopic,
					((MyConfig.OutputTarget & OutputType.HtmlHelp) == 0));

				htmlHelp.IncludeFavorites = MyConfig.IncludeFavorites;
				htmlHelp.BinaryTOC = MyConfig.BinaryTOC;
				htmlHelp.LangID=MyConfig.LangID;

				OnDocBuildingStep(25, "Building file mapping...");

				MakeFilenames();

				string DocLangCode = Enum.GetName(typeof(SdkLanguage),MyConfig.SdkDocLanguage).Replace("_","-");
				utilities = new MsdnXsltUtilities(fileNames, elemNames, MyConfig.SdkDocVersion, DocLangCode, MyConfig.SdkLinksOnWeb, currentFileEncoding);

				OnDocBuildingStep(30, "Loading XSLT files...");

				stylesheets = StyleSheetCollection.LoadStyleSheets(MyConfig.ExtensibilityStylesheet);

				OnDocBuildingStep(40, "Generating HTML pages...");

				htmlHelp.OpenProjectFile();

				htmlHelp.OpenContentsFile(string.Empty, true);

				try
				{
					if (MyConfig.CopyrightHref != null && MyConfig.CopyrightHref != String.Empty)
					{
						if (!MyConfig.CopyrightHref.StartsWith("http:"))
						{
							string copyrightFile = Path.Combine(workspace.WorkingDirectory, Path.GetFileName(MyConfig.CopyrightHref));
							File.Copy(MyConfig.CopyrightHref, copyrightFile, true);
							File.SetAttributes(copyrightFile, FileAttributes.Archive);
							htmlHelp.AddFileToProject(Path.GetFileName(MyConfig.CopyrightHref));
						}
					}

					// add root page if requested
					if (rootPageFileName != null)
					{
						if (!File.Exists(rootPageFileName))
						{
							throw new DocumenterException("Cannot find the documentation's root page file:\n" 
								+ rootPageFileName);
						}

						// add the file
						string rootPageOutputName = Path.Combine(workspace.WorkingDirectory, "default.html");
						if (Path.GetFullPath(rootPageFileName) != Path.GetFullPath(rootPageOutputName))
						{
							File.Copy(rootPageFileName, rootPageOutputName, true);
							File.SetAttributes(rootPageOutputName, FileAttributes.Archive);
						}
						htmlHelp.AddFileToProject(Path.GetFileName(rootPageOutputName));
						htmlHelp.AddFileToContents(rootPageTOCName, 
							Path.GetFileName(rootPageOutputName));

						// depending on peer setting, make root page the container
						if (MyConfig.RootPageContainsNamespaces) htmlHelp.OpenBookInContents();
					}

					documentedNamespaces = new ArrayList();
					MakeHtmlForAssemblies();

					// close root book if applicable
					if (rootPageFileName != null)
					{
						if (MyConfig.RootPageContainsNamespaces) htmlHelp.CloseBookInContents();
					}
				}
				finally
				{
					htmlHelp.CloseContentsFile();
					htmlHelp.CloseProjectFile();
				}

				htmlHelp.WriteEmptyIndexFile();

				if ((MyConfig.OutputTarget & OutputType.Web) > 0)
				{
					OnDocBuildingStep(75, "Generating HTML content file...");

					// Write the embedded online templates to the html output directory
					EmbeddedResources.WriteEmbeddedResources(
						this.GetType().Module.Assembly,
						"NDoc.Documenter.Msdn.onlinefiles",
						workspace.WorkingDirectory);

					using (TemplateWriter indexWriter = new TemplateWriter(
							   Path.Combine(workspace.WorkingDirectory, "index.html"),
							   new StreamReader(this.GetType().Module.Assembly.GetManifestResourceStream(
							   "NDoc.Documenter.Msdn.onlinetemplates.index.html"))))
					{
						indexWriter.CopyToLine("\t\t<title><%TITLE%></title>");
						indexWriter.WriteLine("\t\t<title>" + MyConfig.HtmlHelpName + "</title>");
						indexWriter.CopyToLine("\t\t<frame name=\"main\" src=\"<%HOME_PAGE%>\" frameborder=\"1\">");
						indexWriter.WriteLine("\t\t<frame name=\"main\" src=\"" + defaultTopic + "\" frameborder=\"1\">");
						indexWriter.CopyToEnd();
						indexWriter.Close();
					}

					Trace.WriteLine("transform the HHC contents file into html");
#if DEBUG
					int start = Environment.TickCount;
#endif
					//transform the HHC contents file into html
					using(StreamReader contentsFile = new StreamReader(htmlHelp.GetPathToContentsFile(),Encoding.Default))
					{
						xpathDocument=new XPathDocument(contentsFile);
					}
					using ( StreamWriter streamWriter = new StreamWriter(
								File.Open(Path.Combine(workspace.WorkingDirectory, "contents.html"), FileMode.CreateNew, FileAccess.Write, FileShare.None ), Encoding.Default ) )
					{
#if(NET_1_0)
						//Use overload that is obsolete in v1.1
						stylesheets["htmlcontents"].Transform(xpathDocument, null, streamWriter);
#else
						//Use new overload so we don't get obsolete warnings - clean compile :)
						stylesheets["htmlcontents"].Transform(xpathDocument, null, streamWriter, null);
#endif
					}
#if DEBUG
					Trace.WriteLine((Environment.TickCount - start).ToString() + " msec.");
#endif
				}

				if ((MyConfig.OutputTarget & OutputType.HtmlHelp) > 0)
				{
					OnDocBuildingStep(85, "Compiling HTML Help file...");
					htmlHelp.CompileProject();
				}
				else
				{
#if !DEBUG
					//remove .hhc file
					File.Delete(htmlHelp.GetPathToContentsFile());
#endif
				}

				// if we're only building a CHM, copy that to the Outpur dir
				if ((MyConfig.OutputTarget & OutputType.HtmlHelp) > 0 && (MyConfig.OutputTarget & OutputType.Web) == 0) 
				{
					workspace.SaveOutputs( "*.chm" );
				} 
				else 
				{
					// otherwise copy everything to the output dir (cause the help file is all the html, not just one chm)
					workspace.SaveOutputs( "*.*" );
				}
				
				if ( MyConfig.CleanIntermediates )
					workspace.CleanIntermediates();
				
				OnDocBuildingStep(100, "Done.");
			}
			catch(Exception ex)
			{
				throw new DocumenterException(ex.Message, ex);
			}
			finally
			{
				xmlDocumentation = null;
 				xpathDocument = null;
 				stylesheets = null;
				workspace.RemoveResourceDirectory();
			}
		}
Example #28
0
		/// <summary>See <see cref="IDocumenter.CanBuild">IDocumenter.CanBuild</see>.</summary>
		public virtual string CanBuild(Project project)
		{
			return this.CanBuild(project, false);
		}
Example #29
0
 /// <summary>
 /// Initialize namespace dictionary
 /// </summary>
 public static void InitializeNamespaces(Project project)
 {
     // If we don't have namespaces list yet, go through each referenced assembly,
     // load the assembly, get the types, then cache the namespaces for all public types.
     if (namespaces.Count == 0)
     {
         foreach (AssemblySlashDoc doc in project.AssemblySlashDocs)
         {
             Assembly theAssembly = Assembly.LoadFrom(doc.Assembly);
             AssemblyName[] assemblies = theAssembly.GetReferencedAssemblies();
             foreach (AssemblyName an in assemblies)
             {
                 Assembly assembly = Assembly.LoadWithPartialName(an.Name);
                 Type[] assemblyTypes = assembly.GetTypes();
                 foreach (Type type in assemblyTypes)
                 {
                     if (type.IsPublic)
                     {
                         namespaces[type.Namespace] = type.Namespace.Replace('.', '_') + '_';
                         namespaces[type.Namespace.Replace(".", "")] = type.Namespace.Replace('.', '_') + '_';
                     }
                 }
             }
         }
     }
 }
Example #30
0
		/// <summary>See <see cref="IDocumenter"/>.</summary>
		public override string CanBuild(Project project, bool checkInputOnly)
		{
			string result = base.CanBuild(project, checkInputOnly); 
			if (result != null)
			{
				return result;
			}

			string AdditionalContentResourceDirectory = MyConfig.AdditionalContentResourceDirectory;
			if ( AdditionalContentResourceDirectory.Length != 0 && !Directory.Exists( AdditionalContentResourceDirectory ) )
				return string.Format( "The Additional Content Resource Directory {0} could not be found", AdditionalContentResourceDirectory );

			string ExtensibilityStylesheet = MyConfig.ExtensibilityStylesheet;
			if ( ExtensibilityStylesheet.Length != 0 && !File.Exists( ExtensibilityStylesheet ) )
				return string.Format( "The Extensibility Stylesheet file {0} could not be found", ExtensibilityStylesheet );

			if (checkInputOnly) 
			{
				return null;
			}

			string path = Path.Combine(MyConfig.OutputDirectory, 
				MyConfig.HtmlHelpName + ".chm");

			string temp = Path.Combine(MyConfig.OutputDirectory, "~chm.tmp");

			try
			{

				if (File.Exists(path))
				{
					//if we can move the file, then it is not open...
					File.Move(path, temp);
					File.Move(temp, path);
				}
			}
			catch (Exception)
			{
				result = "The compiled HTML Help file is probably open.\nPlease close it and try again.";
			}

			return result;
		}
Example #31
0
        /// <summary>
        /// Read HTML file one line at a time.  If HREF is found, call Fix20HRef to update for V2.0 formatting
        /// </summary>
        /// <param name="project">project object containing properties for help file</param>
        /// <param name="fullPath">Fully qualified HTML file path</param>
        /// <param name="encoding">Current encoding for the HTML file</param>
        /// <param name="documentor">MSDN IDocumentor needed by helper methods</param>
        public static void UpdateHtmlHrefs(Project project, string fullPath, Encoding encoding, Msdn2Documenter documentor)
        {
            InitializeNamespaces(project);

            // For generated .html file, create a temporary (.tmp) file with corrected ms-help URLs.  When
            // finished correcting URLs, swap temporary file for generated one, then delete original file.
            string filePath = fullPath.Substring(0,fullPath.LastIndexOf("\\") + 1);
            string tempFile = fullPath + ".tmp";
            using (StreamReader streamReader = new StreamReader(File.Open(fullPath, FileMode.Open), encoding))
            using (StreamWriter streamWriter = new StreamWriter(File.Open(tempFile, FileMode.Create), encoding))
            {
                // Search generated .html file for href links.  For each link, call FixV20HRef to verify/correct link.
                string line;
                do
                {
                    line = streamReader.ReadLine();
                    if (line != null)
                    {
                        int index = 0;
                        while (index >= 0 && index < line.Length && line.IndexOf("href=\"",index) > 0)
                        {
                            index = line.IndexOf("href=\"", index);
                            int indexEnd = line.IndexOf("\"", index + 6);
                            string href = line.Substring(index, (indexEnd - index + 1));
                            bool validLocalUrl = false;
                            if (href.IndexOf("ms-help://") == -1)
                            {
                                line = FixLocalUrl(line,href,filePath,index);
                            }
                            else
                            {
                                string newHRef = FixV20HRef(href, documentor, filePath, ref validLocalUrl);
                                line = line.Replace(href, newHRef);
                            }
                            index++; // look for another HREF
                        }
                        streamWriter.WriteLine(line);
                    }
                }
                while (line != null);
            }
            // Swap updated HTML file with original HTML file, then delete original file.
            System.IO.File.Replace(tempFile, fullPath, fullPath + ".bak");
            System.IO.File.Delete(fullPath + ".bak");
        }
Example #32
0
		public static int Main(string[] args)
		{
			try
			{
				WriteLogoBanner();

				project = new Project();
				documenter = project.GetDocumenter("MSDN");
				if (documenter == null)
				{
					//MSDN documenter not found, pick the first one available.
					if (project.Documenters.Count > 0)
					{
						documenter = (IDocumenter)project.Documenters[0];
					}
					else
					{
						throw new ApplicationException("Could not find any documenter assemblies.");
					}
				}
				int maxDepth = 20; //to limit recursion depth
				bool propertiesSet = false;
				bool projectSet = false;

				if (args.Length==0)
				{
					WriteUsage();
					return 1;
				}

				if (args[0].ToLower().StartsWith("-help"))
				{
					WriteHelp(args);
					return 1;
				}

				foreach (string arg in args)
				{
					if (arg.StartsWith("-"))
					{
						if (string.Compare(arg, "-verbose", true) == 0)
						{
							Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
						}
						else
						{
							string[] pair = arg.Split('=');

							if (pair.Length == 2)
							{
								string name = pair[0].Substring(1);
								string val = pair[1];

								switch (name.ToLower())
								{
									case "documenter":
										if (propertiesSet)
										{
											throw new ApplicationException("The documenter name must be specified before any documenter specific options.");
										}
										if (projectSet)
										{
											throw new ApplicationException("The documenter name must be specified before the project file.");
										}
										documenter = project.GetDocumenter(val.Replace("_"," "));
										if (documenter == null)
										{
											throw new ApplicationException("The specified documenter name is invalid.");
										}
										break;
									case "project":
										if (propertiesSet)
										{
											throw new ApplicationException("The project file must be specified before any documenter specific options.");
										}
										project = new Project();
										documenter = project.GetDocumenter(documenter.Name);
										documenter.Config.SetProject(project);
										project.Read(val);
										projectSet = true;
										break;
									case "recurse":
										string[] recPair = val.Split(',');
										if (2 == recPair.Length)
										{
											maxDepth = Convert.ToInt32(recPair[1]);
										}
										RecurseDir(recPair[0], maxDepth);
										break;
									case "namespacesummaries":
										using(StreamReader streamReader = new StreamReader(val))
										{
											XmlTextReader reader = new XmlTextReader(streamReader);
											reader.MoveToContent();
											project.Namespaces.Read(reader);
											reader.Close();
											streamReader.Close();
										}
										break;
									case "referencepath":
										project.ReferencePaths.Add(new ReferencePath(val));
										break;
									default:
										documenter.Config.SetValue(name, val);
										propertiesSet = true;
										break;
								}
							}
						}
					}
					else if (arg.IndexOf(',') != -1)
					{
						string[] pair = arg.Split(',');

						if (pair.Length == 2)
						{
							project.AssemblySlashDocs.Add(
								new AssemblySlashDoc(pair[0], pair[1]));
						}
					}
					else
					{
						string doc = Path.ChangeExtension(arg, ".xml");
						if (File.Exists(doc))
						{
							project.AssemblySlashDocs.Add(
								new AssemblySlashDoc(arg, doc));
						}
						else
						{
							project.AssemblySlashDocs.Add(
								new AssemblySlashDoc(arg, ""));
						}
					}
				}

				if (project.AssemblySlashDocs.Count == 0)
				{
					WriteUsage();
					return 1;
				}
				else
				{
					documenter.DocBuildingStep += new DocBuildingEventHandler(DocBuildingStepHandler);
					documenter.Build(project);
					return 0;
				}
			}
			catch( Exception except )
			{
				string errorText= BuildExceptionText(except);
				Console.WriteLine(errorText);
				System.Diagnostics.Trace.WriteLine(errorText);
				return 2;
			}
		}
Example #33
0
		private NDoc.Core.Project GetNDocProject()
		{
			NDoc.Core.Project ndocProject = new NDoc.Core.Project();
			MsdnDocumenter msdnDocumenter = new MsdnDocumenter();
			XmlDocumenter xmlDocumenter = new XmlDocumenter();
			
			ndocProject.Documenters.Add(msdnDocumenter);
			ndocProject.Documenters.Add(xmlDocumenter);

			// If solution file doesn't exist yet then that's ok.
			try
			{
				ndocProject.Read(ndocProjectFullName);
			}
			catch(Exception){}

			return ndocProject;
		}