Click here to Skip to main content
Click here to Skip to main content
Articles » Languages » C# » Attributes » Downloads
 
Add your own
alternative version

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

, 26 Apr 2004
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.Collections.Specialized;
	using System.Text.RegularExpressions;
	using System.CodeDom.Compiler;
	using System.Xml;
	using System.IO;

	/// <summary>
	/// Type of compilable language
	/// </summary>
	public enum CodeLanguage
	{
		/// <summary>
		/// C#
		/// </summary>
		CS,
		/// <summary>
		/// Visual Basic
		/// </summary>
		VB
	}

	/// <summary>
	/// A tree of snippets
	/// </summary>
	public class CodeSnippet
	{
		private StringCollection references = new StringCollection();
		private string hiddenNamespace=null;
		private CodeLanguage language = CodeLanguage.CS;
		private bool entryPoint = true;
		private CodeSnippetNode root;
		private XmlNode parentNode;
		private CompilerResults results = null;
		private ExecutionResults executionResults = null;

		/// <summary>
		/// Creates a new <see cref="CodeSnippet"/> instance.
		/// </summary>
		/// <param name="parentEl">Parent XML node that contains the child
		/// code</param>
		/// <param name="el">root code element</param>
		/// <exception cref="ArgumentNullException">
		/// <paramref name="parentEl"/> or <paramref name="el"/>
		/// is a null reference (Nothing in Visual Basic)
		/// </exception>
		protected CodeSnippet(XmlElement parentEl, XmlElement el)
		{
			if (parentEl==null)
				throw new ArgumentNullException("parentEl");
			if (el==null)
				throw new ArgumentNullException("el");
			
			XmlAttribute compilable = el.Attributes["compilable"];
			if (compilable==null)
				throw new ArgumentException("code/@compilable is missing");
			if (!System.Boolean.Parse(compilable.Value))
				throw new ArgumentException("code/@compilable is not true");
			
			XmlAttribute entryPoint = el.Attributes["entry-point"];	
			if (entryPoint!=null)
				this.entryPoint = System.Boolean.Parse(entryPoint.Value);
			
			XmlAttribute language = el.Attributes["language"];
			if(language!=null)
				this.language = (CodeLanguage)Enum.Parse(typeof(CodeLanguage),language.Value,true);			
			
			XmlAttribute hns = el.Attributes["hidden-namespace"];
			if (hns!=null)
				this.hiddenNamespace = hns.Value;

			this.parentNode = parentEl;
			// loading code
			this.root = CodeSnippetNode.FromXml(null,parentEl,el);

			// adding default assemblies
			this.references.Add("System.dll");
		}

		/// <summary>
		/// Gets the parent XML node
		/// </summary>
		/// <value>
		/// Parent <see cref="XmlNode"/> instance.
		/// </value>
		public XmlNode ParentNode
		{
			get
			{
				return this.parentNode;
			}
		}

		/// <summary>
		/// Gets the additional assembly references collection
		/// </summary>
		/// <value>
		/// The assembly reference collection.
		/// </value>
		public StringCollection References
		{
			get
			{
				return this.references;
			}
		}

		/// <summary>
		/// Gets or sets the target language.
		/// </summary>
		/// <value>
		/// A value of <see cref="CodeLanguage"/> that identifies
		/// the target .NET language.
		/// </value>
		public CodeLanguage Language
		{
			get
			{
				return this.language;				
			}
			set
			{
				this.language = value;
			}
		}
		
		/// <summary>
		/// Gets or sets a value indicating if the snippet can be run (
		/// if it has an entry point).
		/// </summary>
		/// <value>
		/// true if the snippet has an entry point; otherwise false.
		/// </value>
		public bool EntryPoint
		{
			get
			{
				return this.entryPoint;
			}
			set
			{
				this.entryPoint = value;
			}
		}
		
		/// <summary>
		/// Gets or sets the compilation results
		/// </summary>
		/// <value>
		/// An instance of <see cref="CompilerResults"/> describing
		/// the compilation.
		/// </value>
		public CompilerResults Results
		{
			get
			{
				return this.results;
			}
			set
			{
				this.results = value;
			}
		}

		/// <summary>
		/// Gets or sets the execution results.
		/// </summary>
		/// <value>
		/// An <see cref="ExecutionResults"/> instance if the code was run;
		/// otherwise a null reference (Nothing in Visual Basic).
		/// </value>
		public ExecutionResults ExecutionResults
		{
			get
			{
				return this.executionResults;
			}
			set
			{
				this.executionResults = value;
			}
		}

		/// <summary>
		/// Gets or set the <see cref="CodeSnippet"/> hidden namespace.
		/// </summary>
		/// <value>
		/// Hidden namespace.
		/// </value>
		public String HiddenNamespace
		{
			get
			{
				return this.hiddenNamespace;
			}
			set
			{
				this.hiddenNamespace = value;
			}
		}
		
		/// <summary>
		/// Gets the root snippet node.
		/// </summary>
		/// <value>
		/// Root <see cref="CodeSnippetNode"/> instance.
		/// </value>
		public CodeSnippetNode Root
		{
			get
			{
				return this.root;
			}
		}
		
		/// <summary>
		/// Gets the merge source code
		/// </summary>
		/// <returns>
		/// Merge source code
		/// </returns>
		public String GetSource()
		{
			if (this.hiddenNamespace!=null)
			{
				StringWriter sw = new StringWriter();
				sw.WriteLine("namespace {0}",this.hiddenNamespace);
				sw.WriteLine("{");
				sw.WriteLine(this.root.GetMergedCode());
				sw.WriteLine("}");
				return sw.ToString();
			}
			else
				return this.root.GetMergedCode();
		}
				
		/// <summary>
		/// Converts to a string describing the snippet.
		/// </summary>
		/// <returns>
		/// A <see cref="String"/> describing the <see cref="CodeSnippet"/>.
		/// </returns>
		public override String ToString()
		{
			StringWriter sw =new StringWriter();
			sw.WriteLine("Language:{0}",this.Language.ToString());
			sw.WriteLine("EntryPoint:{0}", this.EntryPoint.ToString());
			sw.WriteLine("Source Xml code:{0}{1}",sw.NewLine,this.parentNode.OuterXml);
			sw.WriteLine("MergedCode:{0}{1}",sw.NewLine,this.GetSource());
			sw.WriteLine("Compilation results:");
			foreach(CompilerError error in this.Results.Errors)
			{
				sw.WriteLine(error.ToString());
			}
			if (this.EntryPoint)
				sw.WriteLine("Execution results:{0}{1}",sw.NewLine,this.ExecutionResults);
			
			return sw.ToString();
		}

		/// <summary>
		/// Gets the number of <see cref="CodeSnippet"/> in the document
		/// </summary>
		/// <remarks>
		/// This count is computed using the following XPath expression:
		/// <c>"//member/descendant::code[@compilable='true']"</c>
		/// </remarks>
		/// <param name="doc">XML document</param>
		/// <returns>
		/// Number of parts.
		/// </returns>
		public static int SnippetCount(XmlDocument doc)
		{
			return doc.SelectNodes("//member/descendant::code[@compilable='true']").Count;
		}

		/// <summary>
		/// Creates a <see cref="CodeSnippet"/> instance from xml.
		/// </summary>
		/// <param name="assemblyLocation">Name of the documented assembly</param>
		/// <param name="doc">Xml document</param>
		/// <param name="snippets">
		/// Collection where the created snippets are stored
		/// </param>
		/// <exception cref="ArgumentNullException">
		/// <paramref name="assemblyLocation"/> or <paramref name="doc"/>
		/// or <paramref name="snippets"/> is a null reference (Nothing in
		/// Visual Basic).
		/// </exception>
		public static void FromXml(string assemblyLocation, XmlDocument doc, CodeSnippetCollection snippets)
		{
			if (assemblyLocation==null)
				throw new ArgumentNullException("assemblyLocation");
			if (doc==null)
				throw new ArgumentNullException("doc");
			if (snippets==null)
				throw new ArgumentNullException("snippets");

			
			// matching code that are compilable
			foreach(XmlElement member in doc.SelectNodes("//member"))
			{
				foreach(XmlElement code in member.SelectNodes("descendant::code[@compilable='true']"))
				{
					CodeSnippet snippet = new CodeSnippet( member,code );

					// add self-assembly
					snippet.References.Add(assemblyLocation);
					// load reference
					foreach(XmlAttribute r in member.SelectNodes("reference/@assembly"))
					{
						if (!snippet.References.Contains(r.Value))
							snippet.References.Add(r.Value);	
					}

					// loading code
					snippets.Add(snippet);						
				}
			}
		}
	}
}

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

About the Author

Jonathan de Halleux
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).

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 27 Apr 2004
Article Copyright 2004 by Jonathan de Halleux
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid