Pages

Friday, July 23, 2010

Code Snippet in VS Studio

Code Snippet is one of the best and easiest way for any developer to increase code productivity. As far I know, there are lots of people who dont know about this feature in VS studio. It is interesting feature which helps you to get a template of your method or property to code it quickly.

I believe everyone knows about intellesense feature that is already there with Visual Studio. There is nothing more I could tell about this lovely feature. While browsing the list of objects in the intellesense window, you would have already seen few icons. These icons provide special meaning. Some of them signifies keywords, some are custom types/classes, some are methods. One of these are Code snippets.






In the above figure, you can see how a code snippet looks like.  Here in the above code, I have just started typing pro.... You will see a prop menu item should be there, which is actually a code snippet for a property stub. If you use TAB to select prop and then press Tab again, you will see something similar to one below:



A new Property will be created which has return type as int and name of the property is MyProperty. As I am using VS 2010 to do this, you will see the automatic property initializer here. But for previous version, you might see a little longer than this property. It will create a variable and also a Property to access that variable. In VS 2010, if you want that property snippet, you will have to use propfull.




In either case, use TAB to stop to each of the literals. If you change the int to float, the return type of the property will also change likewise. Similarly if you press TAB again, and change the name of the variable, it will also reflect to the property.


Just similar to properties, you can also apply Code snippets to methods, structs, classes etc.





Thus in the above figure you can see that testm produces a TestMethod. Hence you can say code snippets enhances the code production in a huge extent.

You can now even add code snippet in the asp.net page.




Here using code snippet  I have added a new update panel. But to remind you, code snippet is added in aspx page in VS 2010.

Code Snippet Manager

Visual Studio comes with Code-snippet manager. This is a tool which enables you to change an existing code snippet and also enlist all the code snippets that are available within the IDE. To check the Code snippet manager, go to Tools menu of Visual studio IDE and choose Code Snippet Manager.





In the above figure you can see you can easily manage the property / code snippets from within the Manager. You can get the location where the actual code snippets are installed. You can even import a new code snippet to your Visual Studio IDE.  By default the custom VS code snippets are loaded from MyDocuments/Visual Studio/Code Snippets.


Custom Code Snippet

Yes, in spite of large number of code snippets available for the IDE, I always find something short while writing my code. All of us has unique coding styles. Visual Studio IDE offers custom Code snippets that you can produce just by writing an XML schema definition and placing it on Code Snippets folder inside MyDocuments folder with custom extension .snippet.

Let us write an snippet which we need most of the times while writing code in WPF. We need to invoke events called OnPropertyChanged and OnPropertyChanging. Inspite of writing this several times lets fix this issue somewhat.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>propnch</Title>
            <Shortcut>propnch</Shortcut>
            <Description>Code snippet for property and backing field and ensure that it invokes INotifyPropertyChanigng and INotifyPropertyChanged</Description>
            <Author>Abhishek</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 
        { 
            this.OnPropertyChanging("$property$");
            $field$ = value;
            this.OnPropertyChanged("$property$");
        }
    }
    $end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

So from the above code you can see a new Property Snippet is added to the system. To try that you just go to the code window and type propnch. It will produce the output.



Now lets explain this a bit.

We divide the whole XML into three parts :

1. The header section :

<Header>
    <Title>propnch</Title>
    <Shortcut>propnch</Shortcut>
    <Description>Code snippet for property and backing field and ensure that it invokes INotifyPropertyChanigng and INotifyPropertyChanged</Description>
    <Author>Abhishek</Author>
    <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
</Header>

In this section, I defined the Title, which represents the name of the snippet. The shortcut defines what will appear in the intellesense menu. The description comes as a tooltip.
SnippetTyes defines the type of the snippet. In general we leave it as Expansion, but it also has few other types like : Surroundswith and Refactoring.

2. Variables :
In the second part we define variables for which we want to input during the use of it.

<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>

You can see in the above XML segment, I have defined literals like type which defaults to int, property which defaults to MyProperty and field which defaults to myVar. These variables can be accessed using $ sign, which indicates where these variables will be placed. In code, anything written inside $ sign will be replaced by users action.

3. Declaration:

<Code Language="csharp"><![CDATA[

    private $type$ $field$;

    public $type$ $property$
    {
        get 
        { 
            return $field$;
        }
        set 
        { 
            this.OnPropertyChanging("$property$");
            $field$ = value;
            this.OnPropertyChanged("$property$");
        }
    }
    $end$]]>
            </Code>
        </Snippet>

In the final part we define the code. You can see, in my example I used C# as my language. The code is written inside the Code element and we put parameters wrapped within $ sign as I have already told you that these will be replaced when we use it in code.
Thus you can see, the variables are replaced within the code while you use it. You can use TAB to move from one variable to another.

I hope you can create more snippets like this to enhance your IDE capabilities.

Thanks for reading.

3 comments:

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.