Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Visual Studio 2005 » Using Snippets in Visual Studio 2005

Using Snippets in Visual Studio 2005

Visual Studio contains several built-in intellisense code snippets. Snippets are like templates and can be described completely in XML. If you understand the snippet xml schema, you can easily begin to create your own snippets.

Author Rank:
Total page views :  3514
Total downloads :  36
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
CopyrightSnippet.zip
 
Become a Sponsor

Introduction

I finally found some time to download Visual Studio 2005 and take a look at some of its powerful new features. One feature that struck me as a real time saver was the new code snippet Intellisense feature. This feature allows you to create pieces of commonly used code with just a few keystrokes. For example, if I want to create a property using the snippet feature, I simply type prop into Visual Studio, hit the tab key twice, and Walla, instant property and corresponding private variable. I then have the ability to edit the private variable type and name, which simultaneously changes my property type and internal get and set variables.

 

  

 

Figure 1 - Snippets in Visual Studio 2005



Figure 2 - Property generated by the Intellisense Code Snippet

Visual Studio contains several built-in intellisense code snippets. Many of the shortcuts for these snippets are C# keywords themselves that just expand after hitting the magical tab key twice. These include C# keywords such as for, if, switch, try, foreach, while, and using. There are some also less obvious shortcuts such as tryf, mbox, and ctor (try-finally, messagebox, constructor). All of these snippets can greatly increase the efficiency of your coding.

Understanding a Snippet

Snippets are like templates and can be described completely in XML. You'll find all of the above snippet xml file representations in the C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C# directory. If you understand the snippet xml schema, you can easily begin to create your own snippets. In order to begin understanding snippets, let's look at a simple predefined xml snippet, the if statement.

<?xml version="1.0" encoding="utf-8" ?>
<
CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<
CodeSnippet Format="1.0.0">
<
Header>
<
Title>if</Title>
<
Shortcut>if</Shortcut>
<
Description>Code snippet for if statement</Description>
<
Author>Microsoft Corporation</Author>
<
SnippetTypes>
<
SnippetType>Expansion</SnippetType>
<
SnippetType>SurroundsWith</SnippetType>
</
SnippetTypes>
</
Header>
<
Snippet>
<
Declarations>
<
Literal>
<
ID>expression</ID>
<
ToolTip>Expression to evaluate</ToolTip>
<
Default>true</Default>
</
Literal>
</
Declarations>
<
Code Language="csharp"><![CDATA[if ($expression$)
{
$selected$ $end$
}
]]>
</
Code>
</
Snippet>
</
CodeSnippet>
</
CodeSnippets>

Listing 1 - Code Snippet for the if statement in C#

The first part of the snippet is the header. This contains the title of the snippet, the shortcut keys needed to invoke the snippet, a description of the snippet, and the company that made the snippet. It also contains the different kinds of snippets the snippet supports. There are three allowed types of snippets: Refactoring, SurroundsWith, and Expansion. SurroundsWith allows you to use the snippet by selecting the code you want to affect and invoking the snippet around the selected code. Our if statement supports SurroundsWith. Therefore if you select a group of statements, right click and choose Surrounds With from the popup, and select the if snippet, the statements will suddenly be engulfed by a bracketed if statement. Expansion types simply expand the snippet after the cursor. The if statement also supports the Expansion type. If you type if and then tab twice, the if statement will expand from the point of the cursor.

It is useful to insert header information into your snippet because it can be used to describe your snippet in the Snippet Manager which can be brought up from the Visual Studio 2005 Tools Menu shown in Figure 3:



Figure 3 - Snippet Manager

After the header, we have the snippet itself. The snippet is similar to a template and contains two main sections: declarations and code. Declarations consist of literals and objects. In our if example, we only use literals. Literals are simply variables inside your snippet code. These literals can be substituted and edited inside the code snippet produced. In our example, the literal has three sections: the ID, the tooltip, and the default value . The ID identifies the literal inside the code. expression is our ID for the if statement. In the code section, expression is represented as $expression$. The dollar signs indicate that we have a variable in our code. The tooltip tag supplies the information for our tooltip. If we drag over our literal expression after the snippet is expanded inside our code, it brings up the tooltip defined in the tooltip node, giving us a little more information about our literal variable. The default value is the initial text inserted inside the if statement, in this case is the value true.

The Code section starts with the attribute "Language" to let us know which programming language our code snippet produces. The next part of the Code section is mostly a template containing variables marked for substitution with the bookend dollar signs. Our only variable is the literal expression seen between the dollar signs as $expression$. The other two dollar signed variables, $selected$ and $end$, tell us where the cursor selection will be placed after we've edited our literal expression and hit the enter key.

Below is the snippet produced for the if statement code snippet. Note that  the default value true is inserted into the literal variable and the if statement expression is ready to be edited.

Figure 4 - if statement generated from snippet

Creating a Custom Snippet

Now that we have a fairly good feel of how our snippet can help us create code fragments, let's create our own simple snippet. The snippet we create will contain commented copyright information for our source class. We will be able to edit the author, copyright year, and company name. The shortcut key will be cp. When the snippet is finished, it will exit two lines below the copyright information.

The first part of our copyright snippet is the header containing description, shortcut, snippet type(s) and author of the snippet shown in listing 2.

<?xml version="1.0" encoding="utf-8" ?>
<
CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<
CodeSnippet Format="1.0.0">
<
Header>
<
Title>CopyRight Insert</Title>
<
Shortcut>cp</Shortcut>
<
Author>Microgold Software Inc.</Author>
<
SnippetTypes>
<
SnippetType>Expansion</SnippetType>
</
SnippetTypes>
<
Description>Inserts a copyright string</Description>
</
Header>

