Printer Friendly Version      Send     
Click to Rate and Give Feedback
Related Articles

Ken Getz shows how the CollectionChanged event lets you reflect changes to your underlying data source in your bound data controls.

Ken Getz

MSDN Magazine December 2008

...

Read more!

This month Dino Esposito explains how the browser interoperability layer in Silverlight addresses a number of your Silverlight / Web page interaction needs.

Dino Esposito

MSDN Magazine November 2008

...

Read more!

Our security experts present 10 vulnerable pieces of code. Your mission is to find the holes (a.k.a. bad security practices) in the code.

Michael Howard and Bryan Sullivan

MSDN Magazine November 2008

...

Read more!

Choosing the right design pattern for your ASP.NET Web application can help you achieve the separation of concerns between your presentation layer and the layers beneath it.

Dino Esposito

MSDN Magazine December 2008

...

Read more!

Matt Milner takes a look at some of the challenges and techniques related to testing Windows Workflow Foundation activities, workflows, and associated components.

Matt Milner

MSDN Magazine November 2008

...

Read more!

Popular Articles

Jason Clark

MSDN Magazine July 2003

...

Read more!

James Avery does it again with his popular list of developer tools. This time he covers the best Visual Studio add-ins available today that you can download for free.

James Avery

MSDN Magazine December 2005

...

Read more!

The MVP pattern helps you separate your logic and keep your UI layer free of clutter. This month learn how.

Jean-Paul Boodhoo

MSDN Magazine August 2006

...

Read more!

C# allows developers to embed XML comments into their source files-a useful facility, especially when more than one programmer is working on the same code. The C# parser can expand these XML tags to provide additional information and export them to an external document for further processing. This article shows how to use XML comments and explains the relevant tags. The author demonstrates how to set up your project to export your XML comments into convenient documentation for the benefit of other developers. He also shows how to use comments ...

Read more!

Learn how to automate custom SharePoint application deployments, use the SharePoint API, and avoid the hassle of custom site definitions.

E. Wilansky, P. Olszewski, and R. Sneddon

MSDN Magazine May 2008

...

Read more!

Our Blog

Silverlight provides a browser interoperability layer that allows managed code to access the document object model (DOM) of the underlying page. At the same time, JavaScript code running in the page can access the XAML content of the plug-in and even make modifications.

In the November 2008 issue of MSDN Magazine, Dino Esposito discusses the ...

Read more!

Windows Presentation Foundation (WPF) adds functionality to the Microsoft .NET Framework so that you actually can reliably keep bound controls synchronized with their data sources.

In the December 2008 issue of MSDN Magazine, Ken Getz demonstrates how to use the ObservableCollection class provided by WPF to keep bound controls in ...

Read more!

Windows Workflow Foundation (WF) imposes some restrictions on the developer authoring programs that target it. But in return WF offers a powerful, flexible, and extensible set of runtime services such as support for long-running code.

In the December 2008 issue of MSDN Magazine, Josh Lane provides some best practices to consider ...

Read more!

It’s helpful to think about secure design from a more holistic perspective by using threat models to drive your security engineering process.

In the November 2008 issue of MSDN Magazine, Michael Howard proposes using the threat model to help drive other SDL security requirements, primarily code review priority, fuzz testing priority, ...

Read more!

We're currently in the process of stepping back and taking a critical look at our Web site to see how you all are using it - and how we can redesign parts of it (big or small) to make that experience better.  We are continuously receiving your feedback on existing frustrations and we are working hard to remedy those (as a general fyi, most of the frustrations have to do with navigation).  However, in order to get a sense of whether we need to look at some of the more fundamental ...

Read more!

Advanced Basics
IntelliSense Code Snippets
Lorenzo Minore

Code download available at: AdvancedBasics0604.exe (117 KB)
Browse the Code Online
IntelliSense code snippets are one of the coolest new features in Visual Studio® 2005. Code snippets are highly customizable code fragments intended to accomplish simple to intermediate tasks quickly; they can be inserted into your code with just a few keystrokes.
In this column I'll describe how to use the code snippets installed with Visual Studio 2005, how to edit the existing set or create your own, how to share your snippets with other users, and where to look for more samples.

