October 22, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Introducing Visual Studio 2005 IntelliSense Code Snippets

  • October 20, 2005
  • By Patrick Gallucci
  • Send Email »
  • More Articles »

The Elements of a Snippet

You now are ready to learn what it takes to create a snippet. You'll find the snippet schema at snippetformat.xsd. CodeSnippets is the root element of the schema. It can contain one or more CodeSnippet child elements, each of which contains all the data for the snippet:

<CodeSnippets>
   <CodeSnippet>...</CodeSnippet>
   <CodeSnippet>...</CodeSnippet>
</CodeSnippets>

The CodeSnippet element contains two child elements, as well as an optional format attribute. The format attribute is a mechanism that enables you to version the snippet:

<CodeSnippet Format="1.0.1">
   <Header>...</Header>
   <Snippet>... </Snippet>
</CodeSnippet>

The Header element contains general information about the snippet, and each code snippet can contain only one. The child elements of the header are Title, Author, Description, HelpUrl, SnippetTypes, Keyword, and Shortcut:

<Header>
   <Title>...</Title>
   <Author>...</Author>
   <Description>... </Description>
   <HelpUrl>... </HelpUrl>
   <SnippetTypes>...</SnippetTypes>
   <Keywords>... </Keywords>
   <Shortcut>... </Shortcut>
</Header>

The following is the Header from the ctor.snippet file in this example:

<Header>
   <Title>ctor</Title>
   <Shortcut>ctor</Shortcut>
   <Description>Code snippet for constructor</Description>
   <Author>Microsoft Corporation</Author>
   <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
   </SnippetTypes>
</Header>

Most of these elements are pretty self-explanatory. The HelpUrl is a pointer to a document that contains additional information about the snippet. SnippetTypes indicates to Visual Studio 2005 how to insert the code snippet into the code window:

<SnippetTypes>
   <SnippetType>... </SnippetType>
   <SnippetType>... </SnippetType>
<SnippetTypes>

If this value does not exist, code can be inserted into any file. The following are the valid SnippetType values:

  • SurroundsWith: Place the code snippet around a selected piece of code
  • Expansion: Insert the code snippet at the cursor
  • Refactoring: Use the code snippet during Visual C# refactoring (Refactoring cannot be used in custom code snippets.)

Because refactoring is not allowed in custom code snippets, that leaves SurroundsWith and Expansion. The main difference between the two is shown in the figures below. To use the SurroundsWith type, you must select the code or text block that you want to 'surround' with the snippet. Figures 8 and 9 show the before and after of the SurroundsWith type.

Figure 8: Before the SurroundsWith Type

After selecting the code, you then can right-click and select the snippet. This example selects the region snippet.

Figure 9: After the SurroundsWith Type

Selecting the #region snippet encases the code in #region and #endregion tags. Also note that the default substitution string MyRegion is highlighted. If you needed to make more replacements, you could simply tab to the next one. This feature speeds up the maintenance of the snippet. The expansion snippet, on the other hand, just inserts the code at the location of the cursor.

The Keywords elements allows one or more keyword elements to be defined so that Visual Studio and other providers can search and locate the snippet in a standard way:

<Keywords>
   <Keyword>... </Keyword>
   <Keyword>...</Keyword>
<Keywords>

And finally comes the Shortcut key, a unique feature that allows you to just type the shortcut into the code window and then press the tab key. This works great with expansion snippets.

You can now look at the Snippet element, which defines the code for the snippet:

<Snippet>
   <References>... </References>
   <Imports>... </Imports>
   <Declarations>... </Declarations>
   <Code>...</Code>
</Snippet>

The following is the snippet node from the example ctor.snippet:

<Snippet>
   <Declarations>
      <Literal Editable="false">
         <ID>classname</ID>
         <ToolTip>Class name</ToolTip>
         <Function>ClassName()</Function>
         <Default>ClassNamePlaceholder</Default>
      </Literal>
   </Declarations>
   <Code Language="csharp"><![CDATA[public $classname$ ()
   {
      $end$
   }]]>
   </Code>
</Snippet>

The References element is valid only in Visual Basic snippets. This optional element contains information about references to other libraries that may be used in the snippet. It has two child elements: Assembly is the location of the dll, and Url is a link to more information about the assembly:

<References>
   <Reference>
      <Assembly>System.Data.dll</Assembly>
      <Url>msdn.microsoft.com</Url>
   </Reference>
   <Reference>
      <Assembly>... </Assembly>
      <Url>... </Url>
   </Reference>
</References>

