devxlogo

An Introduction to the New Visual Studio Snippet Format

An Introduction to the New Visual Studio Snippet Format

roductive developers and coding shops all maintain some type of custom code or scripts library, usually chock-full of code routines for common tasks such as string parsing, database operations, etc. Unfortunately, the mechanism used to store and retrieve such code clips?often simply a vast directory tree full of text files saved on a local or external drive or stored on a network file server?has also been custom-built.

In some cases, these home-built source code libraries are convenient, but just as often, because code and coding practices change rapidly, they end up becoming stale or out-of-sync with development trends. With Visual Studio 2005, Microsoft has finally stepped up to offer a generic, supported, and efficient way to manage and access those code libraries?Visual Studio .NET snippets.

If the word “snippets” causes you to immediately make assumptions about the intent, you’re probably correct. Snippets are little code blocks commonly used for repetitive tasks. Storing source code files locally in My Documents may be opportune, but it’s not scalable, and is prey to human error. Visual Studio stores snippets in XML; they support replaceable parameters, assembly references and Imports (or using for C#) statements. Moreover, they provide an efficient way to organize and store reusable code with a level of scalability that was difficult to achieve with custom solutions.

Snippet files are simply well-formed and valid XML files with a .snippet extension, placed where Visual Studio can find them. Although the Beta 2 release of VS.NET does not yet have a snippet editor (I stress yet), it does come with a Snippets Manager to help you administer it all. For those who insist on a snippet editor immediately, you can download a free VB.NET Snippet Editor from MSDN. The free Snippet Editor is a shared-source project; so I encourage you to download the source files, make enhancements or fixes as you see fit, and check in your modifications to help improve the product.

I’ll start out by showing you the basics of the Snippets Manager using stock snippets included with VS.NET 2005 Beta 2. Then you’ll see how to create new XML snippets, how to add them to the Snippets Manager, and finally, how to package them for distribution.

Visual Studio Snippets Manager
To get started, open VS.NET 2005 Beta 2 and begin a new project. When the New Project dialog window opens, expand the Visual Basic item in the Project Types pane. Select Windows, and in the Templates pane, select Windows Application. If you prefer, change the name of the application and change the location where the application is to be saved. Click OK (see Figure 1).

?
Figure 1. Create a New VB.NET Application: The figure shows the New Project dialog, in the process of creating a new Windows application project.

After the project loads, it defaults to design-time mode and displays a blank form. Switch to code view using the Solution Explorer tool bar, and you’ll see the default template that begins a public class named form1. At this point, I usually create a few named Regions. Regions, in Visual Studio, set collapsible blocks of code, giving you the ability to organize and hide portions of your code, just like Classes, Functions or Methods. I name these Regions “methods,” “functions,” and “declarations.”

For this example, you’re going to create a method to handle a basic file system task and a function that generates and returns a random number.

First, create a method named copyFiles. Next, press Enter to close the method, and place your cursor between the opening and closing statements. This is where you’ll add the snippet.

   Sub copyFiles()     ' place your cursor here   End Sub

The snippet code for this example already exists in the snippet libraries that ship with Visual Studio. Open the Snippets Manager by pressing Ctrl+K+B and make sure Visual Basic is selected in the Language ListBox. In the left pane you’ll see a directory tree of all the snippet’s categories. Expand the filesystem folder and select the “Copy a File” snippet. When you select a snippet, the Snippets Manager displays the path to the selected snippet file in the location bar, and displays a description of the snippet, the shortcut phrase, and the author in the right pane (see Figure 2). Alternatively, you can place your cursor where you want the snippet inserted and press Ctrl+K+X, to open Snippet Intellisense, which then displays available snippets based on the language of the current project.

?
Figure 2. Selecting a Snippet: Open the Snippets Manager and select the Copy a File snippet in the filesystem folder.

To insert the “Copy a File” snippet code, make sure the cursor is inside your copyFiles method, and then type the shortcut phrase shown in the right pane (filCopyFile) and press the Tab key. Visual Studio inserts the snippet code into your method, replacing the shortcut phrase, and highlights any replaceable parameters.

   Sub copyFiles()      My.Computer.FileSystem.CopyFile("C:Source.txt",          "C:NewFolderDest.txt")   End Sub

Next, create a method named getRandNum() that will generate and return a random integer.

   Private Function getRandNum() As Integer            End Function

Press Ctrl+K+B to open the Snippets Manager and expand the math folder. Select the “Get a Random Number using the Random class” snippet. Type the shortcut phrase into your function and press Tab. As before, this will insert the snippet into your function and highlight the replaceable parameters. To complete your function, add a Return statement after the snippet code and pass the variable named randomValue to it.

?
Figure 3. Form Code with Inserted Snippets: The figure shows the code view of the sample form after completing a method and a function by inserting Visual Studio snippets.
   Private Function getRandNum() As Integer      Dim generator As New Random      Dim randomValue As Integer      ' Generates numbers between 1 and 5, inclusive.      randomValue = generator.Next(1, 6)      Return (randomValue)   End Function

In both the examples shown here, you can substitute your own variables or constants for the replaceable parameters, and place a copy of the variables in the functions parameter list. Just as with any code in Visual Studio, you will have real-time debugging and Intellisense. Your class should look like Figure 3.

Create Your Own Snippets
Now you know how to retrieve and insert snippets into your projects using the Visual Studio Snippets Manager, and you’ve probably explored the large number of built-in snippets that ship with Visual Studio. But you’re probably eager to create your own snippets and use them the same way. Here’s how to create a .snippet file, save it in the My Code Snippets folder and use it in your current project. Afterwards, you will see how to add other snippet folders to the Snippets Manager to help organize your code better or access snippets on a network share.

First, create a stub private function called replaceLastOcurr() that returns a string. Your code should look like this.

   Private Function replaceLastOcurr() As String      End Function

A snippet file is a well-formed and valid XML file with a .snippet extension. Start by creating a new XML file to hold the snippet using the standard document type declaration, including the encoding attribute. You can use Visual Studio, or NotePad, or any text editor; however, I use Altova’s XML Spy for all my XML-based documents.

   

Snippet files contain the following nodes, some of which can contain child nodes. The root element is , which contains one or more elements. Each element contains the snippet code, as well as nodes for ancillary information, such as the snippet title, author, description, and keywords. The element also includes a shortcut phrase and help URL.

               

The code structure description begins after the header, in a element. Each element has a child element, which contains a set of nodes. A literal is the description of a replaceable parameter or variable.

Each element contains:

  • An element, which is your replaceable parameter.
  • A element, which holds the data type of your replaceable parameter.
  • A element, which displays information or instructions in the Snippets Manager for display on a event.
  • A element, which is a default value for this literal.
                                                                                                                                                                   

The following and final child element in the section is , which is where your actual code snippet goes. The node has two attributes; Language and Kind. The Language attribute defines the language used for the code and accepts VB, Csharp, JSharp or XML. The Kind attribute specifies the kind of code the snippet contains and filters out snippets based on your location in the code. This example uses “method body” and “function body.”

You begin your code by containing it within a character data declaration.

    

The CDATA tag tells the XML interpreter to not parse the code?to treat it as literal content.

You write the code exactly the same as if it were in your project, except that you place the IDs from your Literal nodes where your replaceable parameters go, delimiting them within your code using dollar ($) signs.

?
Figure 4. An XML Snippet File: This example snippet file contains code converted from an existing DevX VB.NET tip.

For this example, I’ve converted an existing DevX VB Tip to a code snippet. Figure 4 shows an example snippet XML file and how the code for the VB Tip was transformed.

Save this file with a .snippet extension into the folder C:Documents and SettingsMy DocumentsVisual Studio 2005Code SnippetsVisual BasicMy Code Snippets.

The VS.NET 2005 Beta 2 installation creates that folder during installation, and should already be included in your Snippets Manager. The Snippets Manager comes with a few options to add snippets or folders of snippets. The Add button gives you the ability to add a new folder and all its contents to the directory tree, whereas the Import button lets you import a single snippet into an existing directory within the Manager. There is a Remove button to remove entire folders from the directory tree, but note that the Remove feature does not let you remove individual snippets. There is a Search Online button, but with VS 2005 not yet in production, there were no snippets to be had online at the time of this writing. Give it time.

Packaging Your Snippets For Distribution
With the Visual Studio Community Content Installer (VSI), it can’t get much simpler to create a redistributable version of your code snippets. This is a three-step process that you can also use to package Visual Studio project templates, starter kits, and controls, and even expand upon by registering other content handlers. But that is beyond the scope of this article. There are in-depth instructions on MSDN for those looking to take full advantage of the VSI. The primary difference between the various types of distributions lies in the contents of the XML manifest, or Meta file.

Visual Studio Community Content Installer files have a .vsi extension and are handled by a standalone EXE on the user’s machine. The VSI came to fruition from a need to create a way to easily and consistently exchange Visual Studio content to be shared within the developer community. Through a simple wizard, the VSI helps the user install snippets in the specific registered location required by Visual Studio .NET.

For distributing snippets, the VSI package is made up of your .snippet files and a .vscontent file, which is an XML manifest. The XML manifest for snippet files has a root element named VSContent, which in turn must contain a Content element for every snippet you want to include. The content element has the following child nodes:

  • FileName?The name of the snippet file.
  • DisplayName?The friendly name displayed in the VSI interface.
  • Description?The Tooltip text for the item.
  • FileContent?The valid value for code snippet distributions is Code Snippet.
  • ContentVersion?For now, this should always be 1.0 (at this point, all content types are 1.0).
  • Attributes?The parent node for a set of Attribute child nodes.
  • Attribute?A valid attribute name/value pair for this element is lang with a value of either csharp, jsharp, vb or XML.
Author’s Note: Code snippets require the lang attribute. Other attributes include TemplateType, ProjectType, and ProjectSubType. Other valid FileContent values are Addin, Macro Project, VSTemplate, and Toolbox Control.

A completed XML manifest to install snippets should look similar to Listing 1.

Now that you have your snippet files and your manifest, you are ready to package it. Add those files to a ZIP archive. Once zipped, change the file extension to .vsi, and you’re done. Your snippets are ready for distribution.

When you are ready to test your package, or install a package you received, simply double-click on the .vsi file, or if downloading from the Web, choose Open from your download dialog and the installer will display all the snippets that were included in the VSI package, including any information about the publisher if it was signed.

If you are not familiar with the publisher, if the .vsi file isn’t signed, or you’re downloading from a third-party site, I recommend clicking the Review button. This will open Windows Explorer and display the files included in the package via a temp file, giving you the chance to scan it for viruses. Reviewing the contents will help protect you from blindly installing malicious or unknown file types. Furthermore, any files included in a VSI package should be viewable with Notepad, so you can review the code.

After you have reviewed the code and deemed it safe, click the Next button. This will display the Installing Content dialog with links in the Details pane for each item you want to install. After checking all the desired items, click Next and then choose the location where you want to install them, and?if applicable?configure how they should be installed. Click Next to complete the installation. There’s always the possibility for naming conflicts; if they occur you’ll be given the opportunity to overwrite, cancel the installation, or rename the snippets.

When the installation is complete (or failed to complete), links appear next to each item. Clicking these links displays the install status. If any failed to install, you can use the status report to fix the issue and attempt to install again. When you’re done, click Finish to wrap up the install.

Visual Studio records every VSI package you install in a history file named ContentInstallerHistory.xml located in the C:Documents and SettingsMy DocumentsVisual Studio 2005 folder. Note that this is a hidden file, so you may have to change the view properties of that folder to display all the files.

In my opinion, snippets are an excellent addition to the features in Visual Studio .NET. You obtain better organization of your code, scalability through replaceable parameters, and gain another step in efficiency; “Work smarter, not harder”…right?

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist