Thursday, October 11, 2007

When someone is writing a book that contains code snippets, the question of (automatically) keeping those in sync quickly becomes very imporant. There's already lots of different solutions to this problem (every author has probably it's own), here's yet another one for C# that we've developed to author the Pex documentation.

Goals

A couple things that we wanted to acheive with this tool:

  • snippets are always compilable and run as expected,
  • snippets can be full classes, methods or even partial statements
  • simple :)

'#region' based solution

This solution uses the #region directive to define a snippet. The region describe contains the snippet name, which will be used to dump it into a file. For example, given this piece of C#,

...
#region snippet StackExamplePart3
stack.Push(new object);
#endregion
...

Our parse will extract the code in the region and write it to StackExamplePart3.tex, which gets pulled in our LaTeX scripts.

\begin{verbatim}
stack.Push(new object);
\end{verbatim}

That's it?

Yes, you can author snippets that stay compilable and up to date:

  • we can author all the snippets in Visual Studio and we are sure they always compile
  • it's very easy to parse the #region's (left as exercise ;))
  • #region are very flexible in terms what they contain so we can have snippets containing partial methods, statement, etc...
  • the scheme aslo supports nested regions which is usefull when one explains an example line by line, and integrate the entire sample at the end. For example, DeclaringUnitTest is a 'sub'-snippet of UnitTest:
#region snippet UnitTest
#region snippet DeclaringUnitTest
[TestMethod]
void Test(int i)
#endregion
{
   
}
#endregion
  • we can integrate our snippets in unit tests and verify they work as expected
  • the tool can be integrated into the build process as a post-command build

 

Thursday, October 11, 2007 2:43:59 PM UTC
Hi Peli,
Your link to the Pex documentation takes us to what looks to be a domain squatter page.

I am looking forward to the day that Pex becomes available externally.

Cheers,
Ben.
Ben C
Thursday, October 11, 2007 9:36:42 PM UTC
Thanks I've fixed the link. I also looking towards the day Pex becomes available externally. :)
Peli
Comments are closed.