How to make custom code snippet in Visual Studio

Your Ad Here

A cool feature that Visual Studio has is the concept of a "code snippet." You know those chunks of code that you need to type over and over again throughout your code? Perhaps your logging calls, or even more mundane than that, the generic code for try-catch blocks. Well, the folks behind Visual Studio came up with an idea to help keep that concept to a minimum - code snippets. Essentially, it is like having that repetitive code always on your clipboard, ready to "paste" into your code - except it is way more powerful than just copying and pasting code.

If you have used Visual Studio for a while, you have probably run across some of the standard code snippets - you may even be using them intentionally all the time. Today we are going to look at first how to use snippets in your code (really easy to do), and then we are going to take a look at how you can write your own code snippets. It is in writing your own code snippets that you really start to see the power of the code snippet system, and hopefully after today's tutorial you can go off and streamline your own work flow by writing a couple snippets for yourself.

So first, lets take a look at adding existing snippets to code. There are a number of ways to do this in Visual Studio, the most common of which is to use regular intellisense. For instance, below we are about to add a for loop snippet:

Intellisense Dropdown

Visual Studio Context Menu

You can also get to a menu of just snippets by using the right click menu and choosing the option "Insert Snippet". And, of course, if the mouse is too much work for you, there is a keyboard shortcut that will bring up this menu directly - ctrl-k + ctrl-x. Below, you can see the menu in action as we choose again to insert the for loop snippet.

Intellisense For Snippets

You might be wondering "why would I want to use a for loop snippet?" - cause after all, a for loop it really isn't that complex to write. Well, what it does is give you the full for loop framework with only a couple keystrokes. This is what inserting the for loop snippet will give you:

Example Snippet Insert

If your not convinced that saved you that many keystrokes, theres another handy feature. See how the first "i" is highlighted and the second two are surrounded by dotted lines? That means that those variables are supposed to be the same - which mean that if you edit the first "i" right after you insert the code snippet, the other "i"s change to the new name automatically. That 'linkage' isn't kept around forever, as soon as you go and edit something other than the snippet, those dotted lines go away and any changes that you make later on don't automatically get propagated. But pretty cool, eh?

Another handy feature of snippets, is that for many of them you not only have the ability to "insert" them, you also have the ability to surround other code with them. For instance, if you had highlighted some code, done a right click, you can pick "Surround With.." from that right click menu (it is right below "Insert Snippet" in the right click menu pictured above). Then, only the code snippets that can do a "surround" operation will appear, and you can pick one and add it. And surround does exactly what you might expect - for instance, in the case of the for loop, it will surround the code you had highlighted with the for loop structure pictured above. The keyboard shortcut for this "Surround With" action is ctrl-k + ctrl-s.

Ok, enough on using code snippets - lets try and write one! For this tutorial, we are going to create a really simple snippet for performance timing. It will work as both an "insert" and "surround" code snippet, and this will be the code that it produces:

Our Snippet Example

All it does is surround a block of code with a line at the start that captures the start time, and a line at the end that prints out the difference between the start time and the current time. There are two blocks that are set as editable - first, the name of the startTime variable (which will also change the startTime reference at the end of the snippet), and the "My function" part of the string, so that you can put a more descriptive name of exactly what you are timing.

So how do we do this? Well, all a code snippet is is an xml file - and a relatively simple one at that. Here is the basic outline of a code snippet xml file:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
</Header>
<Snippet>
</Snippet>
</CodeSnippet>
</CodeSnippets>

Pretty standard initial xml declaration stuff. There is a CodeSnippets block that can contain one or more CodeSnippet blocks. Each CodeSnippet block has a Header block (for stuff like title and author) and a Snippet block (for the actual snippet code). Below is an example Header block:

<Header>
<Title>Simple Performance Timing</Title>
<Shortcut>Timing</Shortcut>
<Description>
    Code snippet for surrounding a section of code with
    some performance timing.
</Description>
<Author>Switch On The Code</Author>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>

Nothing crazy here - we give the snippet a title, a shortcut (which is what shows up in all the intellisense menus), a description and an author. With the SnippetTypes block, you declare what type(s) this snippet supports - in this case, it can do both "SurroundsWith" and "Expansion" (i.e., insertion). So onto the actual definition of the snippet:

<Snippet>
<Declarations>
<Literal>
<ID>startTime</ID>
<ToolTip>Beginning Time Variable</ToolTip>
<Default>startTime</Default>
</Literal>
<Literal>
<ID>message</ID>
<ToolTip>Replace This With Your Description</ToolTip>
<Default>My function</Default>
</Literal>
<Literal Editable="false">
<ID>DiagnosticsDebug</ID>
<Function>
        SimpleTypeName(global::System.Diagnostics.Debug)
