Tuesday, September 8, 2009

Code Snipet : Step by step guideline from creation to installation of a snippet


Contents

A. Introduction: What is Code Snippet??

B. Can we create our own code snippet ??

Create a .snippet file (Step by Step)

C. How to Manage Code Snippets inside VS Editor ??

Add/Register a snippet

Remove a snippet

Modify an existing snippet

D. Code Snippet Functions

GenerateSwitchCases( EnumerationLiteral )

ClassName()

SimpleTypeName( TypeName )

E. Is it possible to share it with all of my team mates ??

Create a vsi installer (Step by Step)

F. An example

Singleton Pattern Example: 1

Singleton Pattern Example: 2



A. Introduction: What is Code Snippet??



Code snippets are ready-made snippets of code we can quickly insert into our code.

We can use code snippets to type a short alias, and then expand it into a common programming construct.

For example, the prop code snippet creates an empty property block.

Benefits

  • Write once use anywhere: Reduce the repeatable writing of code effort.

  • Define/Maintain a Coding Standard to be used for any Project/Organization.

  • Provide easier way to write/define a group of code. Like a code snippet can generate a Switch case statement only through its shortcut (as myswitch)

  • Easy to use as well as create and also easily maintainable.

  • Share management with other developers

How to Use

Step 1. In the Code Editor by typing a short name for the alias or a code snippet shortcut


Step 2. Press two times Tab key. It will generate a Property block automatically

Step 3. Once a code snippet has been chosen, the text of the code snippet is inserted automatically at the cursor position. At this point, any editable fields in the code snippet are highlighted in light green, and the first editable field is selected automatically.


When a field is selected, users can type a new value for the field. Pressing TAB cycles through the editable fields of the code snippet; pressing SHIFT+TAB cycles through them in reverse order. Clicking on a field places the cursor in the field, and double-clicking on a field selects it.

Only the first instance of a given field is editable; when that field is highlighted, the other instances of that field are outlined. When you change the value of an editable field, that field is changed everywhere it is used in the code snippet.


B. Can we create our own code snippet ??

Yes we can create and utilize custom code snippets, in addition to the code snippets that are included with Visual Studio by default.

IntelliSense Code Snippets are XML files with a .snippet file name extension that adhere to the IntelliSense Code Snippet XML schema.

To create a .snippet file


  1. Go to File è New è File.

  2. From Template select XML File and then click Open, it will open a blank XML file for editing.

  3. On the File menu, click Save <XMLFileName>.

  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.

Writing the Code


Now we have an XML file, we need to write the XML code that makes up our code snippet.


  1. Below the automatically generated line of XML, add a CodeSnippets element with the proper xmlns attribute value, and a CodeSnippet element to create an individual code snippet. For example:

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

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

    <CodeSnippet Format="1.0.0">

    </CodeSnippet>


    </CodeSnippets>

    Note : This is the standard defined by VS that every snippet file must start with the CodeSnippets tag, identifying the namespace that defines the code snippet schema. Within these tags, each snippet is defined using the CodeSnippet tag, which will in turn contain the definition of the snippet itself:


  2. Add a header section to the code snippet. Each code snippet has a header area and a body area, known as the Header and Snippet, respectively. The Header area mainly contains three tags:


    • Title: The name of the snippet

    • Description: The description of the snippet

    • Shortcut: Shortcut names provide a way for us to insert IntelliSense Code Snippets into our code by typing a shortcut name and then pressing Tab.

    Apart from these Tags we can also use Author , SnippetTypes tags like:

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

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

    <CodeSnippet Format="1.0.0">

    <Header>

    <Title>Property</Title>

    <Shortcut>propcs</Shortcut>

    <Description>Code snippet to define a property .</Description>

    <Author>Anand Ranjan</Author>

    <SnippetTypes>

    <SnippetType>Expansion</SnippetType>

    </SnippetTypes>

    </Header>

    </CodeSnippet>

    </CodeSnippets>

    What is what : A snapshot of Code Snippet Manager – Uses of Header Tag elements



    What is what : A snapshot of VS Editor – Uses of Header Tag elements



  3. Add the elements that define the code snippet itself. For example:

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

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

    <CodeSnippet Format="1.0.0">

    <Header>

    <Title>Property</Title>

    <Shortcut>propcs</Shortcut>

    <Description>Code snippet to define a property .</Description>

    <Author>Anand Ranjan</Author>

    <SnippetTypes>

    <SnippetType>Expansion</SnippetType>

    </SnippetTypes>

    </Header>

    <Snippet>

    <Code Language="csharp">

    </Code>

    </Snippet>

    </CodeSnippet>


    </CodeSnippets>

  4. Inside the Code element of Snippet Tag, add the C# code for the snippet. All snippet code must be placed between <![CDATA[ and ]]> brackets. For example

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


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

    <CodeSnippet Format="1.0.0">

    <Header>

    <Title>Property</Title>

    <Shortcut>propcs</Shortcut>

    <Description>Code snippet to define a property .</Description>

    <Author>Anand Ranjan</Author>

    <SnippetTypes>

    <SnippetType>Expansion</SnippetType>

    </SnippetTypes>

    </Header>

    <Snippet>

    <Code Language="csharp">

    <![CDATA[

    /// <summary>

    /// Property to set a $property$

    /// </summary>

    private $type$ $defaultValue$;

    public $type$ $property$

    {

    get

    {

    return $defaultValue$;

    }

    set

    {

    $defaultValue$ = value;

    }

    }

    $end$]]>

    </Code>

    </Snippet>

    </CodeSnippet>


    </CodeSnippets>

  5. We may have portions of code snippets that we want to be replaced by the person inserting them. Code Snippets provide this ability with the Literal and Object elements.

    The Literal element is used to identify a replacement for a piece of code that is entirely contained within the snippet, but will likely be customized after it is inserted into the code. For example, literal strings, numeric values, and some variable names should be declared as literals. The optional <Declarations> section is used to define replaceable sections in the snippet. Replaceable sections are denoted with $name in the <Code> section and are the sections displayed green and configurable by the developer using the snippet.