Listing 2 - Header for the copyright snippet

The shortcut cp will show up in the snippet menu. If we type cp <tab> <tab> it will generate our code snippet right at the cursor point in our code since it is an expansion snippet. The next part of our snippet are the literal (variable) declarations for author, year, and company. All are editable variables and all have default values. You can change the default values to your own personal copyright information, or you can set them to more generic values such as Author, Year, and Company.

<Declarations>
<
Literal Editable="True">
<
ID>author</ID>
<
ToolTip>author of class</ToolTip>
<Default>Mike Gold</Default>
</
Literal>
<
Literal Editable="True">
<
ID>year</ID>
<
ToolTip>copyright year</ToolTip>
<
Default>2005</Default>
</
Literal>
<
Literal Editable="True">
<
ID>company</ID>
<
ToolTip>company owning code</ToolTip>
<
Default>Microgold Software Inc.</Default>
</
Literal>
</
Declarations>

Listing 3 - Declarations of variables inside the code snippet that can be edited

The last part of our snippet is the code template contained in a CDATA tag shown in listing 4. This template will be copied into our source at the cursor along with all the variable place holders. The coder can change the variables by tabbing between them. The $selected and $end are placed two lines down from the copyright comment. This placement of these variables will have the effect of moving two lines after the user hits the enter key.

<Code Language="csharp" Format="CData">
<![
CDATA[// This code was written by $author$ . This code may be used only for educational purposes.
// Any distribution of this code may only be carried out with written consent from the auhor.
// Copyright © $year$ by $company$
$selected$ $end$
]]>
</
Code>

Listing 4 - code template node for the copyright snippet

So now we have the entire picture. The final snippet with all its nodes is shown in listing 5 below. This code is saved in a file called copyright.snippet inside of the c:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C# directory. Saving the snippet will immediately make it active.

<?xml version="1.0" encoding="utf-8" ?>
<
CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<
CodeSnippet Format="1.0.0">
<
Header>
<
Title>CopyRight Insert</Title>
<
Shortcut>cp</Shortcut>
<
Author>Microgold Software Inc.</Author>
<
SnippetTypes>
<
SnippetType>Expansion</SnippetType>
</
SnippetTypes>
<
Description>Inserts a copyright string</Description>
</
Header>
<
Snippet>
<
Code Language="csharp" Format="CData">
<![
CDATA[// This code was written by $author$ . This code may be used only for educational purposes.
// Any distribution of this code may only be carried out with written consent from the auhor.
// Copyright © $year$ by $company$
$selected$ $end$
]]>
</
Code>
<
Declarations>
<
Literal Editable="True">
<
ID>author</ID>
<
ToolTip>author of class</ToolTip>
<
Default>Mike Gold</Default>
</
Literal>
<
Literal Editable="True">
<
ID>year</ID>
<
ToolTip>copyright year</ToolTip>
<
Default>2005</Default>
</
Literal>
<
Literal Editable="True">
<
ID>company</ID>
<
ToolTip>company owning code</ToolTip>
<
Default>Microgold Software Inc.</Default>
</
Literal>
</
Declarations>
</
Snippet>
</
CodeSnippet>
</
CodeSnippets>
 

Listing 5 - The entire copyright.snippet xml schema

After saving the snippet, when you type cp inside Visual Studio 2005, it will pop up the following menu:



Figure 5 - Snippet Insertion Popup Menu Showing the Copyright shortcut Selection

When you choose cp (and hit the tab key twice), it produces the following code snippet inside your class. The highlighted green fields can all be edited by the coder just as we did with the if statement. Tabbing cycles through each of the editable variable fields.



Figure 6 - Code Snippet generated from the copyright.snippet schema

Functions

Although not in any of our examples, snippet literal nodes support the concept of functions. Functions allow you to replace literal variables with strings returned from certain built in functions. The current list of functions, although fairly sparse, can sometimes be useful. The current functions supported by snippets are GenerateSwitchCases, ListVariablesOfType, ListEnumVariables, ClassName, SimpleTypeName. It would be great if you could somehow create your own functions, but I'm not really sure how this is done. Below is an example of including a function in a literal node for the ctor (constructor) snippet. The snippet variable $classname$ would be replaced with the name of the current class being edited.

<Declarations>
<
Literal Editable="false">
<
ID>classname</ID>
<
ToolTip>Class name</ToolTip>
<
Function>ClassName()</Function>
<
Default>ClassNamePlaceholder</Default>
</
Literal>
</
Declarations>
<
Code Language="csharp"><![CDATA[public $classname$ ()
{
$end$
}
]]>

Listing 6 - Part of the Constructor Snippet schema using the ClassName function

Conclusion

Snippets provide coders yet another way to cut time off their arduous coding day. You can use all the built in snippets to quickly generate C# language constructs by typing in their corresponding shortcuts. You can even create your own snippets to produce code that you find yourself frequently typing. You can even use code snippets to enforce a standard within your software programming team. One thing I wouldn't mind seeing as part of snippets is the capability to add some code (such as DateTime.Now) inside the snippet. Perhaps this is already possible, but I haven't figured out from the existing documentation how this can be done. Anyway, if coding is taking you longer than you wish and time is dragging on with those long coding constructs, snipp-et down with the power of Visual Studio and .NET.


Login to add your contents and source code to this article
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
CopyrightSnippet.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.