Working with Code Snippets in VS.NET

INTRODUCTION

Creating code snippets using VS.NET is very useful tip because it may help you when you need to write code repeatedly within your applications. For instance, we may use try catch finally block very often. Rather than writing the complete code-block manually, we may save it as a Code Snippet, then use it anywhere we want.

In this blog post, I will show you how to create, save and use Code Snippets, where you will see why Code Snippets are extremely useful, especially if you know that you may have various cases where you will apply such or similar code-blocks.

WORKING WITH EXISTING VS.NET CODE SNIPPETS

Microsoft has provided us with code snippets that developers use in most of the cases. In order to see the already existing code-snippets, in code-behind of your .net application, use the following shortcut keys:

CTRL+K+X

Insert Snippet will appear

you can select one of the given folders, and some predefined code snippets will appear

The line above the snippets shows the path to the snippet (1) where you can write the shortcut key of the snippet you want to insert (for faster approach). In our case, we select the try (2) snippet, which will insert the following code:

        void MyMethod()
        {
            try
            {
            
            }
            catch (Exception)
            {
                
                throw;
            }
        }

So, you see, there is predefined try catch block with given standard format, where we can modify it to satisfy our needs. This is small sample, but if you have some large code-block(s) that you use repeatedly, this could be extremely useful.

 

You can also use the code snippets in the ASPX Source code.
Here is an example:

CREATING A CUSTOM CODE SNIPPETS

Visual Studio.NET by default saves the code snippets in C:\User\<Your-username>\Documents\Visual Studio 2010\Code Snippets where you have folder for each category, where you want to use the Code Snippet:

  • SQL
  • Visual Basic
  • Visual C#
  • Visual Web Developer
  • XML

In my case, by default the VS.NET will add the code snippet in Visual Web Developer, because I’m using ASP.NET Web Application.

Here are the steps you need to take in order to create your custom code snippet

1. With right click to your Project on Solution Explorer in your VS.NET, go to ADD –> NEW ITEM

2. Chose an XML file, name it as you wish and change the extension from .xml to .snippet

You will have an empty XML file.

3. Once the file is opened, with right click on the empty surface chose Insert Snippet… and then chose Snippet.
Another way to do this is with the shortcuts using CTRL+K+X.

4. When you insert the Snippet snippet, the following code will be generated

<?xml version="1.0" encoding="utf-8" ?>
<
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>name</ID
>
<
Default>value</Default
>
</
Literal
>
</
Declarations
>
<
Code Language="XML"
>
<![CDATA[
<test>
<name>$name$</name>
$selected$ $end$</test>
]]>
</
Code
>
</
Snippet
>
</
CodeSnippet
>

As you can see, the Code Snippets can be very useful for scenarios like this one. So, this is predefined template of the XML file that we need to modify in order to create our Snippet.

Lets see how

4.a) Firstly, we write the info in the <Header> … </Header> nodes

    <Header>
<
Title>Hajan's Prof. GridView</Title
>
<
Author>Hajan Selmani</Author
>
<
Shortcut>hgridview</Shortcut
>
<
Description>This is my own stylized GridView control.</Description
>
<
SnippetTypes
>
<
SnippetType>Expansion</SnippetType
>
</
SnippetTypes
>
</
Header
>

  • TITLE xml node will show the title of the Snippet when we will search for it. It would be nice to write title by which you will recognize your own snippet (good to manage when having a lot of custom code snippets)
  • AUTHOR is the author, in this case Your Name
  • SHORTCUT, this might be very useful in order to access your own Code Snippet using keyboard shortcut i.e. CTRL+K+X –> <snippets-folder> –> <snippets-shortcut> OR by typing the shortcut of the Code Snippet (we will see later)
  • DESCRIPTION – description of your Code Snippet. Will appear as Tool Tip once you get over the name of your Code Snippet.
  • SNIPPETTYPES – By default, there are two Types: SurroundsWith and Expansion.
    • SurroundsWith will place the Snippet Code around selected piece of code
    • Expansion will insert the Snippet Code at the cursor

In our case, I’m using the Expansion snippet type.

4.b) Next is the <Snippet> … </Snippet> part of the XML file

    <Snippet>