To create a literal replacement

  1. Locate the Snippet element of the code snippet.

  2. Add a Declarations element as a child of the Snippet element. The Declarations element is used to group replacement declarations.

  3. Add a Literal element as a child of the Declarations element. The Literal element specifies an individual literal. A code snippet may have more than one literal replacement.

  4. Add an ID element as a child of the Literal element. The text value of this element specifies the name that you will use to reference the literal in the Code element.

  5. Add a Default element as a child of the Literal element. The text value of the Default element specifies the default value of the literal when you insert the code snippet.

  6. Optionally, add the Function and/or ToolTip elements.

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

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

<CodeSnippet Format="1.0.0">

<Header>

<Title>Property</Title>

<Shortcut>propcs</Shortcut>

<Description>Code snippet to define a property .</Description>

<Author>Anand Ranjan</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>Value</Default>

</Literal>

<Literal>

<ID>defaultValue</ID>

<ToolTip>The default value for this property.</ToolTip>

<Default>intValue</Default>

</Literal>

</Declarations>

<Code Language="csharp">

<![CDATA[

/// <summary>

/// Property to set a $property$

/// </summary>

private $type$ $defaultValue$;

public $type$ $property$

{

get

{

return $defaultValue$;

}

set

{

$defaultValue$ = value;

}

}

$end$]]>

</Code>

</Snippet>

</CodeSnippet>


</CodeSnippets>


What is what : A snapshot of VS Editor – Generated code using snippet


Creating an Object Replacement

The Object element is used to identify an item that is required by the code snippet but is likely to be defined outside of the snippet itself. For example, Windows Forms controls, ASP.NET controls, object instances, and type instances should be declared as objects. Object declarations require that a type be specified.

To create an object replacement

  1. Locate the Snippet element of the code snippet.

  2. Add a Declarations element as a child of the Snippet element. The Declarations element is used to group replacement declarations.

  3. Add an Object element as a child of the Declarations element. The Object element specifies an individual object. A code snippet may have more than one object replacement.

  4. Add an ID element as a child of the Object element. The text value of this element specifies the name that you will use to reference the object in the Code element.

  5. Add a Type element as a child of the Object element The text value of the Default element specifies the type of the object.

  6. Add a Default element as a child of the Object element. The text value of the Default element specifies the default value of the object when you insert the code snippet.

  7. Optionally, add the Function and/or ToolTip elements.

Example :

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


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

<CodeSnippet Format="1.0.0">

<Header>

<Title>Property</Title>

<Shortcut>getcustomer</Shortcut>

<Description>Code snippet to interact with database .</Description>

<Author>Anand Ranjan</Author>

<SnippetTypes>

<SnippetType>Expansion</SnippetType>

</SnippetTypes>

</Header>

<Snippet>

<!-- Add additional Snippet information here -->

<Declarations>

<Literal>

<ID>SqlConnString</ID>

<ToolTip>Replace with a SQL connection string.</ToolTip>

<Default>"SQL connection string"</Default>

</Literal>

<Object>

<ID>SqlConnection</ID>

<Type>System.Data.SqlClient.SqlConnection</Type>

<ToolTip>Replace with a connection object in your application.</ToolTip>

<Default>dcConnection</Default>

</Object>

</Declarations>

<Code Language="CSharp">

<![CDATA[

daCustomers = new SqlClient.SqlDataAdapter();

selectCommand = new SqlClient.SqlCommand($SqlConnString$);

daCustomers.SelectCommand = selectCommand;

daCustomers.SelectCommand.Connection = $SqlConnection$;

]]>

</Code>

</Snippet>

</CodeSnippet>


</CodeSnippets>

C. How to Manage Code Snippets inside VS Editor ??

The Code Snippets Manager allows us to set the directories and individual snippets that we want available to insert into your code.

To access the Code Snippets Manager

  • On the Tools menu, click Code Snippets Manager or alternately we can use

Key ctrl + KB

This will open a code snippet manager dialog box like




To add a directory to the Code Snippet Manager


  1. In the Language list, select the language that you want to add a directory to.

  2. Click Add. This opens the Code Snippets Directory window.

  3. Select the directory that we want to add to the Code Snippets Manager and click OK.The directory will now be used to search for available code snippets.


To remove a directory from the Code Snippet Manager

  1. Select the directory that you want to remove.

  2. Click Remove.

To import a code snippet into the Code Snippet Manager

  1. In the Language list, select the language that you want to add the code snippet.

  2. Select the existing folder that you want to place the imported code snippet into.

  3. Click Import. This opens the Code Snippets Directory window.

  4. Select the code snippet file that you want to add to the Code Snippets Manager and click OK.The code snippet is now available for insertion into the code editor.


Select the location for code snippet and click on finish




To modify an existing Snippets

IntelliSense Code Snippets are XML files with a .snippet file name extension that can be easily modified using any XML editor, including Visual Studio 2005.

To modify an existing IntelliSense Code Snippet


  • Use the Code Snippets Manager to locate the snippet that you want to modify.


  • On the File menu, click Open, and click File.




  • Modify the snippet.

  • On the File menu, click Save.

    D. Code Snippet Functions

    There are three functions available to use with Visual C# code snippets,

    1. GenerateSwitchCases( EnumerationLiteral )

      Generates a switch statement and a set of case statements for the members of the enumeration specified by the EnumerationLiteral parameter. The EnumerationLiteral parameter must be either a reference to an enumeration literal or an enumeration type.

      For example:

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


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

      <CodeSnippet Format="1.0.0">

      <Header>

      <Title>myswitch</Title>

      <Shortcut>myswitch</Shortcut>

      <Description>Code snippet for switch statement</Description>

      <Author>Microsoft Corporation</Author>

      <SnippetTypes>

      <SnippetType>Expansion</SnippetType>

      </SnippetTypes>

      </Header>

      <Snippet>

      <Declarations>

      <Literal>

      <ID>expression</ID>

      <ToolTip>Expression to switch on</ToolTip>

      <Default>switch_on</Default>

      </Literal>

      <Literal Editable="false">

      <ID>cases</ID>

      <Function>GenerateSwitchCases($expression$)</Function>

      <Default>default:</Default>

      </Literal>

      </Declarations>

      <Code Language="csharp">

      <![CDATA[

      switch ($expression$)

      {

      $cases$

      }

      ]]>

      </Code>

      </Snippet>

      </CodeSnippet>


      </CodeSnippets>

      Usage example :


      What is what : A snapshot of VS Editor – To select a snippet


      Replace swich_on ( Highlighted in green) with our enum and press two times enter.


      What is what : A snapshot of VS Editor – End result using snippet



    2. ClassName()

      Returns the name of the class that contains the inserted snippet.

      For example to write a constructor for a class with an input parameter,

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

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

      <CodeSnippet Format="1.0.0">

      <Header>

      <Title>Common constructor pattern</Title>

      <Shortcut>myconstructor</Shortcut>

      <Description>Code Snippet for a constructor</Description>

      <Author>Anand Ranjan Pandey</Author>

      <SnippetTypes>

      <SnippetType>Expansion</SnippetType>

      </SnippetTypes>

      </Header>

      <Snippet>

      <Declarations>

      <Literal>

      <ID>type</ID>

      <Default>int</Default>

      </Literal>

      <Literal>

      <ID>name</ID>

      <Default>field</Default>

      </Literal>

      <Literal Editable="false">

      <ID>classname</ID>

      <ToolTip>Class name</ToolTip>

      <Function>ClassName()</Function>

      <Default>ClassNamePlaceholder</Default>

      </Literal>

      </Declarations>

      <Code Language="CSharp" Kind="CData">

      <![CDATA[

      public $classname$ ($type$ $name$)

      {

      this._$name$ = $name$;

      }

      private $type$ _$name$;

      ]]>

      </Code>

      </Snippet>

      </CodeSnippet>


      </CodeSnippets>

      Usage Example :




      What is what : A snapshot of VS Editor – End result using snippet


    3. SimpleTypeName( TypeName )

      It reduces the TypeName parameter to its simplest form in the context in which the snippet was invoked.

      For example : below example shows how to use the SimpleTypeName function. When this snippet is inserted into a code file, the $SystemConsole$ literal will be replaced with the simplest form of the Console type in the context in which the snippet was invoked.

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


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

      <CodeSnippet Format="1.0.0">

      <Header>

      <Title>Console_WriteLine</Title>

      <Shortcut>mycw</Shortcut>

      <Description>Code snippet for Console.WriteLine</Description>

      <Author>Anand Ranjan Pandey</Author>

      <SnippetTypes>

      <SnippetType>Expansion</SnippetType>

      </SnippetTypes>

      </Header>

      <Snippet>

      <Declarations>

      <Literal Editable="false">

      <ID>SystemConsole</ID>

      <Function>SimpleTypeName(global::System.Console)</Function>

      </Literal>

      </Declarations>

      <Code Language="csharp">

      <![CDATA[

      $SystemConsole$.WriteLine();

      ]]>

      </Code>

      </Snippet>

      </CodeSnippet>


      </CodeSnippets>

      Usage example :




      What is what : A snapshot of VS Editor – End result using snippet


    E. Is it possible to share it with all of my team mates ??

    Yes, To get a code snippet to appear in the code editor, it must be placed on a user's computer and imported with the Code Snippet Manager. To make this process easier, we can place our snippet file inside of a Visual Studio Installer (.vsi) file and use the Visual Studio Content Installer to place the file in the correct location. The .vsi file can then be easily shared with other developers throughout the community.

    Steps to create a .vsi file :

    Visual Studio Content Installer (.vsi) files are used to exchange Visual Studio content in the developer community. A .vsi file is a renamed .zip file that contains these components:

    • An XML .vscontent file that describes the content.

    • The content files.

    Step 1: File è New è File

    Step 2: Select XML file type from Template

    Step 3: Add the files/files inside the <FileName> Tag as per given Schema. For schema information, see Visual Studio Content Installer Schema Reference

    In my case the .vscontent file has included all the above examples:

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

    <VSContent xmlns="http://schemas.microsoft.com/developer/vscontent/2005">

    <Content>

    <FileName>getCustomer.snippet</FileName>

    <FileName>myconstructor.snippet</FileName>

    <FileName>mycw.snippet</FileName>

    <FileName>myswitch.snippet</FileName>

    <FileName>propcs.snippet</FileName>

    <FileName>singletonts.snippet</FileName>

    <FileName>singletontswl.snippet</FileName>

    <DisplayName>Sample Code Snippet</DisplayName>

    <Description>A code snippet created for this example</Description>

    <FileContentType>My Code Snippet</FileContentType>

    <ContentVersion>1.0</ContentVersion>

    <Attributes>

    <Attribute name="language" value="csharp"/>

    </Attributes>

    </Content>


    </VSContent>

    Step 4: Save the file with extension .vscontent like MyCodeSnippet.vscontent

    Step 5: keep the .vscontent file in the same directory as the other files that are related to the community component



    Step 6: Select the folder right-click, select Send To, and click Compressed (zipped) Folder. The selected files are compressed into a single .zip file.

    Step 7: Rename the extension of the .zip file to .vsi

    Step 8: Go to C:\...\My Documents\Visual Studio <version>\Addins\

    Step 9: Paste the early created .vsi file into this folder. In my case I am using Visual

    Studio 2008




    Step 10: Now your newly created Code Snippets is ready to use inside Visual Studio

    2008 Editor.

    F. An example

    Let us take an example of Singleton class which is almost used in every project. In this example I will create a code snippet, which will generate the code using the concept of Singleton class.

    Singleton Example 1 :

    In this code snippet the implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

    File name: singletontswl.snippet

    Code :

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

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

    <CodeSnippet Format="1.0.0">

    <Header>

    <Title>Thread safe Singleton Pattern with Lock</Title>

    <Shortcut>singletontswl</Shortcut>

    <Description>Code Snippet for a singleton class : Thread-safe with locks</Description>

    <Author>Anand Ranjan Pandey</Author>

    <SnippetTypes>

    <SnippetType>Expansion</SnippetType>

    </SnippetTypes>

    </Header>

    <Snippet>

    <Declarations>

    <Literal>

    <ID>instancename</ID>

    <Default>instance</Default>

    </Literal>

    <Literal>

    <ID>instanceobject</ID>

    <Default>Instance</Default>

    </Literal>

    <Literal>

    <ID>lockobject</ID>

    <Default>padlock</Default>

    </Literal>

    <Literal Editable="false">

    <ID>classname</ID>

    <ToolTip>Class name</ToolTip>

    <Function>ClassName()</Function>

    <Default>ClassNamePlaceholder</Default>

    </Literal>

    </Declarations>

    <Code Language="CSharp" Kind="CData">

    <![CDATA[

    static $classname$ $instancename$ =null;

    static readonly object $lockobject$ = new object();

    $classname$()

    {

    }



    public static $classname$ $instanceobject$

    {

    get

    {

    lock ($lockobject$)

    {

    if ($instancename$==null)

    {

    $instancename$ = new $classname$();

    }

    return $instancename$;

    }

    }

    }

    ]]>

    </Code>

    </Snippet>

    </CodeSnippet>


    </CodeSnippets>

    Now we register this snippet using Code Snippet Manager and used in our singleton class as

    After pressing Tab the end result is :


    Singleton Example 2:

    In this code snippet the implementation is thread-safe without using lock.

    File name: singletonts.snippet

    Code :

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

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

    <CodeSnippet Format="1.0.0">

    <Header>

    <Title>Thread safe Singleton Pattern</Title>

    <Shortcut>singletonts</Shortcut>

    <Description>Code Snippet for a singleton class : Thread-safe without using locks</Description>

    <Author>Anand Ranjan Pandey</Author>

    <SnippetTypes>

    <SnippetType>Expansion</SnippetType>

    </SnippetTypes>

    </Header>

    <Snippet>

    <Declarations>

    <Literal>

    <ID>instancename</ID>

    <Default>instance</Default>

    </Literal>

    <Literal>

    <ID>instanceobject</ID>

    <Default>Instance</Default>

    </Literal>

    <Literal Editable="false">

    <ID>classname</ID>

    <ToolTip>Class name</ToolTip>

    <Function>ClassName()</Function>

    <Default>ClassNamePlaceholder</Default>

    </Literal>

    </Declarations>

    <Code Language="CSharp" Kind="CData">

    <![CDATA[

    static readonly $classname$ $instancename$=new $classname$();

    // Explicit static constructor to tell C# compiler

    // not to mark type as beforefieldinit

    static $classname$()

    {

    }

    $classname$()

    {

    }



    public static $classname$ $instanceobject$

    {

    get

    {

    return $instancename$;

    }

    }

    ]]>

    </Code>

    </Snippet>

    </CodeSnippet>


    </CodeSnippets>

    Now we register this snippet using Code Snippet Manager and used in our singleton class as




    After pressing Tab the end result is :



    That’s all for Code Snippets. Hope you will enjoy it.

    How to use Code

    Note: To use the sample example follow these steps:

    1. Unzip the folder MyCodeSnippets.zip any directory you want.

    2. Open Code Snippet Manager and add folder MyCodeSnippets


    3. Now snippets are ready to use.

    Note: All above mentioned examples are included in MyCodeSnippets.zip file which you can download Here


  • Cheers By,

    Anand Ranjan Pandey