Code Snippets File

The code snippets file allows you to define code samples outside of conceptual topic files. Each snippet has a unique ID that can be referenced in multiple topics using a codeReference MAML element so that the snippets do not have to be copied into each one. Automatic colorization and language filter synchronization is supported by specifying a language identifier on the code samples.

Currently supported identifiers are VisualBasic, CSharp, ManagedCPlusPlus, JSharp, and JScript. Custom colorization rules can be added to the conceptual configuration file for the ExampleComponent.

  Note

When using the Sandcastle Help File Builder or the standalone build components from it, the Code Block Component offers the same set of features and several others for both inline and external code snippets. In addition, it supports many other languages and can import code from working source code files which allows you to pull in examples from working projects that you can maintain and build without having to update a separate example snippets file. As such, you may prefer to use it rather than the code snippets file.

Code Snippets File Format

Below is an example of a code snippets file.

Example Code Snippets File
<?xml version="1.0" encoding="utf-8" ?>
<!-- This is an example code snippets file -->
<examples>
  <item id="ClassDefinition#Define">
    <sampleCode language="CSharp">
      public class CSharpClass()
      {
          // Members go here
      }
    </sampleCode>
    <sampleCode language="VisualBasic">
      Public Class VBClass
          ' Members go here
      End Class
    </sampleCode>
  </item>

  <item id="CreateInstance#Local">
    <sampleCode language="CSharp">
      CSharpClass x = new CSharpClass();
    </sampleCode>
    <sampleCode language="VisualBasic">
      Dim x As VBClass = New VBClass()
    </sampleCode>
  </item>

  <item id="CreateInstance#Static">
    <sampleCode language="CSharp">
      public static CSharpClass sharedInstance = new CSharpClass();
    </sampleCode>
    <sampleCode language="VisualBasic">
      Public Shared sharedInstance As VBClass = New VBClass()
    </sampleCode>
  </item>
</examples>

The file consists of a root examples node that contains one or more item nodes. The item element has an id attribute that gives each one a unique identifier. This is used as the inner text of the codeReference element in a topic to represent the snippet.

  Note

The ID value must consists of an example ID, a hash character (#), and a sample ID. The example and sample ID values are not case-sensitive. The example ID does not have to be unique. However, when combined with a sample ID, the entire value must be unique.

Each item must contain one or more sampleCode elements with a language attribute identifying the language of the sample code. The valid language IDs are noted above. The inner XML of the sampleCode element is the code snippet.

See Also