How to Create your own Visual Studio 2005/2008 code snippets

Overview of Code Snippets

Code snippets is new feature added in visual studio 2005, which allows to use a pre-authored piece of code. This helps in fast development and re-usability of standard pre-authored piece of code throughout your application.

Microsoft ships set of pre-authored code-snippets with visual studio 2005. you can also download many snippets from Microsoft site. These snippets provide many re-usable pre-authored piece of code that can directly inserted in our application. But many time you will require to create your own snippet as per you application requirement. The good news is that using IntelliSense Code Snippet XML schema elements you can create your own code snippets. Once code snippet is created you can use Visual Studio Code Snippet Manger and add them to the code snippets that Visual Studio 2005 already includes.

Code snippets are xml files that uses code snippet xml schema elements. You can use the IntelliSense Code Snippet XML schema to create your own Visual Basic, Visual C#, Visual J#, or XML code snippets.

Sample code

In this tutorial I will show you how to create a simple code snippet.

Snippet definition : I want to create a simple code snippet for C# language that read a SQL server database table content using data reader class.

Following is the code that I will convert into snippet. The purpose of the code is to read a table from SQL server database and store results into reader object. You will need to change the connection string and query as per your requirement in this code.

Sample Code that will be converted into snippet.

	//Creates instance of sql connection
	SqlConnection conn=new SqlConnection("connectionString");
	SqlDataReader rdr=null;
	try
	{
		//create new sql command object
		SqlCommand cmd = new SqlCommand("Sql query", conn);
		cmd.CommandType = CommandType.Text;

		if ( conn.State != ConnectionState.Open )
			conn.Open();
		rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
				
		//Check if reader has any records within it.
		if ( rdr.HasRows )
		{
			while ( rdr.Read() )
			{ 
				//Read table column information from reader
			}
			rdr.Close();
		}
	}
	catch(SqlException ex)
	{
		//Handle Database related exception here
	}
	catch(Exception ex)
	{
		//Handle General exception here
	}
	finally
	{
		//Close reader
		if ( rdr != null && rdr.IsClosed == false )				
			rdr.Close();

		//Dispose reader
		rdr.Dispose();
				
		//Close Connection
		if ( conn != null && conn.State != ConnectionState.Closed )
			conn.Close();	
				
		//Dispose connection if you don't require
			conn.Dispose();
	}

Following are the steps to create code snippet (.snippet) file

  1. On the File menu, click New and then click File.
  2. Click XML File and then click Open.
  3. On the File menu, click Save.
  4. In the Save as type box, select All Files (*.*).
  5. In the File name box, enter a file name with the .snippet file name extension.
  6. Click Save.

Now xml file is created and now you need to put xml code to create your own code snippet. To avoid any errors in your code snippent you can use this code

Sample Snippet Code.

<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<Header>
		<Title>title</Title>
		<Author>author</Author>
		<Shortcut>shortcut</Shortcut>
		<Description>description</Description>
		<SnippetTypes>
			<SnippetType>SurroundsWith</SnippetType>
			<SnippetType>Expansion</SnippetType>
		</SnippetTypes>
	</Header>
	<Snippet>		
		<Declarations>
			<Literal>
				<ID>literal id</ID>
				<Default>literal value</Default>
			</Literal>
		</Declarations>
		<Code Language="CSharp">
			<![CDATA[
				//Write your snippet code here
			]]>
		</Code>
	</Snippet>
</CodeSnippet>

Following is the description of the code snippet xml schema elements we have used within our snippet code

  • CodeSnippet : Allows you to specify a heading and multiple IntelliSense Code Snippets, which you can insert into Visual Studio 2005 code files.
    • Header : Specifies general information about the IntelliSense Code Snippet.
      • Title : Specifies the title for the code snippet.
      • Author : Specifies the name of the snippet author.
      • Shortcut : Specifies the shortcut text used to insert the snippet.
      • Description : Specifies descriptive information about the contents of an IntelliSense Code Snippet.
      • SnippetTypes : Groups individual SnippetType elements..
        • SnippetType : Specifies how Visual Studio inserts the code snippet
    • Snippet : Specifies the references, imports, declarations, and code for the code snippet.
      • Declarations : Specifies the literals and objects that make up the parts of a code snippet that you can edit. The literals/object id in declarations section can be used in code and must prefixed and suffixed by $. For ex. if a literal is "SQL" then in the code section you have to use it as $SQL$.
      • Code : Provides a container the short code blocks of IntelliSense Code Snippets.

Code Snippet to read table using data reader

Save the following following content in your code snippet file.

Code Snippet File : ReadTableUsingDataReader.snippet

<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<Header>
		<Title>Read table content using SQL Data Reader</Title>
		<Author>Mrityunjaya Kumar</Author>
		<Shortcut>ReadTableUsingDataReader</Shortcut>
		<Description>
			The purpose of the code is to read a table from SQL server database 
			and store results into reader object. You will need to change the 
			connection string and query as per your requirement in this code.
		</Description>
		<SnippetTypes>
			<SnippetType>SurroundsWith</SnippetType>
			<SnippetType>Expansion</SnippetType>
		</SnippetTypes>
	</Header>
	<Snippet>		
		<Declarations>
			<Literal>
				<ID>ConnectionString</ID>
				<Default>Server=(local);Data Source=(local);Initial Catalog= ;UserId=;Password=;</Default>
			</Literal>
			<Literal>
				<ID>Query</ID>
				<Default>Select * from table</Default>
			</Literal>
		</Declarations>
		<Code Language="CSharp">
			<![CDATA[
			//Creates instance of sql connection
			SqlConnection conn=new SqlConnection("$ConnectionString$");
			SqlDataReader rdr=null;

			try
			{
				//create new sql command object
				SqlCommand cmd = new SqlCommand("$Query$", conn);
				cmd.CommandType = CommandType.Text;

				if ( conn.State != ConnectionState.Open )
					conn.Open();
				rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

				//Check if reader has any records within it.
				if ( rdr.HasRows )
				{
					while ( rdr.Read() )
					{ 
						//Read table column information from reader
					}
					rdr.Close();
				}
			}
			catch(SqlException ex)
			{
				//Handle Database related exception here
			}
			catch(Exception ex)
			{
				//Handle General exception here
			}
			finally
			{
				//Close reader
				if ( rdr != null && rdr.IsClosed == false ) 
				rdr.Close();

				//Dispose reader
				rdr.Dispose();
				
				//Close Connection
				if ( conn != null && conn.State != ConnectionState.Closed )
				conn.Close(); 
				
				//Dispose connection if you don't require
				conn.Dispose();
			}
			]]>
		</Code>
	</Snippet>
</CodeSnippet>

Adding Code Snippet to Visual Studio

After saving the .snippet file on disk, now we have to add our snippet into the visual studio so that we can use it in our application. For adding custom snippet in the list of existing Visual Studio snippets

  1. Go to Tools > Code snippet Manager or press Ctrl+K, Ctrl+B.
  2. It will display code snippet manager window. select "import" button and select the .snippet file you have created.
  3. after selecting the file code snippet manager will display the "Import Code Snippet" window where you can add the snippet to specific location. We have created code snippet to be used in Visual C# application, so select Visual C#.
  4. Click Finish and your code snippet is available to be used in your application

To use you code snippet, right click inside the method and select "Insert Snippet". Select "Visual C#" and it will display list of all the Visual C# snippets. Find your snippet by the title you have assigned in snippet file or use short cut to find your snippet. The snippent will be added to your cursor location.

Advertisements
This entry was posted in Visual Studio 2005/2008. Bookmark the permalink.

One Response to How to Create your own Visual Studio 2005/2008 code snippets

  1. Pingback: Visual Studio 2005 Express Tutorial « Hebat El Niel مصر هبة النيل

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s