Click here to Skip to main content
Click here to Skip to main content

Extending Visual Studio Part 1 - Creating Code Snippets

, 14 Apr 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Learn how to extend Visual Studio 2010 by creating custom code snippets.

Extending Visual Studio

This article is part of the series 'Extending Visual Studio'.

Part 1 - Creating Code Snippets
Part 2 - Creating Addins
Part 3 - Item Templates  

Introduction

In this series of articles, I am going to show you some of the fantastic ways that you can extend Visual Studio. Visual Studio is amazingly extensible, there are a number of ways that you can build upon it.

In this article, we'll start with one of the simplest ways to extend Visual Studio - creating Code Snippets.

What are Code Snippets?

A code snippet is a chunk of pre-formatted code that is dropped into the editor, either inserting a new block of code or wrapping an existing block. The snippet can contain some reusable segment of code. As an example, create an empty class and type in 'ctor'. As you type, intellisense will narrow down the choices for you, here we can see a snippet:

extendingvisualstudio1/SnippetScreenshot.png

Now press tab twice. The 'ctor' snippet creates the class constructor. You can create all sorts of snippets, let's get started.

The Brief

First let's define what we want the snippet to do. Look at the code below - here you can see two Notifying Properties from my Apex Library.

private NotifyingProperty firstNameProperty =
    new NotifyingProperty("FirstName", typeof(string), string.Empty);

public string FirstName
{
    get { return (string)GetValue(firstNameProperty); }
    set { SetValue(firstNameProperty, value); }
}

private NotifyingProperty secondNameProperty =
    new NotifyingProperty("SecondName", typeof(string), string.Empty);

public string SecondName
{
    get { return (string)GetValue(secondNameProperty); }
    set { SetValue(secondNameProperty, value); }
}

I use these properties all over my code - so this is the ideal candidate for a code snippet. The majority of the code is the same in every case, the only thing that will change is:

  • The name of the property
  • The type of the property

Creating the Snippet

In the example project, I have added the snippet files to a blank C# project - however, we don't need any specific type of project to create a snippet, it's just a bit of XML. Create a new XML file and rename it InsertApexNotifyingProperty.snippet. Use the boilerplate below to get started.

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

        <!-- The header contains information describing the snippet. -->
        <Header>
          
          <!-- The Title of the snippet, this will be shown in the snippets manager. -->
          <Title>Insert Notifying Property</Title>
          
          <!-- The description of the snippet. -->
          <Description>Inserts an Apex Notifying Property.</Description>
          
          <!-- The author of the snippet. -->
          <Author>Dave Kerr</Author>
          
          <!-- The set of characters that must be keyed in to insert the snippet. -->
          <Shortcut>apexnp</Shortcut>
          
          <!-- A URL for more help. -->
          <HelpUrl>http://apex.codeplex.com</HelpUrl>
          
          <!-- The set of snippet types we're dealing with - either Expansion or -->
          <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
          </SnippetTypes>          
          
        </Header>
      
        <!-- Now we have the snippet itself. -->
        <Snippet>
                    
            <!-- Sepecify the code language and the actual snippet content. -->
            <Code Language="CSharp" Kind="any">
                <![CDATA[

                    // My first snippet!
                    
                ]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

You may find this boilerplate useful - a link to it is at the top of the page.

Note for Visual Basic: If you're creating a VB code snippet, the in the 'Code' tag, change 'Language' from 'CSharp' to 'VB'. 

So what have we done here? Just created some summary data for the snippet and a very basic piece of content.

Installing the Snippet

Choose 'Tools > Code Snippet Manager' and then select 'Import' - browse to your newly created snippet. Now in any code window, you can key in 'apexnp' and you get the comment '// My first snippet'. Not bad!

extendingvisualstudio1/CodeSnippetsManager.png

Adding Parameters

Let's generalise the code that we want to create. Insert the code below into the snippet file in the 'Code' tag.

private NotifyingProperty PropertyNameProperty =
    new NotifyingProperty("PropertyName", typeof(PropertyType), default(PropertyType));

public PropertyType PropertyName
{
    get { return (PropertyType)GetValue(PropertyNameProperty); }
    set { SetValue(PropertyNameProperty, value); }
}

I've highlighted the key points in red and blue - there are actually only two segments of code we need to replace, the PropertyName and PropertyType strings.

Modify the snippet definition so it looks like this:

<!-- Now we have the snippet itself. -->
<Snippet>

  <!-- Create any declarations that we use in the snippet. -->
  <Declarations>
    <Literal>
      <ID>PropertyName</ID>
      <ToolTip>Enter the property name</ToolTip>
      <Default>PropertyName</Default>
    </Literal>
    <Literal>
      <ID>PropertyType</ID>
      <ToolTip>Enter the property name</ToolTip>
      <Default>PropertyType</Default>
    </Literal>
  </Declarations>

  <!-- Sepecify the code language and the actual snippet content. -->
  <Code Language="CSharp" Kind="any">
    <![CDATA[
                private NotifyingProperty $PropertyName$Property = 
                  new NotifyingProperty("$PropertyName$", typeof($PropertyType$), default($PropertyType$));
                
                public $PropertyType$ $PropertyName$
                {
                  get { return ($PropertyType$)GetValue($PropertyName$Property); }
                  set { SetValue($PropertyName$Property, value); }
                }
            ]]>
  </Code>
</Snippet>

We've added two Literal tags. Literals are replaced in each segment of code. The first part of a literal is the ID - this is what we must surround in dollar signs in the Code tag. The second part is the tooltip that is displayed. The final part is the default value for the snippet. Let's see our updated snippet in action.

extendingvisualstudio1/FinalScreenshot.png

Perfect! It all works exactly as it should.

Installing the Snippet

We can create an installer for the snippet by first creating another XML file named .vscontent. It should look like this:

<?xml version="1.0" encoding="utf-8" ?>
<VSContent xmlns="http://schemas.microsoft.com/developer/vscontent/2005" >
  <Content>
    <FileName>InsertApexNotifyingProperty.snippet</FileName>
    <DisplayName>Insert Apex Notifying Property</DisplayName>
    <Description>Inserts an Apex Notifying Property</Description>
    <FileContentType>Code Snippet</FileContentType>
    <ContentVersion>2.0</ContentVersion>
    <Attributes>
      <Attribute name="lang" value="csharp"/>
    </Attributes>
  </Content>
</VSContent>

Note for Visual Basic: If you need to install a Visual Basic snippet - use 'vb' as the 'value' part of the 'attribute' tag. 

The final thing to do is add the .vscontent and .snippet file into a new *.zip file and rename it from zip to vsi. This creates a VSI installer - double click on it and you get the below:

extendingvisualstudio1/ContentInstaller.png

Important Nnte: If you get an exception when running the installer, do you have the Windows Phone Developer Toolkit installed? If so, post on http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/6504fde1-b84d-4e4f-80f9-54f6a5596fc0/ and kick up a stink so that Microsoft fixes this bug!

If you need to display publisher information, you must sign the VSI file, some more details are available here: http://msdn.microsoft.com/en-us/library/ms246580.aspx.

Final Thoughts

I hope you enjoyed this article, keep your eyes on my blog for news of the next in the series, www.dwmkerr.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dave Kerr
Software Developer
United Kingdom United Kingdom
Follow my blog at www.dwmkerr.com and find out about my charity at www.childrenshomesnepal.org.
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 4 PinmemberMember 391382325-Dec-12 21:14 
GeneralRe: My vote of 4 PinmvpDave Kerr28-Dec-12 2:07 
QuestionVery usefull post but how to make it dynamic? Pinmembermabanza1-Aug-12 8:42 
GeneralRe: Very usefull post but how to make it dynamic? PinmvpDave Kerr6-Aug-12 5:59 
GeneralRe: Very usefull post but how to make it dynamic? Pinmembermabanza8-Aug-12 4:02 
GeneralRe: Very usefull post but how to make it dynamic? PinmvpDave Kerr8-Aug-12 4:24 
GeneralRe: Very usefull post but how to make it dynamic? Pinmembersandeshjkota13-May-13 0:46 
GeneralMy vote of 5 PinmemberMihai MOGA12-May-12 19:30 
GeneralRe: My vote of 5 PinmvpDave Kerr6-Aug-12 5:55 
GeneralMy vote of 5 Pinmemberrctaubert14-Apr-12 4:11 
GeneralRe: My vote of 5 PinmvpDave Kerr6-Aug-12 5:55 
QuestionLanguage type Pinmemberrctaubert13-Apr-12 8:08 
AnswerRe: Language type PinmvpDave Kerr14-Apr-12 1:01 
AnswerRe: Language type PinmvpDave Kerr14-Apr-12 1:04 
GeneralRe: Language type Pinmemberrctaubert14-Apr-12 4:10 
QuestionDon't suppose you know PinmvpSacha Barber4-Feb-12 0:48 
AnswerRe: Don't suppose you know PinmvpDave Kerr4-Feb-12 0:54 
GeneralRe: Don't suppose you know PinmvpSacha Barber4-Feb-12 1:55 
GeneralRe: Don't suppose you know PinmvpDave Kerr4-Feb-12 2:40 
GeneralRe: Don't suppose you know PinmvpSacha Barber4-Feb-12 6:46 
AnswerRe: Don't suppose you know PinmemberMike Hankey4-Feb-12 6:47 
GeneralRe: Don't suppose you know PinmvpSacha Barber4-Feb-12 7:00 
QuestionFound new snippet to vsi converter PinmemberMember 432946910-Dec-11 11:56 
AnswerRe: Found new snippet to vsi converter PinmvpDave Kerr4-Feb-12 0:54 
GeneralUseful... Pinmemberjanhavib7-Dec-11 20:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411028.1 | Last Updated 14 Apr 2012
Article Copyright 2011 by Dave Kerr
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid