Saturday, March 30, 2013

Code Snippets

Today I’m going to write about code snippets. Code Snippets have been in use since Visual Studio 2005. I knew about them then, but didn’t really have a need to create my own, so I eventually forgot about them until about 4 months ago, when I found I had a really, really, really good use for them!

But, let’s back up a bit … what is a code snippet? Surely you have taken advantage of them without realizing it. Think about loops: just type the word for and hit tab twice. Voila, the entire for loop is stubbed out for you to fill in the details:

for (int i = 0; i < length; i++)
{
    
}

Likewise, try foreach and hit tab twice. Here’s what you get:

foreach (var item in collection)
{
    
}

If you haven’t already discovered this feature, you’re in for a treat. Try it yourself right now, you’ll love it! The “for” and the “foreach” are called shortcuts. If you don’t know a shortcut, or can never remember the one you want or you simply want to explore, all you have to do is position your mouse in your code where you want to insert a code snippet, then right-click and choose “Insert Snippet …” and find what you’re looking for or something else that looks interesting.

Now for the good part … you can create your own code snippets to do simple “templates” (like those for loops above) or more complicated “templates'”. I had big chunks of semi-repetitive code; groups of methods that needed to be put into each new module written (a new module to interface with each different vendor product, so each bit of code would use different parameters in the methods).

I wrote a big long snippet for that use (and it works beautifully) and after that I was hooked on creating snippets! I regularly use 4 or 5 that I created in every new module I have to write. It speeds up my coding tremendously, not to mention gets rid of any possibilities for screwing up and leaving out something important.

First, here’s a link for future reference if you need to know more than I can tell you in this short blog:

http://msdn.microsoft.com/en-us/library/vstudio/ms165393(v=vs.100).aspx

Next, let me show you what the file looks like for those simple snippet examples I showed above. Let’s just do the “foreach” one. Here’s the entire foreach.snippet file … it’s just XML:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>foreach</Title>
            <Shortcut>foreach</Shortcut>
            <Description>Code snippet for foreach statement</Description>
            <Author>Microsoft Corporation</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
                <SnippetType>SurroundsWith</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Type of object in the collection to iterate through</ToolTip>
                    <Default>var</Default>
                </Literal>
                <Literal>
                    <ID>identifier</ID>
                    <ToolTip>Identifier that represents the element in the collection</ToolTip>
                    <Default>item</Default>
                </Literal>
                <Literal>
                    <ID>collection</ID>
                    <ToolTip>Name of collection or array to iterate through</ToolTip>
                    <Default>collection</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[foreach ($type$ $identifier$ in $collection$)
    {
        $selected$ $end$
    }]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

So, how does this work? Notice the very last thing in the XML, this is the part that contains the code “template” that will become the snippet (all the stuff contained within the CDATA).

foreach ($type$ $identifier$ in $collection$)
{
    $selected$ $end$
}

All the things delimited by the “$” are what will get replaced in the IDE when you hit tab twice. The Declarations in the beginning of the XML describe what each of these literals should be, along with the defaults that are initially displayed in your IDE. The $selected$ and $end$ are special literals. Here’s what MSDN has to say about them:

Two reserved words are available for use in the text of the Code element: $end$ and $selected$. $end$ marks the location to place the cursor after the code snippet is inserted. $selected$ represents text selected in the document that is to be inserted into the snippet when it is invoked. For example, if you had:

$selected$ is a great color. I love $selected$.

and the word "Blue" was selected when you invoked the template, you would get:

Blue is a great color. I love Blue.

All other $ keywords are dynamically defined in the <Literal> and <Object> tags.

What they mean by “selected text” is when you highlight some text in your code, then right-click and choose “Surround With …” and then pick a snippet to use.

Here’s something I wrote to help out a guy on the MSDN forums (see the thread here, if you’re interested: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/3198baaa-0250-49c6-bad5-f5242a2b5852). He wanted to have a static property that was set by calling a method … but, he didn’t want to have to run that method every time he used the property. And, he used these types of properties everywhere, so he didn’t want to have to type the same monotonous stuff over and over again. To me, it sounded like the perfect use for a code snippet.

Here’s the GetPropOnce.snippet I wrote for that:

<?xml version= "1.0" encoding="utf-8" ?>
<CodeSnippets xmlns = "http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format ="1.0.0">
    <Header >
        <Title>GetOnce Property</Title>
        <Description>Property that is only gotten once, checking backing variable for null</Description>
        <Shortcut>propgetonce</Shortcut>
    </Header>
    <Snippet>
        <Declarations>
            <Literal>
                <ID>type</ID>
                <Default>int</Default>
            </Literal>
            <Literal>
                <ID>PropertyName</ID>
                <Default>MyProperty</Default>
            </Literal>
            <Literal>
                <ID>MethodName</ID>
                <Default>DoSomething</Default>
            </Literal>
            <Literal>
                <ID>DefaultValue</ID>
                <Default>DefaultForNull</Default>
            </Literal>
        </Declarations>
        <Code Language="CSharp">
            <![CDATA[
                private $type$? m_$PropertyName$ = null;
                public $type$ $PropertyName$
                {
                    get
                    {
                        if (m_$PropertyName$ == null)
                        {
                            m_$PropertyName$ = $MethodName$();
                        }
                        return m_$PropertyName$ ?? $DefaultValue$;
                    }
                }
             ]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

A lot of stuff, but still pretty easy. The code template part of it is pretty straightforward:

private $type$? m_$PropertyName$ = null;
public $type$ $PropertyName$
{
    get
    {
        if (m_$PropertyName$ == null)
        {
            m_$PropertyName$ = $MethodName$();
        }
        return m_$PropertyName$ ?? $DefaultValue$;
    }
}

Cool, huh? But, it was time-consuming to write all those literals and everything in XML. Now, I just wrote this last week (which is what made me think I should write a blog post about it), but I thought at the time that there had to be an easier way to write the .snippet file. I didn’t get around to looking for anything to make it easier until I started researching for writing this blog post. I found a decent Snippet editor/designer on CodePlex:

http://snippetdesigner.codeplex.com/

This designer is a plug-in for Visual Studio (download it, double-click what you downloaded, and it adds it to Visual Studio for you). Basically, with this plug-in you only have to write the template (without all the $ delimiters), and indicate which parts of that template should be the literals and it does a lot of the grunt work for you. And, what’s even better is you can use existing code in the IDE (or write some new code just for this purpose) … just select the code, right-click and choose “Export As Snippet” and you’re in the designer with your selected code all set to make it into a template. Couldn’t be easier … I wish I had discovered this plug-in a few months back when I was writing some heavy-duty snippets!

Enjoy!