Code Snippets in Visual Studio 2005
 
Published: 04 Jan 2006
Unedited - Community Contributed
Abstract
In this article, Bilal Haidar covers an interesting feature in Visual Studio 2005, the Code Snippet. He will introduce Code Snippets, analyze an existing one, then create a new Code Snippet from scratch.
by Bilal Haidar
Feedback
Average Rating: 
Views (Total / Last 10 Days): 35101/ 47

Introduction

Visual Studio 2005 ships with a huge number of new features, including ready-to-use controls, IDE enhancements and much more interesting features. One of the nice and useful features of Visual Studio 2005 is the Code Snippet feature. The Code Snippet feature allows you to add a piece of generic code that you can customize to make it work with your specific needs.

In this article, I will be introducing Code Snippets, showing you how to add a Code Snippet in your page, and finally showing you how to create a Custom Code Snippet.

 

What is a Code Snippet?

How many times have you needed to create a new property with its private field in your objects or pages? You had to copy and paste the private field and its property and change the private field name, private field data type, property name, and the property data type. The Code Snippet feature is the solution for this repetitive work. You can now insert a generic property and all you need to do is change the property and private field data types and names without the need to write the whole property and private field codes again.

So now that you know what a code snippet does, let us discover what a code snippet is. A code snippet is nothing but an XML-formatted file which has .snippet as a file extension and is registered in Visual Studio 2005 using the Snippet Code Editor. A code snippet supports replaceable values and referencing assemblies (Visual Basic.NET only). I will be showing the contents of a snippet file and how to create a new one later on in this article.

Visual Studio 2005 comes with a set of predefined code snippets. If you want to add your own code snippet, then you must use the Visual Studio 2005 Code Snippet Manager.

 

Major Parts of a Code Snippet

The code snippet consists of two main parts:

  • Header
  • Snippet

 

The Header has the following sections:

  • Title
  • Shortcut
  • Description
  • Author
  • SnippetTypes

 

The Header is the code snippets meta-data which includes the title of the code snippet, a shortcut to access the code snippet, a description explaining what the code snippet does, and other relevant information.

The Snippet has a mandatory section and an optional one:

  • Declarations
  • Code

The required section is the Code section. In this section you define the code emitted by the code snippet. The optional Declarations section is used to define the replaceable values in the code snippet. Replicable values are represented by $value$ in the Code section; they are displayed as green and are configurable by the developer using the code snippet.

 

Code snippets are language-specific. Visual Studio 2005 ships with a number of ready code snippets for both Visual Basic and C#. You can find all the code snippet files at the following path:

{Drive Letter}:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C#

 

A Code Snippet

In this section, I will demonstrate on a ready-made code snippet that ships with Visual Studio 2005.

Listing 1 below shows the property code snippet that ships with Visual Studio 2005.

<?xml version="1.0" encoding="utf-8" ?>

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">

  <CodeSnippet Format="1.0.0">

    <Header>

      <Title>prop</Title>

      <Shortcut>prop</Shortcut>

      <Description>Code snippet for property and backing field</Description>

      <Author>Microsoft Corporation</Author>

      <SnippetTypes>

        <SnippetType>Expansion</SnippetType>

      </SnippetTypes>

    </Header>

    <Snippet>

      <Declarations>

        <Literal>

          <ID>type</ID>

          <ToolTip>Property type</ToolTip>

          <Default>int</Default>

        </Literal>

        <Literal>

          <ID>property</ID>

          <ToolTip>Property name</ToolTip>

          <Default>MyProperty</Default>

        </Literal>

        <Literal>

          <ID>field</ID>

          <ToolTip>The variable backing this property</ToolTip>

          <Default>myVar</Default>

        </Literal>

      </Declarations>

      <Code Language="csharp">

<![CDATA[private $type$ $field$;

public $type$ $property$

{

  get { return $field$;}

  set { $field$ = value;}

}

$end$]]>     

      </Code>

    </Snippet>

  </CodeSnippet>

</CodeSnippets>

In the Header section, you can see the informative information about the code snippet including a title, a shortcut, a description, an author, and snippet types.

The Snippet section includes two sections, the Declarations and the Code section.

As mentioned above, the Declarations section contains definitions for the replicable values inside the code snippet. In this example, the prop code snippet should define three replicable values, the private field name, the property name, and finally the property data type.

The mandatory code section includes the usual code for a property. You can see the replicable values surrounded by the $ sign. Those values have been defined above in the Declarations section. It is the developer using the code snippet who would replace those values with proper values.

How to Use a Built-In Code Snippet

In this section you will see how to use a ready-made code snippet. I will assume you are currently working with an open web application in Visual Studio 2005.

Create a new ASP.NET page, and then flip to the code view so that you will be able to add a code snippet.

Click on Tools, then Code Snippet Manager; you will be faced by the following figure

 

I have selected the prop code snippet included inside the Visual C# package. You can also select any other code snippet belonging to Visual C# or Visual Basic.

In the location section, you can see the location of the code snippet which is the same as mentioned in one of the sections in the article. The left pane shows the Header section of the prop code snippet.

You select a code snippet and press OK. You then see the code snippets code emitted on the page where you are adding the code snippet as follows:

private int myVar;

public int MyProperty

{

get { return myVar;}

set { myVar = value;}

}

The words highlighted by green are the replicable values defined inside the Declarations section of the code-snippet. As you can see, they have taken their default values as defined. Now, the developer should either change the default values to meet his/her needs or keep them the same.

 

 

How to Build a Custom Code Snippet

In this section, I will consider a step-by-step process to show you how to create a new code snippet and add it to the Visual Studio to be accessible any time you want to use it.

The code snippet I will create will be a method that fits in the Data Access Layer of any application. This method would simply return a SqlDataReader for clients living in a certain region.

The first step in developing a code snippet is to start by configuring the Header section of the new code snippet.

Create a new text file; rename the file to SqlDataReader.snippet. Then place the following text shown in Listing 2 in the snippet file.

<?xml version="1.0" encoding="utf-8" ?>

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">

  <CodeSnippet Format="1.0.0">

    <Header>

      <Title>SqlDataReader</Title>

      <Shortcut>dr</Shortcut>

      <Description>Code snippet for a method to return a Sql data reader </Description>

      <Author>Bilal Haidar</Author>

      <SnippetTypes>

        <SnippetType>Expansion</SnippetType>

      </SnippetTypes>

    </Header>

The next step is to specify the replicable values inside that method. Let us state the replicable values I have come up with:

  • Method name: I will give the developer freedom to change the method name.
  • SqlConnection instance name: The developer can change the SqlConnection instance used.
  • ConnectionString Text: The developer can change the Connect string text.
  • SqlCommand instance name: The developer can change the SqlCommand instance used.
  • Query Text: The developer will change the SQL statement used to retrieve a Data Reader.
  • SqlDataReader instance name: The developer will change the SqlDataReader instance name used.

The above analysis resembles the following Declarations section which is part of the Snippet section. Each Literal defines the state of each replicable value in the emitted text by the code snippet. Listing 3 below shows the Declarations section.

    <Snippet>

      <Declarations>

        <Literal>

          <ID>MethodName</ID>

          <ToolTip>Method name</ToolTip>

          <Default>GetAllCustomers</Default>

        </Literal>

        <Literal>

          <ID>SqlConnectionInstance</ID>

          <ToolTip>SqlConnection Instance Name</ToolTip>

          <Default>conn</Default>

        </Literal>

        <Literal>

          <ID>ConnectionString</ID>

          <ToolTip>Connection String</ToolTip>

          <Default>ConnectionString</Default>

        </Literal>

        <Literal>

          <ID>SqlCommandInstance</ID>

          <ToolTip>SqlCommand Instance Name</ToolTip>

          <Default>cmd</Default>

        </Literal>

        <Literal>

          <ID>QueryText</ID>

          <ToolTip>The select statement to be executed </ToolTip>

          <Default>SELECT * FROM Customers</Default>

        </Literal>

        <Literal>

          <ID>SqlDataReaderInstance</ID>

          <ToolTip>SqlDataReader Instance Name</ToolTip>

          <Default>dr</Default>

        </Literal>

      </Declarations>

The Code section, which is a mandatory section in the Snippet section, is shown in Listing 4 below.

      <Code Language="csharp">

<![CDATA[

public static SqlDataReader $MethodName$()

{

  SqlConnection $SqlConnectionInstance$ = new SqlConnection("$ConnectionString$");

  SqlCommand $SqlCommandInstance$ = new SqlCommand("$QueryText$", $SqlConnectionInstance$);

  $SqlConnectionInstance$.Open();

  SqlDataReader $SqlDataReaderInstance$ = $SqlCommandInstance$.ExecuteReader(CommandBehavior.CloseConnection);

  return $SqlDataReaderInstance$;

}

$end$]]>

      </Code>

    </Snippet>

  </CodeSnippet>

</CodeSnippets>

The above is a simple method that instantiates a connection, command, and executes a data reader that is returned as the output of that method.

Now, copy the above sections of the code-snippet into the SqlDataReader.snippet file created in a previous step.

In Visual Studio 2005, go to the Code Snippet Manager and select Visual C# from the drop-down list of available languages. Click on Import, select the code snippet file created, and you will be faced by the following screen:

You can select the My Code Snippets checkbox or any other checkbox and click Finish.

If you add this code snippet to your page in the same way discussed earlier, you would see something similar to the following method in Listing 5 below:

public static SqlDataReader GetAllCustomers()

{

  SqlConnection conn = new SqlConnection("ConnectionString");

  SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn);

  conn.Open();

  SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

  return dr;

}

All the green highlighted values are the ones defined in the Declarations section in the code snippet file.

You can either change the default values or use your own.

Conclusion

In this article, I have introduced the new cool feature in Visual Studio 2005, the Code Snippet. I defined what a code snippet is, discussed the sections constituting a code snippet file, demonstrated how to use a built-in code snippet, and finally presented a step-by-step guide on how to create a new custom code snippet and add it to the Visual Studio Code Snippet Editor.

 

Happy Dot Netting!!

 



User Comments

Title: developer   
Name: sunil
Date: 2009-10-27 9:23:04 AM
Comment:
very nice exmpl
Title: developer   
Name: nanda
Date: 2007-08-06 2:00:31 AM
Comment:
nice article..
Title: Developer   
Name: Stefan Leoni
Date: 2006-12-13 7:18:51 AM
Comment:
concise. Excactly what i was looking for.

Thanks.
Title: Re:   
Name: Bilal Haidar
Date: 2006-01-20 3:38:15 PM
Comment:
You can now, discuss, comment, and ask me questions related to this article at this forum:

http://bhaidar.net/cs/forums/10/ShowForum.aspx

Regards
Title: Solution Developer   
Name: Mostafa
Date: 2006-01-07 3:05:53 AM
Comment:
Good Article.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-20 3:38:28 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search