Inserting Code Snippets into Code
Code snippets can be inserted in a variety of ways. If you're in the editor browsing for a code snippet, use the Code Snippet Inserter. You can invoke it by right-clicking in the editor and selecting the Insert Snippet... command from the context menu. In Visual Basic® you can also type "?", then hit the Tab key to obtain the same result. The Code Snippet Inserter has some features in common with the IntelliSense® UI; it lets you navigate the snippet directory structure to select the snippet you want to use (see Figure 1). Tooltips will appear beside the currently selected snippet to give you a description and the shortcut for it.
Figure 1 Code Snippet Inserter 
For snippets that you use more frequently or for which you want quicker access, you can just type the shortcut in the editor, followed by the Tab key to insert them. To learn a snippet's shortcut, you can either select it in the Code Snippet Inserter and look at the tooltip, or view it in the Code Snippets Manager, which can be accessed via the Tools menu.
The shortcut+Tab insertion method also produces a neat effect for snippets that use keywords as their shortcuts. Type Select followed by Tab in your Visual Basic code and the Select-Case code snippet will be inserted (see Figure 2).
Figure 2 Select-Case Snippet 
If you only remember a part of the snippet's shortcut, in Visual Basic, you can type the beginning of the shortcut, type "?" followed by the Tab key, and a shortcut completion list will appear (see Figure 3). For example, to insert a Visual Basic snippet from the Application directory, you could type "app" (the shortcut prefix for that directory), or just "a" followed by "?", then hit the Tab key in order to invoke the list. When the shortcut list appears, the title of the snippet corresponding to the currently selected shortcut will be displayed in the tooltip. You can navigate the list, then double-click or press Enter to insert the selected snippet into your code.
Figure 3 Snippet Shortcut List 
Visual Basic snippets can also be inserted in code through a simple drag and drop operation. If you know the location of a particular snippet file on disk, you can simply drag and drop it from Windows® Explorer directly into your Visual Basic code!
You can undo a snippet insertion; if you inserted the wrong snippet or invoked a shortcut by accident, just execute the undo command (Ctrl+Z) and your code will return to its previous state.

Code Snippet Customization
Code snippets are different from simple fragments that you can copy and paste into your editor.
When you insert a Visual Basic code snippet it will automatically add the referenced assemblies to the project and the required imports to the code file, so that your code will build properly (this feature, however, is not supported in C# code snippets).
What really makes code snippets so convenient to use is the replacement fields, green highlighted areas that identify the values you may commonly want to replace to fit the snippet to your specific task. You can use Tab and Shift+Tab to move back and forth through replacement fields. Each one has a tooltip associated with it that describes what it represents and how it should be replaced.
In Visual Basic, replacement fields also have IntelliSense support to help you make the right substitution; if you hit Ctrl+Space while in a replacement, a list of the local variables of the same type as the replacement will pop up, and you can pick one as your substitution. In C#, this key combination will bring up the same IntelliSense completion list you would see when typing ordinary code (see Figure 4).
Figure 4 Replacement Fields with IntelliSense 
While you type in a replacement field, it will extend itself; if you want to keep typing without further extending that field, you can hit the Esc key, which lets you transition outside of the replacement.
Replacements can be linked; there may be multiple occurrences of the same one, and when you replace one, all the linked ones will be updated automatically as well.
In Visual Basic the replacement fields will stay highlighted as long as you don't close the code file and all associated files (that is, a Form's design view needs to be closed as well). In C#, once you press Enter, the replacement fields will be gone and your changes will be committed. Of course you can always make more changes later on; as the snippet becomes part of your code, though, you won't have the visual help of the highlighting or the other replacement field features.

Managing Code Snippets
Code snippets installed with Visual Studio are organized in a directory structure by the subject or task they accomplish. To see all directories and the snippets they contain, you can open the Code Snippets Manager. Simply select Tools | Code Snippets Manager (see Figure 5). This dialog lets you browse the snippet folders and displays useful information. When you select a snippet, you'll be able to see its physical location on disk, a short description of what it does, the shortcut, and the snippet author (which is Microsoft Corporation for all preinstalled snippets).
Figure 5 Code Snippets Manager 
The Add button in the Code Snippets Manager lets you add a whole folder to the root of the directory structure shown. This is a good way to add new snippets that you have stored in a directory on disk to your collection. The folder you're adding may contain some files that are not code snippets, but when you look at it in the snippet manager you'll see only subfolders and code snippets. Your current selection in the tree view doesn't affect where the new folder is added; it will always be a direct child of the snippet folders root.
The Import button lets you add one or more code snippets to the directory structure shown by the snippet manager. Once you select the snippets you want to import, you'll be able to choose the folders where you want to place these snippets.
The snippet directory structure contains a folder called My Code Snippets, where you should install your own snippets or the ones obtained from other users. If you want to make changes to some of the code snippets installed with Visual Studio 2005, it's a good practice to create a copy of the snippet in the My Code Snippets folder and modify it; otherwise it may be hard to revert.
To change the code snippets installed with Visual Studio without first copying them, you also need write privileges to the Program Files folder, which are normally granted only to administrators.
The Remove button will simply remove the currently selected folder from the directory structure shown by the Code Snippets Manager. The folder you remove won't be deleted from the file system, it will just be removed from the Snippets Manager's view. You can always use the Add command to get it back. The Snippets Manager view represents the snippets you'll be able to insert in your code editor through the snippet inserter or the other techniques described here, so if you remove a folder from this view, you won't have access to the snippets it contains in the IDE.
The Search Online command will bring you to the MSDN® search dialog, where you can enter keywords and search for code snippets. Unfortunately, this feature doesn't always work quite as expected, and you may end up with results matching your keywords but not related to code snippets. If you're searching online, I suggest using a search engine and entering your keywords together with "code snippet" or "IntelliSense Code Snippet" as this should give you a more fitting set of results.

The Visual Basic Snippet Editor
You're not limited to the code snippets that come with Visual Studio 2005; you can write your own or obtain them from other people.
Code snippets are actually XML files that follow a specific format. To see what they look like, open a code snippet in an XML editor. If you want, one way to edit code snippets is to work on the XML directly. If you want to learn more about the XML format of code snippets, take a look at the MSDN Code Snippet Schema Reference.
An easier way to write or modify code snippets is using the Visual Basic Code Snippet Editor tool.
The Visual Basic Snippet Editor is a shared source project developed by the Visual Basic user community in conjunction with the Visual Basic team. One of the Visual Basic MVPs, Bill McCarthy, did most of the development and bug fixing for the editor and gave it the slick look it has today (see Figure 6).
Figure 6 Snippet Editor 
When you open the editor, you'll see the left-hand pane containing a tree view similar to the one in the Code Snippets Manager. A textbox above it also lets you filter for particular keywords. When you select a node in the tree view and right-click on it, you'll be presented with a context menu and different options to manage your snippets and directories.
Both the Snippet Editor and the Code Snippets Manager share the same information regarding the code snippets folders, so if you make a change in one of the two tools, it will be reflected in the other one.
The Snippet Editor gives you the option to remove a single snippet when you select it in the left pane. In this case, the snippet will be deleted from the file system, so be very careful with this command. You can either add a new empty snippet to one of the folders or open an existing one.
If you plan to modify one of the snippets installed with Visual Studio, I suggest you create a copy in the My Code Snippets folder and work on that one. Depending on the version of the snippet editor you have, the My Code Snippets folder may not be displayed by default in the tree view, but you can easily add this directory yourself. The snippet code will be shown in the editor view, and there is also a preview pane that shows you how the snippet is going to look when you insert it in code.
Below the editor window there are five different panes that let you further customize your snippet. In the Properties pane you can modify the snippet's Title, Shortcut, Description, Author, Language, Scope, and Help URL. Most of these are self-explanatory. The Scope property refers to the code construct represented by the snippet—whether it's a class declaration, a member declaration, or part of a class member body. This can be a bit misleading because you may think that the scope is where the snippet lives instead of what the snippet represents. The Help Url property isn't enabled; it will be saved in the snippet file, but currently it won't be shown anywhere in the Visual Studio IDE. Other users will be able to see it if they open your snippet with the editor.
In the Replacements pane you can browse through replacement fields and modify their properties, or you can create new ones. Some replacement properties are not supported in all languages; the Function and Editable fields are supported in C#, but not in Visual Basic.
To create a new replacement, you can simply select the code in the editor and click on the + button in this pane. The Snippet Editor also allows you to create linked replacements; it will do so automatically if it finds expressions matching the one you selected in the snippet code. The Replacement Kind and Type properties are used in Visual Basic to provide IntelliSense for that field, so make sure to set them correctly if you want to enable this feature.
The References and Imports panes let you specify the referenced assemblies and Imports statements associated with the snippet you're authoring. These will be automatically added to your project and code file when you insert the snippet. This feature is currently supported only in Visual Basic. The Test pane lets you compile the code snippet inserted in the right scope and check for errors.
The Options dialog in the Snippet Editor can be used to customize the editor font and appearance and to select which languages you want to use. The language choice affects the snippets shown in the tree view and the keyword colorization in the code editor. Another interesting feature is the Save as .vsi command. This option lets you save a code snippet as a VSI (Visual Studio Installer) file. This is the recommended format for sharing community content, and makes installing new code snippets very easy.
For further information on how to use the editor, you can download the documentation from the Snippet Editor workspace. Here you can also file bugs or request new features for the editor and download the source code. You should also check out Snippy, another tool for creating code snippets, created by Gus Perez.

Sharing Code Snippets
Two Web sites that host code snippets are DotNetJunkies and GotCodeSnippets. Both sites currently have a limited number of code snippets available, but I expect these to increase significantly over the next few months.
The code snippets you download from there are in .vsi format. Once you have downloaded the .vsi package, double-click it and a wizard will guide you through the installation process, asking you, among other things, in which folder you want to place the snippets (see Figure 7). Again, I suggest separating snippets you download from the Web or obtain from other developers from the ones created by Microsoft; you can do so by placing them in the My Code Snippets folder.
Figure 7 Screen from the Visual Studio Content Installer 
If you're planning to publish or share your own code snippets, I'd recommend using the .vsi format as well; this will make installation for your target audience easiest. To create a VSI with multiple snippets, the easiest way is probably to use Craig Skibo's Content Installer Powertoys, available on GotDotNet. The Content Installer Tool will walk you through the process of creating a Visual Studio Installer Package with multiple code snippets. This tool actually supports creating packages for other content types as well.

The Power of Snippets
Give code snippets a try. The ones included in Visual Studio provide a wide variety of productivity-enhancing solutions. However, the real power of this feature is its extensibility. The snippet editor, the code snippet hosting sites, and the VSI format and tools provide a framework for the user community to create a diversified code snippet library accessible to everyone.

Send your questions and comments to  basics@microsoft.com.


Lorenzo Minore is a Software Design Engineer for Microsoft on the Visual Basic team, working on the data design time experience in Visual Studio. He also coordinates a team to promote IntelliSense code snippets in the Visual Basic user community. Reach Lorenzo at lorenzom@microsoft.com.

Page view tracker