Code Snippets

Developers are connoisseurs of code and tend to collect useful code in a variety of places. While other people collect coins, books, or PEZ dispensers, developers collect code snippets. Why? Developers do not like typing. There is some irony in that, considering how much typing is involved in programming. Still, the principle is unshakable: If you want to improve developers’ productivity, reduce the amount they have to type. Code snippets provide an organized method of managing fragments of code, which then can be reinserted when needed. Developers traditionally cut and paste code to prevent typing the same code over and over. However, this has some limitations, including limited persistence of the Clipboard. Code snippets reduce the number of typos and resulting compiler errors. Code reuse is another reason why developers collect code. Even applications perceived as unique are largely composed of small and modular code snippets. Some of these code fragments, such as loops, classes, and exception handling, are common to every program.

Code snippets are capsules of reusable source code: essentially, aliases for pieces of code. Use a code snippet to insert the aliased code into the source file as needed.

There are multiple sources for snippets. Visual Studio 2008 has a set of default snippets for common tasks, such as the for, try, and while snippets. Snippets also are available online and can be downloaded. Finally, developers can create custom snippets.

There are three kinds of snippets, described as follows:

  • Expansion. Inserts code at the cursor

  • Surround With. Envelops selected code

  • Refactoring. Used with refactoring

A single snippet might fit into more than one category. For example, while is both an Expansion snippet and a Surround With snippet.

Insert a Code Snippet

Use the following techniques to select and insert code snippets:

  • Insert a code snippet using IntelliSense. This is the most convenient way to add a snippet. Code snippets appear in the completion list as a torn page. To insert a code snippet, either enter the complete name at the prompt (IntelliSense automatically completes the name of the category and the snippet as you begin to type it) or double-click the snippet in the completion list.

  • Insert a code snippet from a context menu in the Code Editor window. Choose the Insert Snippet menu command. This is called the code snippet picker. You are presented folders that group related snippets together. Open the proper category and then select the correct snippet or enter the name of the snippet at the prompt. (IntelliSense automatically completes the name of the category and the snippet as you begin to type it.)

  • Hitting Ctrl+K and then Ctrl+X is the keyboard shortcut for the Insert Snippet menu command. At the prompt, enter the name of the snippet. (IntelliSense automatically completes the name of the category and the snippet as you begin to type it.)

  • Insert a code snippet using Auto IntelliSense. Position the cursor where the snippet should be inserted, type the name of the snippet, and then press Tab twice. For example, type for and then press Tab twice. The for snippet will be inserted. Of course, you should do this where a for loop is appropriate

Some code snippets are templates and contain editable fields. After inserting the code snippet, a developer customizes the template by assigning values to each field. The first field is selected automatically when the code snippet is inserted. Other fields in the code template are highlighted in color. There can be multiple instances of a field in the same code snippet. For example, there are several instances of the i field in the for snippet. The first instance of a field is highlighted in color and editable. Remaining instances are notated with a dotted border. When entering data, pressing Tab moves you to the next field, whereas pressing Shift-Tab moves you to the previous file. You can select a field by double-clicking it. Fields with tool tips display the tip when the field is selected. Figure 4-30 shows the for snippet. It has the ‘i’ and length fields. Figure 4-31 shows the snippet with the fields populated with values.

The for snippet

Figure 4-30. The for snippet

A customized code snippet

Figure 4-31. A customized code snippet

When using a Surround With template, select the target code first and then add the snippet. The snippet will surround the code. For example, the following code increments a counter:

int count = 0;
Console.WriteLine(++count);
if (count == 10)
{
    break;
}

The following code is the result of selecting the previous code and adding the code snippet for the while keyword:

while (true)
{
    int count = 0;
    Console.WriteLine(++count);
    if (count == 10)
    {
        break;
    }
}

Default Snippets

Visual Studio 2008 has default snippets for routine tasks. The default snippets include a mixture of Expansion and Surround With code snippets. Default snippets appear in the IntelliSense completion list and the code snippet picker. Table 4-2 lists some of the default code snippets.

Table 4-2. Default code snippets

Code snippet

Description

#if

Surrounds code with the #if and #endif directives

#region

Surrounds code with the #region and #endregion directives

~

Inserts a destructor

attribute

Inserts a class definition for a custom attribute, which is derived from System.Attribute

checked

Surrounds code with a checked block

class

Inserts a class definition

ctor

Inserts a constructor

cw

Inserts a Console.WriteLine statement

do

Surrounds code with a do while block

else

Inserts an else block

enum

Inserts an enum type

equals

Overrides the Equals method inherited from the System.Object type

exception

Inserts a class definition for an application exception, which is derived from System.Exception

for

Surrounds code with a for loop

foreach

Surrounds code with a foreach loop

forr

Surrounds code with a for loop that automatically decrements the loop variable

if

Surrounds code with an if block

indexer

Inserts an indexer function

interface

Inserts an interface definition

iterator

Inserts an iterator

interindex

Inserts a named iterator and indexer

invoke

Inserts an event followed by an invocation of the event

lock

Surrounds code with a lock block

mbox

Inserts the MessageBox.Show statement

namespace

Surrounds code with a namespace

prop

Inserts a property and backing field

propg

Inserts a read-only property. Read-only properties have only a get method

sim

Inserts an entry point (Main) method that is static and returns an integer

struct

Inserts the definition of a struct

svm

Inserts an entry point (Main) method that is static and returns void

switch

Inserts a switch statement

try

Surrounds code with a try-catch block

tryf

Surrounds code with a try-finally block

unchecked

Surrounds code with an unchecked block

unsafe

Surrounds code with an unsafe block

using

Surrounds code with a using block

while

Surrounds code with a while loop

Code Snippets Manager

Use the Code Snippets Manager (shown in Figure 4-32) to manage snippets, including adding, removing, importing, and searching for snippets.

The Code Snippets Manager

Figure 4-32. The Code Snippets Manager

The Code Snippets Manager can be opened from the Tools menu. The folders shown in the Code Snippets Manager are snippet directories. Each directory contains a group of related snippets. Open a directory and possible subdirectories to view individual snippets. For each snippet, the following information is provided:

  • Description of the code snippet

  • The alias or shortcut of the code snippet

  • The snippet type

  • The author of the snippet

The Add button in the Code Snippets Manager adds a directory to the list of code snippet directories. A code snippets directory contains code snippet files, which are Extensible Markup Language (XML) files with the .snippet suffix. The Remove button removes a snippet directory from the list. The Import button imports a code snippet file. Use the Search Online button to browse for code snippets online. This button opens a general search window, in which developers can search for code snippets. When you find the code snippet you’re searching for, you can download the file.

Be aware, however, that downloading snippets you find online is a security risk. The XML of the snippet poses a potential security problem. The snippet might hide malicious scripts. Also, code snippets can silently add references, which then makes it possible for malicious calls to be made to functions in the reference. Be careful when downloading code snippets with database access, code-access security, role-base security, or validation code. As a best practice, carefully review the source code of code snippets that you download before using them in an application.

Creating Snippets

You can create custom code snippets to encapsulate reusable code not found online or in a default snippet, which allows you to maintain private libraries of reusable code. Different industries already may have specialized code snippets. For example, a developer of medical software could use code snippets designed for medical applications, and a developer of legal software could benefit from code snippets designed specifically for legal applications. The availability of snippet libraries will expand in the future.

Custom code snippets are defined with XML files that have the .snippet extension. Microsoft publishes an XML schema for code snippets. Once the schema is declared, Visual Studio 2008 offers IntelliSense on the XML elements and attributes, which helps considerably in creating properly formed code snippet files. You can group custom snippets in directories. Add these directories to the Code Snippets Manager to make using customized snippets more convenient.

The XML schema for code snippets defines the structure of a code snippet file. For a complete explanation of the schema, visit the Code Snippet Schema Reference at http://msdn2.microsoft.com/en-us/library/ms171418(en-us,vs.80).aspx. Some parts of the schema are discussed next.

CodeSnippets and CodeSnippet Elements

The CodeSnippets element is the root element of the code snippet file. The xlmns attribute names the code snippet schema, as follows:

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">

A code snippet is described inside the CodeSnippet elements, as follows:

<CodeSnippet>
  <!-- Insert code snippet here. -->
</CodeSnippet>

Header Element

The Header element has child elements, which provide the basic information about the code snippet. The title, author, description, shortcut, and snippet type are some of the details that can be provided. The title is the name of the code snippet as it appears in the code snippet picker, while the shortcut name appears in the IntelliSense completion list. The description of the snippet found in the Code Snippets Manager is read from this element.

Here is the Header element for an example snippet for the StringBuilder type:

<Header>
  <Title>StringBuilder</Title>
  <Shortcut>sb</Shortcut>
  <Description>Creates a new String Builder</Description>
  <Author>Donis Marshall</Author>
</Header>

Snippet, References, and Imports Elements

The Snippet element encapsulates the actual code of the code snippet. References and Imports are child elements of the Snippet element. The References element identifies references required for the code snippet. Within the References element, there are Reference child elements for each individual reference. The Imports element names implicit namespaces. Within the Imports element, there are Import child elements that identify each namespace to import. Each namespace is identified within Namespace elements. Importing a namespace allows implicit access of members in a namespace without explicitly naming the namespace. An Import element generates a using <namespace> statement.

Here is an example of the References and Import elements. The System.Text namespace contains the StringBuilder type:

<Snippet>
  <References>
    <Reference>
      <Assembly>System.Text.Dll</Assembly>
    </Reference>
  </References>
  <Imports>
    <Import>
      <Namespace>System.Text</Namespace>
    </Import>
  </Imports>

Declarations, Literal, and Object Elements

The Declarations element describes the fields used in the code snippet. It is a child element of the Snippet element and has Literal and Object child elements. The Literal element declares a literal field, which is a field that is fully contained in the code snippet. This would include string and numeric literals. The Object element also declares a field, but the field is defined outside the snippet. This element usually describes a type.

The Literal and Object elements can contain ID, Default, Tooltip, Type, and Function child elements, which are as follows:

  • The ID element is the name of the field.

  • The Default element is the default value of the field.

  • The Tooltip element is the tool tip of the field.

  • The Type element sets the type of the field.

  • The Function element is a function name. This is a function to call whenever the field receives the focus in Visual Studio.

Here is the Declarations element of the StringBuilder code snippet:

<Declarations>
  <Literal>
    <ID>Name</ID>
    <Default>mytext</Default>
    <ToolTip>Name of new StringBuilder</ToolTip>
  </Literal>
  <Literal>
    <ID>Size</ID>
    <ToolTip>Capacity of String</ToolTip>
  </Literal>
</Declarations>

Code and <![CDATA ]> Elements

The Code element contains individual lines of code. It also selects the language of the code snippet. Code is a child element of the Snippet element. The target language is set in the Language attribute. Valid languages are CSharp, VB, VJSHARP, and XML.

Each line of code is placed in a <![CDATA]> element. The code must be written in the syntax of the chosen language.

Here is the CDATA syntax:

<![CDATA[snippetcode]]>

In snippet code, fields are bounded with dollar signs ($<field>$). This is the snippet code for the StringBuilder snippet:

<Code Language="CSharp">
  <![CDATA[StringBuilder $Name$=]]>
  <![CDATA[    new StringBuilder($Size$);]]>
</Code>

String Builder Code Snippet

The following code is the complete listing of the sample code snippet, which creates a new StringBuilder type. The StringBuilder type is found in the System.Text.Dll library and the System.Text namespace. Fields are defined for the name and size of the StringBuilder type.

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>StringBuilder</Title>
      <Shortcut>sb</Shortcut>
      <Description>Creates a new String Builder</Description>
      <Author>Donis Marshall</Author>
    </Header>
    <Snippet>
      <References>
        <Reference>
          <Assembly>System.Text.Dll</Assembly>
        </Reference>
      </References>
      <Imports>
        <Import>
          <Namespace>System.Text</Namespace>
        </Import>
      </Imports>
      <Declarations>
        <Literal>
          <ID>Name</ID>
          <Default>mytext</Default>
          <ToolTip>Name of new StringBuilder</ToolTip>
        </Literal>
        <Literal>
          <ID>Size</ID>
          <ToolTip>Capacity of String</ToolTip>
        </Literal>
      </Declarations>
      <Code Language="CSharp">
        <![CDATA[StringBuilder $Name$=]]>
        <![CDATA[new StringBuilder($Size$);]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Code Snippet Creation Example

This section provides an example of creating a code snippet. Before creating a snippet, it is best to write and test any snippet code in a conventional application. Convert the code into a code snippet only after a successful test has been performed. You should place custom snippets in a dedicated directory. Make sure the directory is identified as a directory with code snippets by adding the directory in the Code Snippets Manager. For this example, name the custom directory "snippets."

The example in this section creates a code snippet that reflects the methods of a type. The following code tests the proposed snippet:

// Snippet starts
Type t = typeof(Object);
string typename = t.Name;
string typenamespace = t.Namespace;
MethodInfo[] methods = t.GetMethods();
// Snippet ends
Console.WriteLine("Type Name:" + typename);
Console.WriteLine("Namespace Name:" + typenamespace);
foreach (MethodInfo method in methods)
{
    Console.WriteLine(method.Name);
}

Create a snippet from the preceding code using the following procedure:

  1. Create an XML file in Visual Studio. The filename of the code snippet is reflectmethod.snippet.

  2. All snippet files begin with the CodeSnippets, CodeSnippet, and Header elements, which name the file schema and describe the basic attributes of the code snippet. This is the basic element for our snippet:

    <?xml version="1.0" encoding="utf-8"?>
    <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
        <Header>
          <Title>ReflectMethod</Title>
          <Shortcut>rm</Shortcut>
          <Description>Reflects methods of a type.</Description>
          <Author>Donis Marshall</Author>
        </Header>
      </CodeSnippet>
    </CodeSnippets>
  3. Performing reflection naturally requires the Reflection namespace. Import the System.Reflection namespace with an Import element, which is contained within the Imports element. The System.Reflection namespace is declared in System.dll. System.dll is implicitly available to managed code, so a Reference element is not needed for this snippet:

    <Snippet>
      <Imports>
        <Import>
          <Namespace>System.Reflection</Namespace>
        </Import>
      </Imports>
    </Snippet>
  4. The code snippet has five fields, which are the type, type instance, namespace, and a MethodInfo array. The type instance is an object field. The other fields are literals and contained within the code snippet. Defaults for the fields are gleaned from the code used to test the code snippet. Fields are defined within the Declarations element with Literal and Object elements:

    <Declarations>
      <Literal>
        <ID>Instance</ID>
        <Default>t</Default>
        <ToolTip>Name of instance.</ToolTip>
      </Literal>
      <Literal>
        <ID>TypeName</ID>
        <Default>typename</Default>
        <ToolTip>Name of type.</ToolTip>
      </Literal>
      <Literal>
        <ID>TypeNamespace</ID>
        <Default>typenamespace</Default>
        <ToolTip>Namespace of type.</ToolTip>
      </Literal>
      <Literal>
        <ID>Methods</ID>
        <Default>Methods</Default>
        <ToolTip>Type methods</ToolTip>
      </Literal>
      <Object>
        <ID>Type</ID>
        <Default>Object</Default>
        <ToolTip>object type</ToolTip>
        <Type>System.Object</Type>
      </Object>
    </Declarations>
  5. Paste the tested code for the snippet into separate <![CDATA]> elements. Then place the <![CDATA]> elements within the Code element. Add extra line feeds to separate lines of source code. After entering the code, substitute the field names into the code:

    <Code Language="CSharp">
      <![CDATA[Type $Instance$ = typeof($Type$);
      ]]>
      <![CDATA[string $TypeName$ = $Instance$.Name;
      ]]>
      <![CDATA[string $TypeNamespace$ = $Instance$.Namespace;
      ]]>
      <![CDATA[MethodInfo [] $Methods$ = $Instance$.GetMethods();
      ]]>
    </Code>
  6. Save the file for the code snippet in the directory reserved for custom code snippets.

  7. Test the snippet in Visual Studio 2008. To do so, open a source file and insert the code snippet using the code snippet picker. Figure 4-33 shows both the snippet in the code snippet picker and the snippet after it has been inserted.

    The Reflect Method snippet

    Figure 4-33. The Reflect Method snippet

Copy and Paste

Of course, copying and pasting code remains available as an alternative to using snippets. One of the main disadvantages of this approach, however, is that the Clipboard is a shared resource in Windows. A second problem is that Clipboard data is not retained across logon sessions. Visual Studio resolves these shortcomings by allowing you to copy source code directly to the toolbox, which then preserves the code on the toolbox for future placement. Code placed in the toolbox is preserved between Visual Studio sessions as well as between logon sessions. This technique is not as elegant as using a snippet, but sometimes it is quicker and more convenient, especially when a custom snippet is required. Unlike the Clipboard, the toolbox is not a shared resource and is available only to Visual Studio.

There are two methods of placing code on the toolbox. The first is to select the code, copy it to the Clipboard, click on the toolbox, and paste the code. The second way is simply to drag the selected code onto the toolbox. A button is then created on the toolbox for the code. Multiple items can be added to the toolbox. After code is placed on the Clipboard, moving the mouse over a code button in the toolbox displays the saved code. Click the code button to insert the code at the cursor. As a best practice, create a separate tab on the toolbox to group code buttons together, as intermingling code with nonrelated buttons can be distracting. To add a tab, right-click the toolbox, choose Add Tab from the context menu, and then enter a name for the new tab. A toolbox populated with code buttons is shown in Figure 4-34. A tab called Code was added to the toolbox for grouping these buttons.

A toolbox with code buttons

Figure 4-34. A toolbox with code buttons

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.251.56