of code to make it more efficient.
Although refactoring tools are implemented for C# in Visual Studio, unfortunately they
haven’t been implemented for VB. In order to fill this hole in functionality in previous
versions of Visual Studio, Microsoft licensed the VB version of Refactor! from Developer
Express. For Visual Studio 2010, CodeRush Xpress (also from Developer Express) takes
over from Refactor! to implement refactoring for VB. Even though Microsoft has licensed
CodeRush Xpress, it still needs to be downloaded and installed separately from Visual Studio
138 .
chaPter 8 code SnippeTS And reFAcToring
(as an add-in). You can download it from the VB developer center at http://msdn.microsoft.
com/vbasic/; follow the links to Downloads, then Tools and Utilities.
CodeRush Xpress provides a range of additional refactoring support that complements the
integrated support available for C# developers. However, this chapter’s discussion is restricted to
the built-in refactoring support provided within Visual Studio 2010 (for C# developers) and the
corresponding action in CodeRush Xpress (for VB developers).
code sniPPets reVealed
Code snippets have been around in a variety of forms for a long time but generally required third - party
add - ins for languages such as VB 6 and the early versions of Visual Studio. Visual Studio 2010 includes
extensive code snippet support that allows a block of code along with predefined replacement variables
to be inserted into a file, making it easy to customize the inserted code to suit the task at hand.
storing code blocks in the toolbox
Before looking at code snippets, this section looks at the simplest means Visual Studio provides to
insert predefined blocks of text into a file. Much like it can hold controls to be inserted on a form,
the Toolbox can also hold blocks of text (such as code) that can be inserted into a file. To add a
block of code (or other text) to the Toolbox, simply select the text in the editor and drag it over
onto the Toolbox. This creates an entry for it
in the Toolbox with the first line of the code
as its name. You can rename, arrange, and
group these entries like any other element in
the Toolbox. To insert the code block you
simply drag it from the Toolbox to the desired
location in a file as shown in Figure 8-1, or
simply double-click the Toolbox entry to
insert it at the current cursor position in the
active file. fiGure 8-1
Many presenters use this simple feature to quickly insert large code blocks when
writing code live in presentations.
This is the simplest form of “code snippet” behavior in Visual Studio 2010, but with its simplicity
comes limited functionality, such as the lack of ability to modify and share them. Nevertheless, this
method of keeping small sections of code can prove useful in some scenarios to maintain a series of
code blocks for short-term use.
code snippets
Now we come to a much more useful way to insert blocks of code into a file: code snippets. Code
snippets are defined in individual XML files, each containing a block of code that programmers
Code snippets revealed .
139
may want to insert into their code, and may also include replaceable parameters making it easy to
then customize the inserted snippet for the current task. They are integrated with Visual Studio’s
IntelliSense, making them very easy to find and insert into a code file.
VB code snippets also have the ability to add assembly references and insert
Imports statements.
Visual Studio 2010 ships with many predefined code snippets for the two main languages, VB
and C#, along with snippets for JavaScript, HTML, and XML. These snippets are arranged
hierarchically in a logical fashion so that you can easily locate the appropriate snippet. Rather than
locate the snippet in the Toolbox, you can use menu commands or keyboard shortcuts to bring up
the main list of groups.
In addition to the predefined code snippets, you can create your own code snippets and store them
in this code snippet library. Because each snippet is stored in a special XML file, you can even share
them with other developers.
Following are three scopes under which a snippet can be inserted:
.
Class Declaration: The snippet actually generates an entire class.
.
Member Declaration: This snippet scope includes code that defines members, such as
methods, properties, and event handler routines. This means it should be inserted outside
an existing member.
.
Member Body: This scope is for snippets that are inserted into an already defined member,
such as a method.
using snippets in c#
Insert Snippet is a special kind of IntelliSense that appears inline in the code editor. Initially, it
displays the words “Insert Snippet” along with a drop-down list of code snippet groups from which
to choose. Once you select the group that contains the snippet you require (using up and down
arrows, followed by the Tab key), it shows you a list of snippets, and you can simply double-click
the one you need (alternatively, pressing Tab or Enter with the required snippet selected has the
same effect).
To insert a code snippet in C#, simply locate the position where you want to insert the generated
code, and then the easiest way to bring up the Insert Snippet list is to use the keyboard shortcut
combination of Ctrl+K, Ctrl+X. You have two additional methods to start the Insert Snippet
process. The first is to right-click at the intended insertion point in the code window and select
Insert Snippet from the context menu that is displayed. The other option is to use the Edit .
IntelliSense . Insert Snippet menu command.
At this point, Visual Studio brings up the Insert Snippet list, as Figure 8-2 demonstrates. As you
scroll through the list and hover the mouse pointer over each entry, a tooltip is displayed to indicate
what the snippet does and a shortcut that can be used to insert it.
140 .
chaPter 8 code SnippeTS And reFAcToring
fiGure 8-2
To use the shortcut for a code snippet, simply type it into the code editor (note that it appears in the
IntelliSense list) and press the Tab key twice to insert the snippet at that position.
Figure 8-3 displays the result of selecting the Automatically
Implemented Property snippet. To help you modify the code to
your own requirements, the sections you would normally need
to change (the replacement variables) are highlighted, with the first
one conveniently selected.
fiGure 8-3
When you are changing the variable sections of the generated
code snippet, Visual Studio 2010 helps you even further. Pressing the Tab key moves to the next
highlighted value, ready for you to override the value with your own. Shift+Tab navigates backward,
so you have an easy way of accessing the sections of code that need changing without needing to
manually select the next piece to modify. Some code snippets use the same variable for multiple
pieces of the code snippet logic. This means changing the value in one place results in it changing in
all other instances.
To hide the highlighting of these snippet variables once you are done you can simply continue
coding, or press either Enter or Esc.
using snippets in Vb
Code snippets in VB have additional features over what is available in C#, namely the ability to
automatically add references to assemblies in the project, and insert Imports statements into a file
that the code needs in order to compile.
To use a code snippet you should first locate where you want the generated code to be placed in the
program listing and position the cursor at that point. You don’t have to worry about the associated
references and Imports statements; they will be placed in the correct location. Then, as with C#
snippets, you can use one of the following methods to display the Insert Snippet list:
.
Use the keyboard chord Ctrl+K, Ctrl+X
.
Right-click and choose Insert Snippet from the context menu
.
Run the Edit . IntelliSense . Insert Snippet menu command
VB also has an additional way to show the Insert Snippet List: simply type ? and press Tab.
Code snippets revealed .
141
Let’s navigate through the hierarchy and insert a snippet named Draw a Pie Chart. Figure 8-4
demonstrates how you might navigate through the hierarchy to find the snippet and insert it into
your project.
fiGure 8-4
You might have noticed in Figure 8-4 that the tooltip text includes the words “Shortcut: drawPie.”
This text indicates that the selected code snippet has a text shortcut that you can use to automatically
invoke the code snippet behavior without navigating the code snippet hierarchy. As with C# all you
need to do is type the shortcut into the code editor and press the Tab key once for it to be inserted. In
VB the shortcut isn’t case-sensitive, so this example can be generated by typing the term “drawpie”
and pressing Tab. Note that shortcuts don’t appear in IntelliSense in VB as they do in C#.
After inserting the code snippet, if it contains replacement variables you can enter their values
then navigate between these by pressing Tab as described for C#. To hide the highlighting of these
snippet variables once you are done, you can simply continue coding, or right-click and select Hide
Snippet Highlighting. If you want to highlight all the replacement variables of the code snippets
inserted since the file was opened, right-click and select Show Snippet Highlighting.
surround with snippet
The last refactoring action, available in C# (and VB with CodeRush Xpress), is the capability to
surround an existing block of code with a code snippet. For example, to wrap an existing block
with a conditional try-catch block, right-
click and select Surround With, or select
the block of code and press Ctrl+K, Ctrl+S.
This displays the Surround With dialog that
contains a list of surrounding snippets
that are available to wrap the selected line fiGure 8-5
of code, as shown in Figure 8-5.
Selecting the try snippet results in the following code:
Vb
Public Sub MethodXYZ(ByVal name As String)
Try
MessageBox.Show(name)
142 .
chaPter 8 code SnippeTS And reFAcToring
Catch ex As Exception
Throw
End Try
End Sub
c#
public void MethodXYZ(string name)
{
try
{
MessageBox.Show(name);
}
catch (Exception)
{
throw;
}
}
code snippets Manager
The Code Snippets Manager is the central library for the code snippets known to Visual Studio
2010. You can access it via the Tools . Code Snippet Manager menu command or the keyboard
shortcut chord Ctrl+K, Ctrl+B.
When it is initially displayed, the Code Snippets Manager shows the HTML snippets available,
but you can change it to display the snippets for the language you are using via the Language
drop-down list. Figure 8-6 shows how it looks when you’re editing a C# project. The hierarchical
folder structure follows the same set of folders on the PC by default, but as you add snippet files
from different locations and insert them into the different groups, the new snippets slip into the
appropriate folders.
If you have an entire folder of snippets
to add to the library, such as when you
have a corporate setup and need to import
the company-developed snippets, you use the
Add button. This brings up a dialog that you
use to browse to the required folder. Folders
added in this fashion appear at the root level
of the tree — on the same level as the main
groups of default snippets. However, you can
add a folder that contains subfolders, which
will be added as child nodes in the tree.
Removing a folder is just as easy — in fact,
it’s dangerously easy. Select the root node that
you want to remove and click the Remove
button. Instantly, the node and all child nodes
and snippets are removed from the Snippets Manager without a confirmation window. If you do
this by accident you are best off clicking the Cancel button and opening the dialog again. If you’ve
made changes you don’t want to lose, you can add them back by following the steps explained in
the previous walkthrough, but it can be frustrating trying to locate a default snippet folder that you
inadvertently deleted from the list.
fiGure 8-6
Code snippets revealed .
143
The location for the code snippets that are installed with Visual Studio 2010 is deep within the
installation folder. By default, the code snippet library when running on 32-bit Windows is installed
in %programfiles%\Microsoft Visual Studio 10.0\VB\Snippets\1033 for VB snippets and
%programfiles%\Microsoft Visual Studio 10.0\VC#\Snippets\1033 for C# (for 64-bit
Windows, replace %programfiles% with %programfiles(x86)%). Individual snippet files can be
imported into the library using the Import button. The advantage of this method over the Add button
is that you get the opportunity to specify the location of each snippet in the library structure.
creating snippets
Visual Studio 2010 does not ship with a code snippet creator or editor. However, Bill McCarthy’s
Snippet Editor allows you to create, modify, and manage your snippets (including support for VB, C#,
HTML, JavaScript, and XML snippets). Starting as an internal Microsoft project, the Snippet Editor is
now an open source project hosted on CodePlex where Bill fixed the outstanding issues and proceeded
to add functionality. With the help of other MVPs it is now also available in a number of different
languages. You can download the snippet editor from http://snippeteditor.codeplex.com.
Creating code snippets by manually editing the .snippet XML files can be a tedious and error-
prone process, so the Snippet Editor makes it a much more pleasant experience. When you start the
Snippet Editor you will notice a drop-down list in the top left-hand corner — make sure you select
Visual Studio 2010. Below this is a tree containing all the snippets known to Visual Studio 2010. By
expanding a node you’ll see a set of folders similar to those in the code snippet library (see Figure 8-7).