ENTERPRISE

Visual Studio 2010 IDE : Using, Creating, and Managing Reusable Code Snippets

11/4/2012 7:40:13 PM
Like its predecessors, starting with Visual Studio 2005, Visual Studio 2010 also provides support for reusable code snippets. The most important addition to the new version is the support for HTML, ASP.NET, and SQL code snippets. The idea is that you can add into the code editor existing code snippets stored in external files with the .Snippet extension, which you can reach from within Visual Studio (and integrated with the IDE) without the need of creating your custom archive. Another huge benefit of code snippets is that they can be shared with other developers, so that you and other friends can increase the code library. Code snippets support is offered in several ways, which is covered in this section.

Visual Studio Code Snippets

Visual Studio ships with a large number of code snippets ready to be used. To prevent accidental deletions, the code snippets reside in the IDE’s own folder and cannot be removed from the Code Snippets Manager.


Consuming Code Snippets

Adding existing code snippets into your code is an easy task. Just for demo purposes, create a new console project with Visual Basic and, when ready, place the cursor within the Sub Main. Right-click and select the Insert Snippet command. At this point the IDE shows a list of available snippets categories, as shown in Figure 1.

Figure 1. The IDE shows a list of available snippets categories.

The first thing to mention is that code snippets files are organized in categories, such as WPF, Code Patterns, Fundamentals, and so on. Basically a category is nothing but a folder containing a number of .snippet files. Double-click the desired category, for example Code Patterns. At this point the IDE shows a list of subcategories; click Error Handling (Exceptions). Now Visual Studio offers the list of available code snippets within the given category, as exemplified in Figure 2.

Figure 2. A list of code snippets.

Double-click the Try..Catch..End Try Statement snippet so that code is added in the code editor. At this point Visual Studio inserts a code snippet for intercepting an exception within a Try..Catch block, as shown in Figure 3.

Figure 3. The code snippet has been added to the current code.

Notice how, in this specific example, the ApplicationException has been highlighted. Highlights are also known as replacements because they indicate to the developers that they should replace the highlighted code with a more appropriate code block according to her needs. For example, you might want to catch a FileNotFoundException instead of an ApplicationException; therefore, you should make this replacement, but the rest of the code snippet is still valid.

 

Replacement Information

If you pass with the mouse pointer over replacements, you get information via a tooltip about what the replacement is about.


Generally code snippets offer lots of information, too, such as the author name, support website, and shortcut. This information is also available in the Code Snippet Manager described in next section.

The Code Snippet Manager

The Code Snippet Manager is an integrated tool for adding, removing, and getting information on code snippets. You invoke it by selecting Tools, Code Snippets Manager. Figure 4 shows how this tool window looks.

Figure 4. The Code Snippet Manager tool.

You can first select one of the available programming or markup languages from the Language combo box. The tool automatically shows a list of available code snippets related to that specific language. You can browse the snippets tree and select one to get information, such as the Description, the Shortcut, and the Author. As you can see, code snippets can be organized into subfolders. To create a new subfolder simply click Add and provide the folder name. If you want to import existing code snippets, simply click Import and select the .snippet files you want to add to the current collection. Notice that you can also remove code snippets from the collection, but this is not allowed for snippets shipped with Visual Studio, whereas it is allowed on custom code snippets. Also notice that the Shortcut property for snippets is useful because in the code editor you can simply add a code snippet typing its shortcut and then pressing Tab, without the need of performing all steps described in the previous subsection. When you know how to manage snippets, you are ready to learn to build custom snippets.

Creating and Consuming Custom Code Snippets

Code snippets .Snippet files are simply Xml files containing the code and information about the snippet. Code snippets have their own Xml schema that Visual Studio then uses to correctly identify them within the IDE. To understand how a code snippet is made, consider the following code that is stored in the snippet named Calculate Cosine of an Angle from the Visual Studio snippets library:

Dim radians As Double = 120 * Math.PI / 180
Dim cos As Double = Math.Cos(radians)

If you open the CalculateCosineOfAngle.snippet file with an Xml editor (or just with Windows Notepad), the file content looks like the content of Listing 1.

Listing1. Examining an Existing Code Snippet
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Calculate the Cosine of a specified Angle</Title>
      <Author>Microsoft Corporation</Author>
      <Description>Converts an angle from degrees to radians and then calculates
                   cosine of the angle</Description>
      <Shortcut>mathCos</Shortcut>
    </Header>
    <Snippet>
      <Imports>
        <Import>
          <Namespace>System</Namespace>
        </Import>
        <Import>
          <Namespace>Microsoft.VisualBasic</Namespace>
        </Import>
      </Imports>
      <Declarations>
        <Literal>
          <ID>Degrees</ID>
          <Type>Double</Type>
          <ToolTip>Replace with the measurement in degrees.</ToolTip>
          <Default>120</Default>
        </Literal>
      </Declarations>
      <Code Language="VB" Kind="method body"><![CDATA[Dim radians As Double =
            $Degrees$ * Math.PI / 180
            Dim cos As Double = Math.Cos(radians)]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

					  

Code snippets in Visual Studio 2010 still adhere to the first Xml schema introduced with Visual Studio 2005, so there are no changes. Basically a snippet structure is divided into some Xml nodes. The Header node provides information on the snippet, whereas the Snippet node contains code, required Imports directives, and assembly references. Notice how the real code is stored inside a CDATA section. As you may know, this kind of section can store any kind of characters, and so it is the most appropriate for storing code. Finally the Declarations node stores information on replacement. The ID element specifies an ID for the replacement, the Type element specifies the data type of the object that should be replaced, ToolTip provides a descriptive tooltip when the user passes the mouse over the replacement, and Default provides a default value. Now imagine you want to create a custom code snippet that will be added to the code snippets library so that you can reuse it inside Visual Studio. First, you need a Visual Basic code snippet. As an example, consider the following code that implements an extension method for converting an IEnumerable(Of T) into an ObservableCollection(Of T):

<Extension()> Module Extensions
    <Extension()> Function ToObservableCollection(Of T)(ByVal source As  _
                  IEnumerable(Of T)) As ObservableCollection(Of T)

        If source IsNot Nothing Then
            Return New ObservableCollection(Of T)(source)
        Else
            Throw New ArgumentNullException("source")
        End If
    End Function
End Module

Now the goal is building a custom .snippet file to make the preceding code reusable. Thus you must create an Xml file according to the snippet schema. Listing 2 shows how to accomplish this. You can use any text editor, such as the Windows Notepad or the Visual Studio’s Xml editor.

Listing 2. Building a Custom Code Snippet
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>ToObservableCollection</Title>
      <Author>Alessandro Del Sole</Author>
      <Description>Convert an IEnumerable(Of T)
                   into an ObservableCollection(Of T)
      </Description>
      <HelpUrl>http://community.visual-basic.it/Alessandro</HelpUrl>
      <SnippetTypes />
      <Keywords />
      <Shortcut>toObs</Shortcut>
    </Header>
    <Snippet>
      <References />
      <Imports>
        <Import>
          <Namespace>System.Runtime.CompilerServices</Namespace>
        </Import>
        <Import>
          <Namespace>System.Collections.ObjectModel</Namespace>
        </Import>
      </Imports>
      <Declarations>
        <Literal Editable="true">
          <ID>source</ID>
          <Type>IEnumerable(Of T)</Type>
          <ToolTip>Replace with a different identifier if needed</ToolTip>
          <Default>source</Default>
          <Function></Function>
        </Literal>
       </Declarations>
       <Code Language="VB" Kind="" Delimiter="$"><![CDATA[<Extension()> Module
 Extensions
     <Extension()> Function ToObservableCollection(Of T)(ByVal $source$ As  _
                   IEnumerable(Of T)) As ObservableCollection(Of T)

         If $source$ IsNot Nothing Then
             Return New ObservableCollection(Of T)($source$)
         Else
             Throw New ArgumentNullException("$source$")
         End If
     End Function
 End Module]]></Code>
     </Snippet>
   </CodeSnippet>
 </CodeSnippets>

					  

Xml elements are self-explanatory. At this point you simply need to save the preceding snippet in the C:\Users\UserName\My Documents\Visual Studio 2010\Code Snippets\Visual Basic\My Code Snippets folder. For example, save it as ToObservableCollection.snippet. Now go back to the Visual Basic code editor, right-click to insert a snippet until you find the new My Code Snippets|ToObservableCollection element. If you add it, you should get a result similar to the one shown in Figure 5.

Figure 5. Adding the new code snippet in Visual Studio.

Notice how you get information on the replacement via the specified tooltip, when the mouse pointer passes over the replacement.

Maybe you want to know how to deploy code snippets for sharing with other developers or simply to create a code snippets database. The most appropriate way for sharing snippets is creating a redistributable .Vsi package based on the Visual Studio Content Installer, a particular engine dedicated to sharing additions for Visual Studio (particularly add-ins and code snippets, the only two additional contents not covered by VSIX packages in Visual Studio 2010). This is appropriate because such an engine can install contents into the correct folders so that developers will not do this manually. The VSCI is not covered here (read the MSDN documentation at this address: http://msdn.microsoft.com/enus/library/ms246580(VS.100).aspx), but in Appendix C you can find tools capable of generating .vsi packages for you. Another way to share snippets is to create a compressed archive storing .Snippet files that you can send to other developers; then they will just extract the archive content into the snippets folder.

Other  
 
Most View
ASUS ROG Poseidon GTX 780 Review
MSI FM2-A85XA-G65 Motherboard Review (Part 4)
The Mercedes-Benz GL63 AMG – Monster Trucking (Part 1)
Connectivity Matters
Jabra SOLEMATE Bluetooth Portable Speaker
Xiaomi Phone 2 - High-End Specifications In A Surprisingly Cheap Package (Part 1)
Constellation Virgo/Centaur: High-End Audio Superstars (Part 2)
Ubuntu Arrives For Touch Phones (Part 2)
Windows Vista : Windows PowerShell (part 2) - PowerShell Variables, PowerShell Scripts, Automate Scripts with the Task Scheduler
Remove Internet Limits With A VPN (Part 2)
Top 10
SQL Server 2012 : Consolidating Data Capture with SQLdiag - Getting Friendly with SQLdiag (part 2) - Using SQLdiag as a Service
SQL Server 2012 : Consolidating Data Capture with SQLdiag - Getting Friendly with SQLdiag (part 1) - Using SQLdiag as a Command-line Application
SQL Server 2012 : Consolidating Data Capture with SQLdiag - The Data Collection Dilemma, An Approach to Data Collection
SQL Server 2012 : Troubleshooting Methodology and Practices - Data Analysis, Validating and Implementing Resolution
SQL Server 2012 : Troubleshooting Methodology and Practices - Data Collection
SQL Server 2012 : Troubleshooting Methodology and Practices - Defining the Problem
SQL Server 2012 : Troubleshooting Methodology and Practices - Approaching Problems
Windows 8 : Accessing System Image Backup and Recovery Functionality with Windows Backup, Cloud Backup
Windows 8 : Using the Windows 8 Recovery Tools (part 2) - Push Button Reset
Windows 8 : Using the Windows 8 Recovery Tools (part 1) - Creating a System Recovery Disc, Booting to the Windows Recovery Environment