| By Tommy Newcomb | Article Rating: |
|
| November 17, 2006 02:45 PM EST | Reads: |
15,478 |
Every now and then a new development tool comes along that is so simple and elegant it leaves us wondering, why didn't we get this sooner? Introducing Intellisense Code Snippets, it's a new feature available in Visual Studio (VS) 2005 that makes inserting routine code much faster and easier.
Using snippets is as simple as right-clicking in the IDE and left-clicking on the Insert Code Snippet pop-up. This opens the Visual Studio Code Snippet Picker, similar to Intellisense, which lets you insert pre-packaged code statements directly into your class. There's nothing extra to install or download so you can start using snippets packaged with VS 2005 immediately.
Visual Basic (VB) and C# both take advantage of snippets; however, VB seems to have been the target language for the snippet designers while C# was more of an afterthought. C# has most of the same functionality, but not quite. In this article, I'll use both languages and make sure to point out the differences along the way. If you're attached to a certain language you needn't worry; they both have their advantages and disadvantages and behave almost identically.
The benefits that you'll gain from using snippets are twofold. First, they reduce repetitive, time-consuming typing. For example, if you intend to write something common like a For loop, try...Catch block, or an If statement. You needn't waste time typing the code for these simple statements. Your snippet will be inserted and you only have to modify the parts of the statement specific to your code.
The second and perhaps greater value is that you no longer have to remember the exact syntax for a particular statement. If, for example, you needed to create a task-oriented snippet that's more complex than an If statement, such as code that will create a parameterized stored procedure, an inserted snippet will give you a perfect example. This eliminates that Google-search crapshoot that we do when we can't quite remember the exact syntax.
Again, to get started you can begin today by using the packaged snippets in the IDE, but there's much more to snippets through customization as we'll see. There are dozens of snippets provided in VS 2005, and there are many more available for download. This article will show you how to create your own snippets, modify existing ones, and demonstrate how to create your own snippet library to improve your productivity, giving you an edge as a highly productive developer.
Inserting Snippets
We're ready to insert our first snippet. While in the VS 2005 IDE, you can right-click where you'd like to place your snippet and select the Insert Snippet...command from the Snippet Inserter menu. In VB only this same step can be accomplished by typing "?" then the Tab key. When you do this you'll notice several sub-categories, such as Collections and Arrays, Common Coding Patters, etc. When you select a sub-category and then select a particular snippet, a tool tip displays both a description of the snippet and its shortcut value. If you know your snippet's shortcut value, you can skip all of this clicking and simply type in the shortcut then hit the Tab key to insert your snippet of code.
For many snippets, the shortcut value is the same as the first word in the statement. So, if you wanted to throw an exception in your code you simply type "throw" then hit the Tab key and it appears. If you aren't quite sure what your snippet shortcut is, you can find it by typing a portion of the keyword. So when you type "Try" then "?" then hit the Tab key, all of the exception-handling statements show up in the Snippet Inserter for you to choose. If you don't like your inserted snippet, executing a Ctrl-Z will remove it as quickly as it appeared.
Many times you have existing code that needs to be modified. Snippets are intelligent in that they don't always overwrite existing selected code with your insert. If, for example, you have existing code and you want it surrounded with an If statement, you can highlight the code and insert your snippet. Your selected code will remain and your If and End If tags will surround it. A big time saver for me is when I have to add Region tags to my code. Using snippets I select the block of code that I want inside my Region and Insert Snippet and - voilá - it's done. It saves scrolling, cursor placement, mouse handling, and typing.
If your snippet code relies on an Imports statement or a project reference, VB will add the necessary Imports and project references as well. It's here that VB has an advantage over C#.
We can see that code snippets have more intelligence than simply cutting and pasting code. In this next VB example, notice how we can insert a Generic List item snippet by choosing: Insert Snippet | Collections and Arrays | Create a list with items of a single Type. (Figure 1)
The following code is inserted:
' Backing storage -- a generic list
Dim names As New List(Of String)()
' Add an item to the Collection
names.Add("John")
The areas that are specific to your code that require a change are highlighted in green. Hitting the Tab key will quickly move your cursor over these areas; hit shift-tab to reverse. The highlighted linked items, such as the names variable in our code, all change to the same value when one occurrence is changed. It's smart enough to know that we're naming all the variables in our statement the same. When you're finished making changes to a field, hit the Escape key to commit and move on.
Now, suppose that you want to loop through the previously inserted Generic List using a For Each...Next statement. Click Insert Snippet | Common Coding Patterns | Conditionals and Loops | For Each...Next Statement.
When your cursor is on the first variable name, in this case Item, if you hit Ctrl + Space, a list of all your declared variables (of the same type as the cursor replacement) will pop up. This lets me choose from my previously declared variables in this selectable list. Notice that I can select myNames and names from the list. Pretty cool, huh? (Figure 2)
Note that in VB once your snippet has been inserted and modified it will remain highlighted until you close the file and all its associated files (like a Form's design view).
Snippets: Inside the Magic
Let's take a look inside the Generic List snippet that comes with VS 2005. To begin with, a snippet is really just an XML file, and the snippetformat.xsd schema defines the rules for valid snippets.
In Listing 1, we use the CreateAStronglyTypedCollection.snippet file located at C:\Program Files\Microsoft Visual Studio 8\VB\Snippets\1033\collections and arrays\. These files are easy to modify and create, which we'll get to, but first look at our collection-snippet XML. The CodeSnippet element defines our entire snippet. The Format attribute in the CodeSnippet element is simply the version it's been given. Following that we see the Header, Title, and Author tags that are intuitive enough, but notice the Shortcut tag. This tag defines the shortcut we used earlier when we typed the value and hit the Tab key to insert our snippet.
The Description tag is what you see displayed in the Intellisense browser description and does just what it says, but you should also note that there are three more tags that can be used in the Header tag: Keyword, HelpURL, and SnippetTypes. The Keyword element(s) provide a standardized way of searching through snippets, the HelpURL is simply a help file reference link, and the SnippetsTypes are a bit more complex - and useful.
SnippetTypes tell the snippet how to behave on insert. There are two types you can use with custom code snippets: SurroundsWith and Expansion. Expansion simply means to insert the code at the cursor. The SurroundsWith tag will actually insert the snippet around the code that's selected. In the diagram, I have a couple of lines that are based on a condition. (Figure 3)
When I choose Surround With... from the menu then the If option, the If code literally surrounds my selected text:
Next, let's take a closer look at the Snippet element. As I mentioned before, only VB supports the Reference tag that provides information about the necessary references that your snippet requires. This is specified under in the snippet element:
<Reference>
<Assembly>System.Windows.Forms.dll
</Assembly>
<Url />
</Reference>
The Assembly element is the name of the reference of course and the URL tag is a link to a more detailed description. The Imports is also a potential child element of the Snippet element and is similar to the Reference element. VS 2005 adds the necessary Imports to your code when the snippet is inserted:
<Imports>
<Import>
<Namespace>Microsoft.VisualBasic
</Namespace>
</Import>
</Imports>
To describe the Declarations element, let's look at the following XML taken from VB's Select...Case Snippet in Listing 2.
Published November 17, 2006 Reads 15,478
Copyright © 2006 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Tommy Newcomb
Tommy Newcomb works for Magenic as an IT consultant in the Chicago area.
His main focus is developing Web application and E-commerce work using Microsoft technologies. He lives with his wife, Emily, and baby daughter, Jaqueline, in the Chicago suburbs.
- Kindle 2 vs Nook
- Wave on Ulitzer: Confessions of a Google Wave Fanboy
- Confessions of a Ulitzer Addict
- IBM Hardware Chief, Intel VC Exec Arrested in Insider Trading Scam
- Cloud Computing Best Practices
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- Ulitzer.com Named Exclusive "New Media" Sponsor of Cloud Computing Conference & Expo
- Infrastructure-as-a-Service Will Mature in 2010: Microsoft's David Chou
- Windows 7 – Microsoft’s First Step to the Cloud
- Cloud Computing & Federal IT - What Does the Future Hold?
- Jill Tummler Singer, Deputy CIO of CIA, Keynotes at GovIT Expo
- Cloud Expo and the End of Tech Recession
- Kindle 2 vs Nook
- The Difference Between Web Hosting and Cloud Computing
- Ajax in RichFaces 3.3, JSF 2 and RichFaces 4
- Wave on Ulitzer: Confessions of a Google Wave Fanboy
- Confessions of a Ulitzer Addict
- IBM Hardware Chief, Intel VC Exec Arrested in Insider Trading Scam
- Cloud Computing Best Practices
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- Ulitzer.com Named Exclusive "New Media" Sponsor of Cloud Computing Conference & Expo
- Eval JavaScript in a Global Context
- Infrastructure-as-a-Service Will Mature in 2010: Microsoft's David Chou
- Windows 7 – Microsoft’s First Step to the Cloud
- Google Maps and ASP.NET
- Crystal Reports XI & How It Has Changed
- Converting VB6 to VB.NET, Part I
- Creating Controls for.NET Compact Framework in Visual Studio 2005
- Where Are RIA Technologies Headed in 2008?
- How to Write High-Performance C# Code
- AJAX World RIA Conference & Expo Kicks Off in New York City
- Implementing Tab Navigation with ASP.NET 2.0
- i-Technology Photo Exclusive: Bill Gates & Steve Jobs In "Nerds"
- .NET Archives: Getting Reacquainted with the Father of C#
- i-Technology Viewpoint: "SOA Sucks"
- Programmatically Posting Data to ASP .NET Web Applications


































