Creating Your Own Code Snippets with Whidbeyby Wei-Meng Lee
One of the new features found in Visual Studio .NET Whidbey is known as Insert Snippets. The Insert Snippets feature allows you to insert commonly-used code blocks into your project, thereby improving the efficiency of your development process. Default code snippets shipped with Whidbey, and you can also add in your own. In this article, I will show you how you can integrate your own snippets into Visual Studio .NET Whidbey.
Using Insert Snippets in Visual Studio .NET Whidbey
In the alpha release of Visual Studio .NET Whidbey, you can only use the Insert Snippets feature in a Visual Basic .NET Windows application. Microsoft claims that there are approximately 500 code snippets available, but in this release there are only 21.
To use the Insert Snippets feature, you simply switch to Code View and right-click at the point where you want to insert your code. The code snippets are divided into categories to make finding the code you want easy. Within each category you will find the title of the code snippet that you want (see Figure 1).
|Figure 1. Using Insert Snippet|
The actual code snippets are located in the C:\Program Files\Microsoft Visual Studio .NET Whidbey\Common7\IDE\Visual Basic Snippets\ folder (see Figure 2).
|Figure 2. The folder containing all of the code snippets|
Within each folder are files containing code snippets. The extension of each file is .vbsnippet. Here is the content of a snippet:
<?xml version="1.0" encoding="utf-8"?> <ExStencil format="1.0.0"> <header> <title>Read Text from Files </title> <id>4ee01447-47c9-47ce-90a2-de6ec704a0e5</id> <version>22.214.171.124</version> <locale>en-us</locale> <author>Microsoft</author> <description>The following code example reads the contents of a text file into a single string. </description> <helpurl> ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.1033 /dv_vbcode/html/vbtskcodereadingtextfromfilevisualbasic.htm </helpurl> <category>My.Computer.FileSystem; FileIO</category> <keywords>My.Computer.FileSystem</keywords> </header> <snippet> <platform> <runtime>v1.2.30422</runtime> </platform> <references> <reference> <assembly>System.dll</assembly> <version>1.0.5000.0</version> <url /> </reference> </references> <imports> <import> <namespace>System</namespace> </import> </imports> <declarations> <literal> <id>FileName</id> <type /> <tooltip> Replace this string with name of the file that you want to read from. </tooltip> </literal> </declarations> <code language="VB" scope="method body"> ' Click for more: 'ms-help://MS.VSCC.2003/commoner/redir/ 'redirect.htm?keyword="vbtskcodereadingtextfromfilevisualbasic"' Dim allText As String Try allText = _ My.Computer.FileSystem.ReadAllText(_ <literal id="FileName">_ "test.txt"</literal>) Catch fileException As Exception Throw fileException End Try </code> </snippet> </ExStencil>
The .vbsnippet file is an XML document that contains a description and the details of the code snippet. The name of each file is not important; it is the text of the
<title> element that is shown in the Insert Snippets menu.
Creating Your Own Code Snippet
Creating your own code snippet is easy — just create a folder in the designated folder (as described earlier) and save a .vbsnippet file in the folder. Visual Studio .NET Whidbey will then automatically recognize the new code snippet. To create the .vbsnippet file, you have two ways to accomplish it — create a .vbsnippet file from scratch, or modify an existing one for your own use.
I strongly suggest you modify an existing code snippet, as this is the simplest; it will save you a lot of trouble trying to create an XML document that conforms to the code snippet schema.
For the example in this article, I will use an existing code snippet and modify it. In particular, I will create a code snippet to perform SOAP serialization. To explain the various parts of a code snippet, I will dissect the modified code snippet.
Dissecting the Code Snippet
A code snippet XML document starts with the
<ExStencil> root element. The
<header> element contains the basic information about your code snippet. More important is the
<title> element, whose text is exposed to the user. You should use a descriptive sentence that conveys the function of your code snippet. The
<snippet> element defines the actual definition of the code snippet.
You can get a detailed description of the function of each element from the MSDN online help.
<?xml version="1.0" encoding="utf-8"?> <ExStencil format="1.0.0"> <header> <title>SOAP Serialization</title> <id>c615968a-0829-4177-9d10-d01388b36ddd</id> <version>126.96.36.199</version> <locale>en-us</locale> <author>Wei-Meng Lee</author> <description>Code for SOAP serialization</description> <helpurl>ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.1033/ dv_vbcode/html/vbtskcodevalidatingdatevisualbasic .htm</helpurl> <category>Serialization</category> <keywords>SOAP, Serialization</keywords> </header>
Next comes the actual declaration of the code snippet. The
<references> element specifies the assembly to be added to your project when this code snippet is added in the project. For my case, I need to add a reference to the
<snippet> <platform> <runtime>v1.2.30422</runtime> </platform> <references> <reference> <assembly> System.Runtime.Serialization.Formatters.Soap.dll </assembly> <version>1.2.3400.0</version> <url /> </reference> </references>
<imports> element inserts the
Imports statement at the beginning of the file so that you can import the relevant namespace for your project:
<imports> <import> <namespace>System.IO</namespace> </import> <import> <namespace> System.Runtime.Serialization.Formatters.Soap </namespace> </import> </imports>
<declarations> element allows you to declare placeholders to be used in the actual code snippet (see the next section for more details). For this current release of Visual Studio .NET Whidbey, there is no visible difference between the
<literal> elements. Besides these two elements, you can also use the
<object> element. Also, the
<tooltip> element shows tooltip help when your cursor hovers above the placeholder. Again, this feature is currently not available in the current release of Visual Studio .NET Whidbey.
<declarations> <control> <id>obj</id> <type /> <tooltip> Replace this string with the object that you want to serialize </tooltip> </control> <literal> <id>filename</id> <type>String</type> <tooltip> Replace this string with your filename </tooltip> </literal> </declarations>
<code> element contains the actual code snippet that you are adding. You can specify the language (only VB at the moment) as well as the scope of the insertion. For example, your code snippet might be inserted into the body of a method, so in this case, your scope attribute is
method body. The
<control> elements reference the control and literal placeholders that you have declared earlier in the
<code language="VB" scope="method body"> '========SOAP Serialization========= Dim fs As New FileStream(_ "<literal id="fileName">your file Name here</literal>", _ FileMode.Create, FileAccess.Write) Dim formatter As New SoapFormatter '--serialize to file stream-- formatter.Serialize(fs, <control id="obj">obj</control>) fs.Close() </code>
However, if you want to insert a complete method, then you can change the scope attribute to
<code language="VB" scope="method decl"> '========SOAP Serialization========= Sub SOAPSerialize(ByVal obj As <control id="obj">objType</control>) Dim fs As New FileStream(_ "<literal id="fileName">your file Name here</literal>", _ FileMode.Create, FileAccess.Write) Dim formatter As New SoapFormatter ' serialize to file stream formatter.Serialize(fs, obj) fs.Close() End Sub </code> </snippet> </ExStencil>
That's it! Visual Studio .NET Whidbey is actually intelligent enough to know if you are inserting the code snippet in the correct place. For example, if you define your code snippet's scope to be a method body, Whidbey will only allow you to insert it within a method body. Otherwise, the code snippet will be grayed out (see Figure 3).
|Figure 3. Inserting the newly created code snippet|
The placeholders will be highlighted in yellow (see Figure 4). As a developer, you just need to replace the placeholders with the relevant information to suit your own use.
|Figure 4. Placeholders are highlighted in yellow|
Visual Studio .NET Whidbey contains a wealth of improvements to make the life of a developer easy and efficient. Using code snippets will reduce the amount of coding you need to perform, particularly in areas such as data access. I am looking forward to seeing this feature work for C# projects. For now, if you have Visual Studio .NET Whidbey, have fun exploring!
Wei-Meng Lee (Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.
Return to ONDotnet.com