Creating your own code snippets with the Code Snippet Manager

Posted Monday, January 9, 2006 4:57 PM by C-Dog's .NET Tip of the Day

I am finally getting settled into my new job, so I should be posting more reguarly now. Since, the Tip of the Day is on a real web server now, I can actually make posts that contain images (how exciting).

Today's topic is on the Code Snippet Manager. The Code Snippet manager provides support for configuring code expansions. You probably have heard about code expansion by now, but maybe not. Basically, they allow you to automate routine things in code such as creating a property, or a try/catch block. The most common one you heard of is the prop expansion. Simply type prop and hit tab and it will expand to include a private variable declaration and the property that reads and writes to it. You can then tab through and set the private variable name and the property name. It will automatically update the relavent spots in the property when you change the private variable's name.

So that's cool, but if what if you want to make your own? Well it's pretty easy. The Code Snippets folder in your Document and Settings\<username>\My Documents\Visual Studio\Code Snippets folder will let you add your own. There are divided into a number of categories such as VB, VC#, J#, Office, and XML. If you want to configure a snippet manually, simply copy it into the appropriate directory.

Of course, there is an easier way to do it. The Code Snippet Manager makes it easy to add your own snippets and manage them. It will even let you search online for new ones. To get to the Code Snippets Manager, go to the Tools menu and click on Code Snippets Manager. Some installations and some projects do not have this in there by default, so if you don't see it, you will have to reconfigure your toolbars or you can try hitting Ctrl + K, Ctrl + B.

When you open the manager, you will notice there is about a billion snippets for Visual Basic that let you do some pretty advanced things such as SQL queries and copying files. Nice if you are like Marcus and love VB, but no good for C#. There are still some handy snippets that you can make use of though. Once you have it open you can click the Import button and import a custom snippet into your collection.

Code Snippet Manager

Now, if you are actually still reading this, you might be wondering exactly, how you create the snippet itself. Snippet files are actually just XML, so the easiet way to create your own is to copy an existing one such as prop. The builtin snippets can be found in the C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C# folder. Here is an example.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  
xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
 <CodeSnippet Format="1.0.0">
 <Header>
   <Title>ErrorKey Test</Title>
     <Shortcut>errorkeytest</Shortcut>
     <Description>Code snippet for creating an Erorr Key Test</Description>
     <Author>Microsoft Corporation</Author>
     <SnippetTypes>
     <SnippetType>Expansion</SnippetType>
	</SnippetTypes>
     </Header>
     <Snippet>
	<Declarations>
		<Literal>
			<ID>rule</ID>
			<ToolTip>Rule Name</ToolTip>
			<Default>errorRule1</Default>
		</Literal>
		<Literal>
			<ID>request</ID>
			<ToolTip>Request Name</ToolTip>
			<Default>request1</Default>
		</Literal>
	</Declarations>
	<Code Language="csharp">
  <![CDATA[if ((this.Context.ValidationLevel >= 
Microsoft.VisualStudio.TestTools.WebTesting.ValidationLevel.High))
	{
		ValidationRuleFindText $rule$ = new ValidationRuleFindText();
		$rule$.FindText = "ErrorKey";
		$rule$.IgnoreCase = true;
		$rule$.UseRegularExpression = false;
		$rule$.PassIfTextFound = false;
		$request$.ValidateResponse += 
new EventHandler<ValidationEventArgs>($rule$.Validate);
	}$end$]]>
        </Code>
     </Snippet>
   </CodeSnippet>
</CodeSnippets>

Some of the elemnts are obvious, I'll point out the function of some of the key ones. The Shortcut element specified the key sequence to type to expand the code snippet in the editor. I believe this has to be unique. The SnippetType is used to specify that the snippet is a code expansion (refactoring can also be done in this manner but I have not tried it). The Literal element in the Declarations section specifies the user replacable values. So after this expansion is expanded, the expansion will prompt for a value for rule and replace everything in the code element that has $rule$ in it with whatever the user typed in. Lastly, the code element specifies the actual code to expand. Just make sure to include it in a CDATA.

Code snippets are extremely useful and people are providing more and more of them. Just click on the Search Online link the Code Snippet Manager to see for yourself.

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=230