<
Declarations
>
<
Literal
>
<
ID>whiteColor</ID
>
<
Default>#FFFFFF</Default
>
</
Literal
>
<
Literal
>
<
ID>blackColor</ID
>
<
Default>#000000</Default
>
</
Literal
>
<
Literal
>
<
ID>grayColor</ID
>
<
Default>#CCCCCC</Default
>
</
Literal
>
<
Literal
>
<
ID>alternativeRowColor</ID
>
<
Default>#EEEEEE</Default
>
<
ToolTip>Color of the alternative rows in the GridView</ToolTip
>
</
Literal
>
<
Literal
>
<
ID>gridLines</ID
>
<
Default>Vertical</Default> <!--Both, Vertical, Horizontal, None
-->
</
Literal
>
</
Declarations
>
<
Code Language="HTML"
>
<![CDATA[
<asp:GridView ID="GridView1" runat="server" BackColor="$whiteColor$"
BorderColor="$blackColor$" BorderStyle='Solid' BorderWidth='1px' CellPadding='3'
ForeColor='$blackColor$' GridLines='$gridLines$'>
<AlternatingRowStyle BackColor='$alternativeRowColor$' />
<FooterStyle BackColor='$grayColor$' />
<HeaderStyle BackColor='$blackColor$' Font-Bold='True' ForeColor='$whiteColor$' />
<PagerStyle BackColor='#999999' ForeColor='Black' HorizontalAlign='Center' />
<SelectedRowStyle BackColor='$grayColor$' Font-Bold='True' ForeColor='$whiteColor$' />
<SortedAscendingCellStyle BackColor='#F1F1F1' />
<SortedAscendingHeaderStyle BackColor='#808080' />
<SortedDescendingCellStyle BackColor='#CAC9C9' />
<SortedDescendingHeaderStyle BackColor='#383838' />
</asp:GridView>
]]>
</
Code
>
</
Snippet
>
  • DECLARATIONS – contains elements that uses predefined declarations that we later use in the CODE of the Snippet. You may have either LITERAL or OBJECT as an element under DECLARATIONS.
  • LITERAL – We use it to declare the node IDs and Default values that we later use in the CODE. Besides the ID & Default elements, inside Literal we can add Function, ToolTip and Type.
  • TOOLTIP – Used to show tooltip on the particular element, in our case the alternativeRowColor Literal element.
  • CODE – This is the place where we put the Snippet Code that we want the VS.NET to generate for us. First, we define the Code language. In my case its HTML. You can use CSharp, VB, XML, JavaScript, HTML etc. After that, you can see I have written example GridView control with some styles applied in it. However, there are some $name$ values, which are the ID values from the DECLARATIONS that we have created previously. For example, I have BackColor=”$whiteColor$” where whiteColor is #FFFFFF (default value) in the LITERAL element inside DECLARATIONS.

NOTE: There are some more details regarding the difference between LITERAL and OBJECT elements of the <DELACARATIONS> parent element. Hence, if you are interested to read more about the difference, check the link here.

5. Once we have created our Snippet, now we need to Save it.

6. Using CTRL+K+B keyboard shortcut the Code Snippet manager dialog box will open. Once it’s opened, select the Language (1) where you want the code snippet to be saved. In the middle of the dialog box you have list of folders (2) for the snippets that already exists. Click the Import (3) button and find the Snippet we have created previously (probably somewhere in your Project directory).

7. Once you select the file, click OK. The following window will appear

select where you want to save the new custom created snippet and click Ok. I have saved it on My HTML Snippets folder.

---

Once you do that, you are already done.

 

USING THE CUSTOM CREATED SNIPPET

Create new (if you haven’t already) ASPX page and go to source view of the ASPX page.

Then, same as we did previously, using the keyboard shortcuts CTRL+K+X

You see, the TITLE of the GridView is shown. Once we select the title name, the code will be automatically generated, here is my code

You see, even the ToolTip of the value inside AlternatingRowStyle works

 

Even better way to use the Custom Created Code Snippet is by typing the shortcut name. In our case, we have defined shortcut name hgridview. In the ASPX code view, type <hgridview and press TAB.

once you press TAB, the complete code for the GridView will be generated

 

…and here is the GridView in design view

CONCLUSION

In this blog post, we have seen one simple example showing what does this VS.NET feature offers to us. This is an extremely useful feature that we may use to create various Code Snippets for various languages used in VS.NET. Imagine what will you achieve if you have bunch of custom created code-blocks where you always need to make some modifications and you want to use in multiple projects? In this blog post, I have started using Code Snippets that already exists in VS.NET by showing an example in C# code-behind, then you saw how I’ve created custom GridView control using pre-defined styles and the ways to use it within your web application.

Thank you for your time while reading my blog post.

I hope this was helpful and informative.

-

Best Regards,
Hajan

3 Comments

  • You should really try Code Barrel as an alternative to Visual Studio's built-in manager. It is integrated with Visual Studio through a plugin, but is much easier to use. Code Barrel allows tagging, comments, revisions, and more. In addition it is cloud-based so you can get your snippets anywhere! Oh, and it's free.

  • @Keir Davis, thanks for the suggestion. I will definitely try the Code Barrel once I get time. If the Code Barel is what you really say, I will definitely write a blog post about it once I try it ;).

    Thank you,
    Hajan

  • nice one...

Comments have been disabled for this content.