The Imports element contains information about the namespaces that will be used in the code snippet. It has the same effect as using the import inside your code. The only child element of the Imports element is the namespace:

<Imports>
   <Import>
      <Namespace>System</Namespace>
   </Import>
   <Import>
      <Namespace>System.Data</Namespace>
   </Import>
<Imports>

The Declarations element is where you define variables that act as replacements within the code element of the snippet. Literal and Object are the two kinds of replacements. Literal replacements take the form of know types, such as string, numbers, or dates. Object replacements are defined outside the snippet. The following is an example of both:

<Declarations>
   <Literal Editable="false">
      <ID>classname</ID>
      <ToolTip>Class name</ToolTip>
      <Function>ClassName()</Function>
      <Default>ClassNamePlaceholder</Default>
   </Literal>
   <Object>
      <ID>SqlConnection</ID>
      <Type>System.Data.SqlClient.SqlConnection</Type>
      <ToolTip>Replace with a connection object in your
               application.</ToolTip>
      <Default>dcConnection</Default>
   </Object>
</Declarations>

The attribute on the Literal element, Editable, determines whether or not you can edit the value of the literal once it is inserted. The default is True. The following are the other element descriptions:

  • Default (Required element): Specifies the literal's default value when you insert the code snippet. A Literal element must contain exactly one Default element.
  • Function (Optional element): Specifies a function to execute when the literal receives focus in Visual Studio. A Literal element may contain zero or one Function element.
  • ID (Required element): Specifies a unique identifier for the literal. A Literal element must contain exactly one ID element in a Literal element.
  • Tooltip (Optional element): Describes the expected value and usage of the literal. A Literal element may contain zero or one Tooltip elements.

The Function element has four functions available for pre-processing, and they can aid in returning some pretty interesting results. They are GenerateSwitchCases(EnumerationLiteral), ClassName(), SimpleTypeName(TypeName), and CallBase(Parameter). They each provide a unique result, which is worth exploring in greater detail. (My next article will dive deep into snippet functions.)

You now can look at the code element, which is where you will put your actual code, with the replacement variables to output your desired text. The code element has three attributes and no child elements. The attributes are kind, delimiter, and language. The delimiter, by default, is $. This character delimits literal and object variables in the snippet code text. The Language attribute, which is required, can be any of the following:

  • VB: Identifies a Visual Basic code snippet
  • CSharp: Identifies a Visual C# code snippet
  • VJSharp: Identifies a Visual J# code snippet
  • XML: Identifies an XML code snippet

This identifies the code snippet's language. The actual code element is text data that is surrounded by CDATA, so that it is taken as a literal string inside the element. The following is the code element from the ctor.snippet:

<Code Language="csharp"><![CDATA[public $classname$ ()
   {
      $end$
   }]]>
</Code>

So, if you look at the output of the snippet, you can pretty easily follow along with what the IDE is generating and why:

public Test()
{
}
  1. The attribute language specifies that it is C#.
  2. The code element begins with the CDATA escape, and then the word public.
  3. The replacement variable $classname$ is the result of the function ClassName, and then comes the two parentheses after the class name. As you can see, the placement is in the same location, based on the location of the cursor. This will also be affected by the options that are set in Visual Studio 2005 for C# formatting.
  4. The next line has the open bracket, followed by $end$ on the next line, and then the closing bracket. The $end$ is one of a set of predefined Literals variables. It is used to indicate the end of a line or statement. When the user presses ENTER to finish editing the code snippet fields, this variable determines where to move the caret (^).

Time to Make Your Own

Now, you can create a real simple snippet that you can use in your own code. Because all of your code should have documentation, create a file header snippet that you can tailor to your own needs. Then, you can extend it with another snippet for when you make changes to the file.

Figure 10 shows the output you want to get with your code snippet.

Figure 10: Desired Output from Your Code Snippet

I have defined four Literal variables that will replace strings in the above template. Classname will be the prefix to the file name. The Author will be replaced by the $author$ Literal variable. The $date$ variable will replace the create date and the history date, and the $company$ Literal will replace Developer.com. Figure 11 shows the final XML snippet file.



Click here for a larger image.

Figure 11: The Final XML Snippet File

You can use this new snippet with just a few clicks of the mouse. Start by loading the Snippet Manager (see Figure 12).

Figure 12: Load the Snippet Manager

Highlight "My Code Snippets" and click the Import button. Navigate to the location where you saved the header.snippet file and select open (see Figure 13).

Figure 13: Navigate to the header.snippet File and Select Open





Page 2 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel