Home MVC Storefront

Save Your Wrists With Geek Performance Enhancers: CodeSnippets and Toolbox Items

CodeSnippets are something we use every day, and from what I know, they are severely overlooked. In this post I'll show you how to create your own to do the things you do a lot of, and also how you can use your Toolbox to store the things you seem to write over and over again.

 

Snip This
I think CodeSnippets are a bit misnamed - if anything they are code macros that offer lots of bang for your typing dollar. Many of us suffer from weak wrists (well, those of use who weren't sailors) and that is due, in part, to the ridiculous amount of typing associated with our jobs. Learning to use Snippets and your Toolbox will greatly, greatly speed up your day.

If you don't know what a snippet is - open up Visual Studio and type "prop" and then hit the TAB key:

snip1

You'll see a property declaration open up, and your cursor will move straight to the entry points you need to fill in. You can tab between these entry points until you have a full-blown property declaration (this is using Visual Studio 2008 with the new sugary Property declaration):

snip2

Note the "torn page" icon of "prop" in the first image - if you scroll the list there you'll see a whole lot of Snippety Love at your finger tips. Here's a list of all of them if you want to know more.

 

Gimme Somma That Snippy Love!
I've been working a lot with the new MVC bits and one thing that's annoying is having to type the same stuff, over and over. One in particular is the Controller Action:

action1

Rather than type this over and over, I decided to make a snippet. It's very very simple it turns out and you can use Visual Studio to edit them. If you want to take a look at your installed snippets, you can - they are stored (usually) in C:\Program Files\Microsoft Visual Studio 9.0\VC#\Snippets\1033\.

To learn snippets, I cracked open the C# snippets folder, and opened up the "prop.snippet" by double-clicking and hitting Save As (immediately, do I didn't forget) and saving it somewhere else on my hard drive:

prop

Here's the code for prop.snippet:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>prop</Title>
            <Shortcut>prop</Shortcut>
            <Description>Code snippet for an automatically implemented property</Description>
            <Author>Microsoft Corporation</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Property type</ToolTip>
                    <Default>int</Default>
                </Literal>
                <Literal>
                    <ID>property</ID>
                    <ToolTip>Property name</ToolTip>
                    <Default>MyProperty</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[public $type$ $property$ { get; set; }$end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

It's basically very, very simple XML with string replacement. Each property is declared in the <Snippet> section, and the code itself is declared in the <Code> section. Visual Studio, when it invokes a snippet, travels the code and looks for the first "unset" instance of any $-prefixed stub, and then creates a replacement entry point for you. When you update that point, all the like-named points are updated.

This seemed pretty simple to get and so to try it out, I decided to create a simple MVC Action snippet:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>MVC Controller Action</Title>
            <Shortcut>mvc_action</Shortcut>
            <Description>Creates an MVC Action method for a controller</Description>
            <Author>Rob Conery, SubSonic</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
        <Literal>
          <ID>name</ID>
          <ToolTip>The method name</ToolTip>
          <Default>Index</Default>
        </Literal>
            </Declarations>
            <Code Language="csharp">
        <![CDATA[
        [ControllerAction]
        public void $name$(){
        
        }
        $end$
      ]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

All I had to do here was

  1. Change the Title to read nicely
  2. Set a shortcut that I would remember (mvc_action)
  3. Add a description and my name
  4. Create my "replacement" property - in this case it's just the name of the Action() - so I called it "name"
  5. Finally, I add in my code in the <Code tag (using CDATA).

Simple stuff!

Loading Your Snippets
Now that you've made your snippet, it's time to let Visual Studio know about it. You can manage your snippets by opening Tools/Code Snippets Manager. This will open up a dialog and you'll see something like this:

snippetmgr

A bit of warning here - the Snippet manager is a bit wonky. You can remove just about any folder, but you can't ever delete a snippet (for some reason). You'll want to be sure NOT to "Import" here - this imports snippets one by one. Instead keep a folder somewhere on your drive (I have mine - "SubSonicSnippets" - in my SubSonic project folder).

To add your folder in, click "Add" and select your folder. You snippets will be read:

snippetmgr2

Be sure, at this point, that you've named everything properly. Once Visual Studio loads them, you'll have to Remove/Add/Restart VS to see them in your IDE.

If you want to play around with some MVC snippets I made - you can get them here. Note: this is an old image and I've removed some of the snippets because the MVC project template will cover much of this for you.

 

Turn That Toolbox Into Something Useful
I don't use the designer when working with ASP.NET. This is just my preference as I've had... issues... with it (and the White Screen of Pain) and Visual Studio 2005. To that end I've learned to love the Toolbox's ability to store text snips for things I write a lot (and that I don't have snippets for).

The first thing to do is right-click on the Toolbox and click "Add Tab", and then give it a meaningful name. You probably want to avoid "My Stuff" since having extra tabs as time goes by is helpful.

Add things to your new tab is as simple as Copying your code, right-click on the Toolbox and click "Paste". Then right click on your new entry and select "Rename" - then call it something meaningful:

toolbox

I hate having to remember how to setup my Web.Config for Membership (Web.Config here), and also how to add Routes for MVC. Also, I like to use jQuery so I made a little text bit for that too (snippets don't work on a Web page in Source view unless you're inside a code block <%%>).

Hope you find these tips useful!

Ayende Rahien avatar
Ayende Rahien says:
Friday, December 07, 2007
You need to fix the awkward design, so you wouldn't need to use the tool to get it workin.

Troy Goode avatar
Troy Goode says:
Friday, December 07, 2007
Hi Rob, Thanks for the easy example of how to create custom snippets. I also am averse to design-view, and was completely unaware that the toolbox could be used for code snippets. I'm looking forward to trying out the MVC snippets you posted whenever the new framework is posted... (checks his watch... end of the week, right?) On an unrelated note, ScottGu posted a comment yesterday stating that the SubSonic Migrations project was recently released. I haven't seen anything about this so I'm assuming Scott got a bit ahead of himself there? The link to the comment is: http://weblogs.asp.net/scottgu/archive/2007/12/06/asp-net-mvc-framework-part-3-passing-viewdata-from-controllers-to-views.aspx#5413101 While we're on the subject of migrations, have you checked into RikMigrations (http://www.codeplex.com/RikMigrations/)? I have been using it for a week or so and barring a few bugs the author is hammering out, it has been quite nice. Troy

Troy Goode avatar
Troy Goode says:
Friday, December 07, 2007
I just noticed that the link to Scott's comment I posted above doesn't appear to actually scroll you to the comment itself. I looked at the source and it appears Scott's template does not contain any anchors for the indivual comments. If you search that page for the word "migration" the comment is the first one you'll find on that post though.

Jeff Kwak avatar
Jeff Kwak says:
Saturday, December 08, 2007
Another tip for saving your wrists is to use slickrun (http://www.bayden.com/SlickRun/) and make yourself a little "magic word" like "snip" that opens a file explorer to your snippet folder. That way you can just double-click one of the .snippet-s for editing or when you want a template to create a new one (opens it up in a VS editor).

cathal avatar
cathal says:
Saturday, December 08, 2007
If you're creating a bunch of snippets the Code Snippet Editor for Visual Basic 2005 (http://msdn2.microsoft.com/en-us/vbasic/ms789085.aspx) is a handy tool -don't be frightened by the name, it works for you curly-brace addicts also.

Thomas Eyde avatar
Thomas Eyde says:
Saturday, December 08, 2007
Didn't they provide a snippet editor in 2008?

Nick Parker avatar
Nick Parker says:
Sunday, December 09, 2007
The Pitfalls of Concession... The Pitfalls of Concession...

Vin avatar
Vin says:
Monday, December 10, 2007
Hey Rob, this isnt related to the blog post, but i was wondering if you could share your VS Environment Settings Thanks

Jav avatar
Jav says:
Monday, December 10, 2007
Thanks for sharing this rob, I found this site which is an online code snippet directory, thought will go well with this post. http://www.codekeep.net/

adminjew avatar
adminjew says:
Monday, December 10, 2007
Great stuff thanks rob

Rupak Ganguly avatar
Rupak Ganguly says:
Friday, December 14, 2007
For some reason, I have to press TAB twice to get the snippet expanded. I am using the VS 2008 RTM Team Suite Edition. Any idea why?


Search Me
Subscribe

Popular Posts
 
My Tweets
  • @codinghorror: I may be weird but I don't ask my cats to write my blog entries :p.
  • @blowdart sure! Wanna come on and do a webcast with me - plugging CardSpace in?
  • People are very, very weird. Skypecasts are creepy.
  • Is Rob Howard trying to tell us something? http://www.rob-howard.net/
  • New storefront posted- all about OpenID :) http://tinyurl.com/5rkgux
  About Me



Hi! My name is Rob Conery and I work at Microsoft on the ASP.NET team. I am the Creator of SubSonic and was the Chief Architect of the Commerce Starter Kit (a free, Open Source eCommerce platform for .NET)

I live in Kauai, HI with my family, and when my clients aren't looking, I sometimes write things on my blog (giving away secrets of incalculable value).