Thursday, May 11, 2006

Code snippets can make the life of a developer a lot easier.  Already in VS2003 you had the possibility to add code snippets to your toolbox or make use of a third party tool.  In VS2005 Microsoft has added a code snippet manager.  We will explain in short how to create such a code snippet.

The format of the code snippet is XML base.  An example of a code snippet file:

<CodeSnippets
xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
     <Title>My MessageboxSnippet</Title>
     <Description>My Snippet for messagebox in c#</Description>
     <Shortcut>mmbs</Shortcut>
</Header>
<Snippet>
<References>
<Reference>
<Assembly>System.Windows.Forms.dll</Assembly>
</Reference>
</References>
<Code Language="VB">
<![CDATA[MessageBox.Show("My first own snippet")]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

We have several parts:

  • Header
    • Title: Name of the snippet
    • Description : Description of the snippet
    • Shortcut : Shortcut to access the snippet
  • Snippet
    • Reference: references to DLL's needed when implementhing the snippet.  Be aware that this is only supported by VB.Net snippets.  Snippets for other code needs to add the reference manually in your solution.
    • Code language: the language of the code
      • VB
      • CSharp

The only thing left now is to save the snippet as a .snippet file and place it in the snippet directory.  By default your snippet directory can be found here : My Documents\Visual Studio 2005\Code Snippets\ and then the language and then the directory "My Code snippets".

A complete course can be found in the MSDN.

But there is an easier way.  The VS Editor Team has released a PowerToy named Snippy.  This is a very handy tool for creating your own snippets.  Click here for more info.

Some interesting code snippets:
Microsoft: http://msdn.microsoft.com/vstudio/downloads/codesnippets/default.aspx
NUnit: http://codebetter.com/blogs/scott.bellware/archive/2006/02/28/139446.aspx
Public property: http://weblogs.asp.net/jeffwids/archive/2005/09/08/424679.aspx

I also found a great tool for world wide snippet sharing: http://www.codexchange.net/
And like gotdotnet there's also a gotcodesnippet site: http://gotcodesnippets.com/

5/11/2006 9:23:04 PM (Romance Standard Time, UTC+01:00)  #     |