Click here to Skip to main content
15,894,124 members
Articles / Programming Languages / C#

Make NDoc compile the code examples contained in your documentation using NLiterate

Rate me:
Please Sign up or sign in to vote.
4.64/5 (19 votes)
26 Apr 20047 min read 124K   622   42  
An utility that merges and recompiles the examples in your documentation using NDoc.
// The MIT License
// Copyright (c) 2004 Jonathan de Halleux
//
// Permission is hereby granted, free of charge, to any person obtaining a 
// copy of this software and associated documentation files (the "Software"), 
// to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, 
// and/or sell copies of the Software, and to permit persons to whom the 
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in 
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.

namespace NLiterate
{
	using System;
	using System.Xml;
	using System.Text.RegularExpressions;	
	
	/// <summary>
	/// A snippet of code for literate documentation.
	/// </summary>
	/// <remarks>
	/// <para>
	/// 
	/// </para>
	/// </remarks>
	public class CodeSnippetNode
	{
		#region Static members
		private static Regex snippetRegex = new Regex(
		    @"{\[(?<SnippetID>\w+\b).*?\]}",
		    RegexOptions.IgnoreCase
    		| RegexOptions.Multiline
    		| RegexOptions.ExplicitCapture
    		| RegexOptions.Compiled
    		);		
		#endregion
		
		#region Private Fields
		private CodeSnippetNode parent;
		private string id;
		private string title;
		private string code;
		private CodeSnippetNodeCollection childNodes = new CodeSnippetNodeCollection();
		#endregion

		#region Constructors	
		/// <summary>
		/// Initializes a new <see cref="CodeSnippetNode"/>
		/// </summary>
		/// <param name="parent">Parent <see cref="CodeSnippetNode"/></param>
		/// <param name="id">node id</param>
		/// <param name="title">node title</param>
		/// <param name="code">node source code</param>
		/// <exception cref="ArgumentNullException">
		/// <paramref name="id"/> or
		/// <paramref name="code"/> is a null reference (Nothing in 
		/// Visual Basic)
		/// </exception>
		protected CodeSnippetNode(CodeSnippetNode parent, string id, string title, string code)
		{
			if (id==null)
				throw new ArgumentNullException("id");
			if (code==null)
				throw new ArgumentNullException("code");
			this.parent = parent;
			this.id = id;
			this.title = title;
			this.code = code;
		}
		#endregion
		
		#region Properties
		/// <summary>
		/// Gets the parent snippet of code
		/// </summary>
		/// <value>
		/// Parent <see cref="CodeSnippetNode"/> instance
		/// </value>
		public CodeSnippetNode ParentNode
		{
			get
			{
				return this.parent;
			}
		}

		/// <summary>
		/// Gets the referenced snippets of code nodes
		/// </summary>
		/// <value>
		/// Collection of child <see cref="CodeSnippetNode"/> instance
		/// </value>
		public CodeSnippetNodeCollection ChildNodes
		{
			get
			{
				return this.childNodes;
			}
		}	

		/// <summary>
		/// Gets the Code snippet ID
		/// </summary>
		/// <value>
		/// The snippet ID
		/// </value>
		public String ID
		{
			get
			{
				return this.id;
			}
		}

		/// <summary>
		/// Gets the <see cref="CodeSnippetNode"/> title
		/// </summary>
		/// <value>
		/// <see cref="CodeSnippetNode"/> title
		/// </value>
		public String Title
		{
			get
			{
				return this.title;
			}
		}

		/// <summary>
		/// Gets the raw code data of the <see cref="CodeSnippetNode"/>
		/// </summary>
		/// <value>
		/// The row content of the <see cref="CodeSnippetNode"/>
		/// </value>
		public String Code
		{
			get
			{
				return this.code;
			}
		}	

		/// <summary>
		/// Gets the <see cref="CodeSnippetNode"/> content where child snippet 
		/// have been merged in.
		/// </summary>
		/// <returns>
		/// Merged code
		/// </returns>
		public String GetMergedCode()
		{
			return snippetRegex.Replace(this.code,new MatchEvaluator(this.CodeMerger));
		}
		
		private string CodeMerger(Match m)
		{
			// find code snippet with the right id
			string cid = m.Groups["SnippetID"].Value;
			foreach(CodeSnippetNode node in this.childNodes)
			{
				if (node.ID!=cid)
					continue;
				
				return String.Format("\n//<code id=\"{0}\" title=\"{1}\">\n{2}\n//</code>",
				                     node.ID,
				                     node.Title,
				                     node.GetMergedCode()
				                     );
			}
			
			throw new InvalidOperationException("unexpeceted exception");
		}
		
		/// <summary>
		/// Converts the <see cref="CodeSnippetNode"/> to code
		/// </summary>
		/// <returns>
		/// String representing the <see cref="CodeSnippetNode"/>.
		/// </returns>
		public override String ToString()
		{
			return String.Format("<code id=\"{0}\" title=\"{1}\">\n{2}\n</code>",this.id,this.title,this.code);
		}
		#endregion
		
		#region Static methods
		/// <summary>
		/// Creates from XML
		/// </summary>
		/// <param name="parent">parent node</param>
		/// <param name="parentEl">parent xml node</param>
		/// <param name="el">xml node</param>
		/// <returns>
		/// A new <see cref="CodeSnippetNode"/> instance
		/// </returns>
		/// <exception cref="ArgumentNullException">
		/// <paramref name="parentEl"/> or <paramref name="el"/>  
		/// is a null reference (Nothing in 
		/// Visual Basic)
		/// </exception>
		/// <exception cref="ArgumentException">
		/// <paramref name="el"/>.Name is not <c>"code"</c>.
		/// </exception>
		/// <exception cref="ArgumentException">
		/// <c>el/@id</c> is missing.
		/// </exception>		
		internal static CodeSnippetNode FromXml(CodeSnippetNode parent, XmlElement parentEl, XmlElement el)
		{
			if (parentEl==null)
				throw new ArgumentNullException("parentEl");
			if (el==null)
				throw new ArgumentNullException("el");
			if (el.Name!="code")
				throw new ArgumentException("el should be code");
			
			// getting data
			XmlAttribute id = el.Attributes["id"];
			if (id==null)
				throw new ArgumentException("el/@id missing");
			XmlAttribute title = el.Attributes["title"];
			
			CodeSnippetNode node = new CodeSnippetNode(
				parent,
				id.Value,
				(title!=null) ? title.Value : null,
				el.InnerXml);
			
			// getting inner snippets
			foreach(Match m in snippetRegex.Matches(node.Code))
			{
				string cid = m.Groups["SnippetID"].Value;
				if (cid==null)
					throw new ArgumentException("snippet reference id is empty");
				
				// find code snippet find ID.
				XmlElement cel = (XmlElement)parentEl.SelectSingleNode(String.Format("//code[@id='{0}']",cid));
				if(cel==null)
					throw new ArgumentException(
						String.Format("code[@id='{0}'] not found",cid));
				
				node.ChildNodes.Add( FromXml(node,parentEl,cel) );
			}
			
			return node;
		}
		#endregion
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Engineer
United States United States
Jonathan de Halleux is Civil Engineer in Applied Mathematics. He finished his PhD in 2004 in the rainy country of Belgium. After 2 years in the Common Language Runtime (i.e. .net), he is now working at Microsoft Research on Pex (http://research.microsoft.com/pex).

Comments and Discussions