Thursday, August 18, 2011

How to create and deploy snippets

Snippets are little bits of pre-coded logic that are meant to help you remember how to perform
some standard code functions in various languages. In VB, for instance, you might not remember
how to read from a file, so there is a snippet for that. In C#, you may want implement a property
getter and setter, so you use a shortcut to get the snippet in place.

Using snippets
You can use a snippet in a few different ways, most of which are somewhat slow. The fastest way
is through the use of key commands. To use a snippet this way, type its shortcut code and press
Tab twice. For instance, try these steps:
1. Open Visual Studio and start a new Class Library project in C#.
2. In the new class that is created, place the cursor inside the curly braces.
3. Type prop.
4. Press Tab twice. Your results should look like the ones shown in Figure 3-2.
See the template that is put into place? Int is highlighted. You can type over it.
5. Type string and press Tab twice. Now MyProperty is highlighted.
6. Type FirstName and press Enter twice.
Now you have a finished automatically implemented property. It should look like this:

public string FirstName {get; set; }
You can get to a snippet in other ways, including this one:
1. Right-click at the insertion point.
You have the option to select Insert Snippet.
2. Click Insert Snippet.
The full list of all the installed snippets appears at the insertion point.
3. Click an item in the list, and the contents of that folder appear.
Continue selecting categories (the menu extends to the right) until you have selected the snippet you
were looking for.
4. Double-click the snippet to insert it.
After they're inserted, populating the variables works just like the shortcut version.

Using surround snippets
Surround snippets are very cool. Have you ever written a few lines of code, and then realized that
you should probably try and catch errors? You have to add a little code at the beginning, and then
add a little code at the end, and then make sure the middle is in the right place. It's a pain.

Surround snippets are designed to solve that problem. They are normal snippets with a bit of logic
in them that says "This part goes above the selection, and this part goes below the selection." If you
want to handle errors for a section, you highlight that section, and the snippet will put the try before
the selection and the catch at the end. To use a surround snippet, follow these steps:
1. Highlight some code in the Code Designer.
2. Press Ctrl+K,S to open the snippets menu.
3. Select the appropriate snippet from the menu. You can choose the snippet that is right for
whatever you are coding. Try prop for a property getter and setter.
4. Set the various variables that Visual Studio prompts you.
The snippet will appear appropriately above and below the selected text.
For instance, if I had this chunk of code:
for (int loopcounter = 1; loopcounter <= 10; loopcounter++)
{
Console.WriteLine(string.Format("The number is {0}.", loopcounter));
}
and I felt that I needed a try ... catch block around it, I could highlight that code and do the preceding
steps. If I select try from the menu, I will get this:
try
{
for (int loopcounter = 1; loopcounter <= 10;
loopcounter++)
{
Console.WriteLine(string.Format("The number is {0}.",
loopcounter));
}
}
catch (Exception)
{
throw;
}
Exception is highlighted in green; I can tab to that and add the exception type I am expecting. It's a
slick system.

Making snippets
Snippets are XML files that follow a format understood by Visual Studio. They include a Header and
Snippet element. The Header includes a title, which is how the snippet is referred. The Snippet element,
where all the work is done, includes a Code element, which has the code to be inserted.

The best way to make a new snippet is to modify an existing one. Snippets can be found in your Visual
Studio install directory, which should be C:\ Program Files (x86)\Microsoft Visual Studio 10.0\VC#\
Snippets\1033 if you are on a 64-bit operating system (otherwise you can
drop the x86).

In the folder referenced in the preceding paragraph, let's look at a simple example: cw.snippet is a
Console.Writeline command. Right-click the file to open it. Here's the code:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>cw</Title>
<Shortcut>cw</Shortcut>
<Description>Code snippet for Console.WriteLine</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal Editable="false">
<ID>SystemConsole</ID>
<Function>SimpleTypeName(global::System.Console)</Function>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[$SystemConsole$.WriteLine($end$);]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

This list describes what's in the Header element:
Title: Shows up on the context menu.
Shortcut: The key combination you can type for IntelliSense.
Description and Author: Show up in the tooltip when you mouse over the snippet in Visual Studio.
SnippetType: Defines which menus the snippet appears on. The most common types are Expansion
    and SurroundsWith. Expansion means that it inserts the text. SurroundsWith means that it's placed
    above and below the selection.

The Snippet element is where the work is done. In the cw.snippet examplethere are two elements in
Snippet: Declarations and Code. Declarations declares the variables, and Code is what gets inserted.
Within these, these statements are true:
The Literal element describes a variable that will be used in the creation of the snippet.
In this case, Function tries to get the simplest version of the System.
     Console namespace given the current constraints, and ID names it SystemConsole.
The Code element specifies the language and then puts the actual code in place.

If you want to make your own snippet, I suggest that you start with one of the samples provided in
the Visual Studio install. You can just start from scratch too — if you wish, you can create an XML
file and give it a .snippet
file extension — but I think these things are best done iteratively.

Deploying snippets
To deploy a snippet of your own, use the Code Snippets Manager. The manager is found on the Tools
 menu and looks like the one shown in Figure 3-3.
 
Figure 3-3:The Code Snippets Manager.

Adding a new snippet this way is fairly simple. After you create your snippets file, click the Import
button, and select the .snippet file. It's placed in the selected folder, so make sure you have the snippet
 folder highlighted.

The Add and Remove buttons in the Manager refer to directories, not files. Use them to make new
snippet folders. The Search Online feature just searches Help for IntelliSense Code Snippets.

Sharing snippets
Sharing a snippet is a more complicated act than it should be. One would think that you could just
 create a .snippet file, send it to someone, and that would be that. It isn't so.

I should amend that — it is so if you are just sending it to a friend — then it is just a matter of using
the Manager. On the other hand, if you are making a package of snippets for a group to install, you
get to the nitty-gritty.
A snippet sharing escapade has three components:
The .snippet file itself: This topic is discussed in the preceding section.
The .vscontent file that lists the snippets (even if there is only one):

The .vscontent file is one with a listing of snippets in a package. It consists of multiple Content
elements that describe the various files in the package. For instance, here is the .vscontent file that
would be used for the previous Console.Writeline example.

<VSContent xmlns="http://schemas.microsoft.com/
developer/vscontent/2010">
<Content>
<FileName>cw.snippet</FileName>
<DisplayName>cw</DisplayName>
<Description>Console.Writeline</Description>
<FileContentType>Code Snippet</FileContentType>
<ContentVersion>3.0</ContentVersion>
<Attributes>
<Attribute name="lang" value="csharp"/>
</Attributes>
</Content>
</VSContent>

This gives you two files in the package — the snippet and the content file. These need to be packaged
 in a .vsi file, and then distributed.
The .vsi file to package it all together: The .vsi file is a Zip file with a new extension. To make it,
literally zip your folder of snippets with the vscontent file and change the file extension from .zip to
.vsi.
Visual Studio users can double-click .vsi files in order to have the vstudio installer handle them.
The command line can also be used for more in-depth installs. The complexity of the system on the
snippet developer side makes sense when you consider that the end user ends up with a better experience.

No comments :

Post a Comment