Monday, February 2, 2009

Visual Studio 2008 - Code Snippits

Well I'm back in Ireland and running amok again. Decided to note some old information as I'd forgotten most of these steps since the last time I'd used Visual Studio 2008 Code Snippits.

Creating a Code snippit is very easy as it's just an XML file using a spcific schema. Unfortunetly that schema is a little hard to remember, which is why I'm posting this information in the first place. Below is a simple example which should be saved as an XML file with the extension ".snippit" (e.g. "test.snippit"):

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Test Snippit</Title>
<Shortcut>snipTest</Shortcut>
<Author>Richard Greene</Author>
<Description>Test Code</Description>
</Header>
<Snippet>
<Declarations>
<Literal Editable="true">
<ID>snipTest</ID>
<ToolTip>Add a hello world message</ToolTip>
<Default>Test</Default>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[MessageBox.Show("Hello World");]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

To place this into your Visual Studio 2008 environment, you use the Code Snippit Manager from the Tools menu or the quick keys <CTRL>K <CTRL>B.



Click the Import button and browse to the the location you saved the XML file.

Select the location within the Manager where you want the snippit to appear, I've chosen the standard "My Code Snippets" folder and click Finish.


You should now be able to see the chosen snippet within the Manager.

To make use of this snippit simply within type the shortcut name (in this case "snipTest") within any C# file and Intelisence should display your snippet. Clicking TAB after selecting the snippet will insert the code block you are looking for.

This feature can be expanded greatly, with lots of flexibility for making areas read-only inserting default values etc., however I'll leave that up to you.