Visual Studio Code Snippets—Creating Snippets Manually
| Visual C# Tutorials |
| Visual Studio .NET Tutorials |
| © 2005 Wiley Publishing, Inc. |
Creating Snippets Manually
Visual Studio 2005 does not ship with a code snippet creator or editor. During the development of the IDE, Microsoft determined that a third-party tool, simply called the Snippet Editor, performed this functionality well enough that there was no reason to include a built-in editor in the IDE. Later in this chapter you’ll learn how to use the Snippet Editor to create your own snippets, but it’s worth taking a look at how code snippets are structured by looking at the manual method of creating one.
Each code snippet is simply an individual XML file with a file extension of .snippet. The contents of the file are written in plain text and follow the standard XML structure of a hierarchy of tags containing attributes and values. The remainder of this section deals with the structure of the code snippet XML schema.
Every snippet file must start with the CodeSnippets tag, identifying the namespace that defines the code snippet schema. This is written in the following form:
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> </CodeSnippets>
Within these tags, each snippet is defined using the CodeSnippet tag, which will in turn contain the definition of the snippet itself:
<CodeSnippet Format="1.0.0"> </CodeSnippet>
Similar to HTML files, each code snippet has a header area and a body area, known as the Header and Snippet, respectively. The Header area can contain any combination of three separate tags, each defining a different attribute of the snippet:
-
Title: The name of the snippet -
Description: The description of the snippet -
Shortcut: A shortcut term used to insert the snippet automatically
-
The Header layout looks like the following:
<Header> <Title>The Name Of The Snippet</Title> <Description>The description of the snippet. (Optional)</Description> <Shortcut>The shortcut for the snippet. (Optional)</Shortcut> </Header>
Within the main Snippet tag you need to define the actual code to be inserted into the module. A Code tag is included with an attribute of Language (containing VB, C#, or J# depending on the language for which the snippet is intended). The actual code needs to be defined within a custom data tag with the format <![CDATA[ code ]]>. For example, the most basic Snippet tag looks like this:
<Snippet> <Code Language="VB"> <![CDATA[The Code Goes Here]]> </Code> </Snippet>
In addition to this code, you can define references and Imports statements in Visual Basic code snippets. Rather than insert the code at the selected entry point, Visual Studio will associate the references correctly as well as place the Imports statements at the top of the code module. These are placed at the top of the Snippet tag before the Code tag:
<Snippet> <References> <Reference> <Assembly>AssemblyName.dll</Assembly> </Reference> </References> <Imports> <Import> <Namespace>Namespace.Name</Namespace> </Import> </Imports> <Code Language="VB"> <![CDATA[The Code Goes Here]]> </Code> </Snippet>
As shown in the preceding example, code snippets can also have variable sections marked with special aliases so that the developer using the snippet knows which bits he or she should customize. To include such an alias, you first need to define it using a Literal tag. The Literal tag structure consists of the following:
-
ID: AnIDtag to uniquely identify the variable -
Type: The type of data to be inserted in this variable. This is optional. -
ToolTip: If defined, the user will see a tooltip containing this text. This is optional. -
Default: A default value to be placed in the automatically generated code. This is optional.
-
Following is a sample Literal tag:
<Literal> <ID>MyID</ID> <Type>String</Type> <ToolTip>The tooltip text</ToolTip> <Default>MyVarName</Default> </Literal>
Object variables can also be included in the same way as literals, but use the Object tab instead.
To use Object and Literal aliases in the code to be inserted, enclose the ID of the required variable with dollar signs ($) and include it at the intended location in the code. The following code includes references to a literal and an object called controlName and controlType, respectively:
<Code Language="VB"> <![CDATA[ Dim $controlName$ As $controlType$ ]]> </Code>
You can use the same variable multiple times in the code. When you change the value after the code is generated, the code snippet IntelliSense engine will automatically update any other occurrences of the Literal or Object with the new value.
The final code snippet structure appears like this:
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title>The Name Of The Snippet</Title> <Description>The description of the snippet. (Optional)</Description> <Shortcut>The shortcut for the snippet. (Optional)</Shortcut> </Header> <Snippet> <References> <Reference> <Assembly>AssemblyName.dll</Assembly> </Reference> </References> <Imports> <Import> <Namespace>Namespace.Name</Namespace> </Import> </Imports> <Literal> <ID>MyID</ID> <Type>String</Type> <ToolTip>The tooltip text</ToolTip> <Default>MyVarName</Default> </Literal> <Object> <ID>MyType</ID> <Type>Control</Type> <ToolTip>The tooltip text</ToolTip> <Default>Button</Default> </Object> <Code Language="VB"> <![CDATA[ Dim $myID$ As $MyType$ ]]> </Code> </Snippet> </CodeSnippet> </CodeSnippets>
The best way to illustrate how code snippets can make your life easier is to walk through the creation of a simple example, adding it to the code snippets library and then using it in code. This next exercise does just that, creating a snippet that in turn creates three subroutines, including a helper subroutine that is intended to show the developer using the snippet how to call the functionality properly:
1. Start Notepad and add the following stub of XML (you’re using Notepad to show that code snippets are simply XML written in plain text):
<?xml version="1.0"?> <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> </CodeSnippet> </CodeSnippets>
2. The first task is to define the header information. This is what’s used to define the name of the snippet in the snippet library, and it also enables you to define a shortcut and a brief description of what the code snippet does. In between the CodeSnippet tags, insert the XML to create a Header tag that contains Title, Description, and Shortcut tags, like so:
<?xml version="1.0"?> <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title>CreateAButtonSample</Title> <Description>This snippet adds code to create a button control and hook an event handler to it.</Description> <Shortcut>createAButton</Shortcut> </Header> </CodeSnippet> </CodeSnippets>
3. Now that the header information is present, you can begin creating the snippet itself. Start by defining the Snippet tag with a Declaration section and the main Code tag, setting attributes to VB (for Visual Basic) and method decl for the Kind so that Visual Studio knows that the scope of this snippet is a member declaration:
<?xml version="1.0"?> <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title>CreateAButtonSample</Title> <Description>This snippet adds code to create a button control and hook an event handler to it.</Description> <Shortcut>createAButton</Shortcut> </Header> <Snippet> <Declarations> </Declarations> <Code Language="VB" Kind="method decl"> </Code> </Snippet> </CodeSnippet> </CodeSnippets>
4. Define the Literal tags for the Name and Text properties that will be used to customize the button’s creation. These properties will be used in the Helper subroutine so you know what you need to change to make the other subroutines work. Literal tags need an ID to identify the alias used in the code snippet; and they can have a default value as well as an explanatory tooltip. You’ll use all three tags to create your Literal tags, which should be included in the Declarations section:
<Declarations> <Literal> <ID>controlName</ID> <ToolTip>The name of the button.</ToolTip> <Default>"MyButton"</Default> </Literal> <Literal> <ID>controlText</ID> <ToolTip>The Text property of the button.</ToolTip> <Default>"Click Me!"</Default> </Literal> </Declarations>
5. As mentioned earlier, the code to be inserted when this snippet is activated needs to be inserted in a custom data tag in the following form:
<![CDATA[code goes here]]>
Type the following code in between the opening and closing Code tags. It defines the three subroutines and is straight Visual Basic code other than the use of the aliased Literal tags. Note that these are enclosed by dollar signs ($) to tell Visual Studio that they are aliases—to use the Literal controlName, the alias $controlName$ is used:
<Code Language="VB" Kind="method decl"> <![CDATA[Private Sub CreateButtonHelper CreateAButton($controlName$, $controlText$, Me) End Sub Private Sub CreateAButton(ButtonName As String, ButtonText As String, _ Owner As Form) Dim MyButton As New Button MyButton.Name = ButtonName MyButton.Text = ButtonName Owner.Controls.Add(MyButton) MyButton.Top = 0 MyButton.Left = 0 MyButton.Text = ButtonText MyButton.Visible = True AddHandler MyButton.Click, AddressOf ButtonClickHandler End Sub Private Sub ButtonClickHandler(ByVal sender As System.Object, _ ByVal e As System.EventArgs) MessageBox.Show("The " & sender.Name & " button was clicked") End Sub ]]> </Code>
6. Save the file as CreateAButton.snippet somewhere where you can locate it easily and switch to Visual Studio 2005. Bring up the code snippets library with the keyboard shortcut chord Ctrl+K, Ctrl+B. Once the library is displayed, click the Import button and browse to the snippet file you just saved.
7. Choose a suitable location for the snippet—the My Snippets group is the usual place for custom-built snippets—and click Finish. Click OK to close the library. Your snippet is now saved and stored in Visual Studio 2005, ready for use.
8. To test that the code snippet was properly defined and installed, create a new Windows Forms application and switch to the Code view of Form1. Display the Code Snippet IntelliSense dialog by using the keyboard chord Ctrl+K, Ctrl+X, and then browse to the CreateAButton snippet you just imported and double-click it. Visual Studio should insert the Visual Basic code to define three subroutines, with two variables highlighted.
9. Add the following code to the bottom of the Form1 class definition:
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load CreateButtonHelper() End Sub
This will execute the CreateButtonHelper subroutine when the form is first loaded, which in turn will call the other subroutines generated by the code snippet and create a button with default text and a default behavior. Run the application and click the button that is created, and you should get similar results to those shown in Figure 19-6.
While this sample shows the creation of a simple code snippet, you can use the same technique to create complex snippets that include Imports statements, code definitions, and markup for sections within the code snippet text to be replaced by the developer using it.
|