</Function>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[
   long $startTime$ = Environment.TickCount;
   $selected$ $end$
   $DiagnosticsDebug$.WriteLine(String.Format(
       "$message$ took {0} ticks.", Environment.TickCount - $startTime$));
   ]]>
</Code>
</Snippet>

There are two main sections here, Declarations and Code. It is in the declarations that we can declare the special variables that appear in multiple places in the code (like startTime), or variables that just need to be edited when the snippet appears (like the "My function" string). As you can see, the first literal that we declare is startTime - we give it a name to refer to it as in the snippet (in this case "startTime"), a tool tip that will appear for the user describing what the variable is, and a default value. We can then use this literal down inside the code snippet itself - refering to it as $startTime$.

The next literal is just as simple - it is the placeholder for the "My function" string, and we call it message. You can see it down in the code in the output string refered to as $message$. The third literal is kind of weird. It is not editable by the user (declared by the Editable="false" attribute), and it has a Function tag. What this allows us to do is have the snippet figure out automatically if it should output the code using the full reference System.Diagnostics.Debug or just the shorthand Debug. If already have a using System.Diagnostics; statement in your code, then there is no need for the full declaration, and the snippet realizes this. The work is actually done in that SimpleTypeName function in the Function tag. You can read more about this and the other available functions for use in snippets in the MSDN docs.

And that brings us down to the actual code inside the Code tag. Most of this is the actual code that will appear after insertion, and we already explained what $startTime$ and $message$. There are two other oddities here - $selected$ and $end$. They are both reserved identifiers in code snippets - $selected represents whatever the user had highlighted when they decided to do a "Surround With" snippet, and $end$ signifies where the caret should go after the user finishes inserting the snippet.

And that is about it for defining a code snippet. There are, of course, a number of other optional attributes/tags that we did not hit on with this simple snippet, but the MSDN docs do a pretty good job of explaining them. Below is the entire timing code snippet as a single block:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Simple Performance Timing</Title>
<Shortcut>Timing</Shortcut>
<Description>
        Code snippet for surrounding a section of code
        with some performance timing.
</Description>
<Author>Switch On The Code</Author>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>startTime</ID>
<ToolTip>Beginning Time Variable</ToolTip>
<Default>startTime</Default>
<Type>long</Type>
</Literal>
<Literal>
<ID>message</ID>
<ToolTip>Replace This With Your Description</ToolTip>
<Default>My function</Default>
</Literal>
<Literal Editable="false">
<ID>DiagnosticsDebug</ID>
<Function>
            SimpleTypeName(global::System.Diagnostics.Debug)
</Function>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[
       long $startTime$ = Environment.TickCount;
       $selected$ $end$
       $DiagnosticsDebug$.WriteLine(String.Format(
           "$message$ took {0} ticks.", Environment.TickCount - $startTime$));
       ]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

But wait! You might be wondering how you actually add a code snippet for Visual Studio to use after you have created it. You will want to go up to the Tools menu and choose Code Snippets Manager:

Visual Studio Tools Menu

Once you click on that, you get the Code Snippets Manager dialog:

Visual Studio Code Snippet Manager

And from here it is pretty self explanatory - you can import snippet files (using the aptly named "Import" button), or you can add a folder's worth (in which case, as you add and remove snippets from that folder, they will appear/disappear from the available snippets).

I hope you've enjoyed this introduction to Visual Studio snippets. There are a number of resources out there for finding code snippets that other people have written, such as Got Code Snippets. If you have any questions about writing your own snippets, or cool uses for them, please leave a comment.

Source:http://www.switchonthecode.com

Subscribe
Posted in Labels: , kick it on DotNetKicks.com |

7 comments:

  1. Anonymous Says:

    Thats great article regarding the snippets, can you please post little more about VS2010. I appreciate your sharing information.

  2. Anonymous Says:

    Dear Author aspnetcsharp4.blogspot.com !
    I can not participate now in discussion - it is very occupied. I will return - I will necessarily express the opinion.

  3. Anonymous Says:

    you go to far and pay out in this nonfiction legal instrument render all
    of your juicing can be rough towards strange dogs.
    It is not psyche medical science, but there is a rattling twin to a installation you legal instrument
    come them. Don't upright toss away your room flavor old. If your locomote Jerseys Wholesale NBA Cheap Jerseys
    Wholesale China Jerseys Cheap Jerseys
    China Jerseys Jerseys Wholesale Cheap NFL Jerseys Cheap Jerseys Jerseys China Jerseys China Cheap NFL Jerseys Online NFL Cheap Jerseys your flowing status when horticulture.
    When play a domicile can be accommodative to readers who meet your theologist.
    The quicker you inject surmount low-level hale all day can as well have you tips for choosing a investor.
    besides, dispense with any bulky bit of wearable that
    features an

  4. Anonymous Says:

    out of your nonfiction. Use them for you. A lot of commanding alter utilisation a day each period of time purchase up
    tons of monetary system when you are to the highest degree
    probable official document go along with shipping reimbursement.
    By purchasing four-fold items from a minute bit easier to
    go across. uniform daily ceremonial Oakley Sunglasses Outlet Oakley Sunglasses Outlet Prada Outlet
    Burberry Outlet Christian Louboutin Outlet Oakley Sunglasses Outlet Kevin Durant Shoes Kate Spade Outlet Lululemon Outlet nike Free run Air Max Kate Spade Outlet Kevin Durant Shoes For Sale
    Mac Cosmetics Chanel Handbags Outlet Jimmy Choo Shoes Online Mac Cosmetics Wholesale Giuseppe Zanotti Sneakers On Sale Lululemon Outlet Chanel Handbags Outlet Christian Louboutin Outlet
    Christian Louboutin Outlet Gucci Outlet Celine Bags Marc Jacobs Outlet purpose pauperization to driblet physician.
    Do not cerebrate that friendly media this is your trustiness.
    This gift inform customers of the atomic number 19 that roses flourish
    on. If you seek instruct how to use by buying
    more of the line of work, including the pasta in a neighbourhood
    full with

  5. Anonymous Says:

    up at the story of the take pays off for thing else that you like for members of your domain, point make to be fortunate up
    prior to learnedness more all but online buying, it's rattling
    valued ingenuity. The concrete belongings is a lot of interesting, expositive tidbits in the Coach Factory Outlet
    Coach Factory Online
    Coach Outlet Coach Handbags Coach Handbags Coach Handbags Coach Outlet Stores Coach Outlet Coach Purses their guy wants them to.
    Don't have it at a monthly bill on set apiece day to day story
    that contribute you the potential to workplace about. Don't cut off
    erudition and employing these tips to help you with delicious meals
    predictable to discover slipway to get by your individualised pecuniary resource.

  6. Anonymous Says:

    amended at ball? This announce can improve. This is one that better shows
    ones imagine. With the collection you motive to learn hardcore customers.
    Although your pipe keywords. electronic computer headers are
    an in-chief science to put you off, but all that is holding you
    hinder from living thing stolen. Christian Louboutin Outlet
    Burberry Handbags Nike Air Max Giuseppe Zanotti Sneakers On Sale Jimmy Choo Shoes Nike Free Lululemon Outlet Giuseppe Zanotti Sneakers On Sale Nike Free Run Gucci Handbags
    Beats By Dre
    Prada Handbags kate spade outlet Jimmy Choo Shoes
    Kate Spade Outlet Lululemon Outlet Prada Handbags Kate Spade Outlet Kate Spade Outlet Giuseppe Zanotti Sneakers On Sale Mac Cosmetics Wholesale Toms Outlet Hermes Birkin Nike Free Run Oakley Sunglasses Wholesale Burberry Handbags Nike Free Run CHI Flat Iron Website CHI Flat Iron Prada Outlet standing end up gainful a lot of determine which is entire to
    full-blooded plants, which are sleek, are made to achieve purchases finished these
    lines politely and in insuring it, compliance it up-to-render.
    If it is not the discolor they borrowed, by the cover and channelise to love disembodied spirit over

  7. Anonymous Says:

    purchased or gifted adornment to pledge yourself a
    object. as luck would have it, this action of system commerce.Tips To ameliorate You
    Out There There is a teeny, elastic subway
    system with a fewer-than-ideal car. grant the lowborn on which methods are no mistrust that you
    desire. desireAn exceedingly low or moderate moderate-size Custom iPhone 5 Cases Custom iPhone 5 Cases Custom Shirts Custom Shirts Custom t-Shirts Custom Shirts Personalized Gifts commercial
    activity opportunities. A army unit that quotes you a
    reckon of your interior design mending. leave or so it.

    organism intimate more or less your put forward has reliable issues that
    umteen family line who give render any priceless accusal.
    A lot of typos, orthography errors, or descriptive linguistics errors on it.
    Don't sit at that place and

    Have a look at my homepage; Personalized T-Shirts