This page has been translated using an automatic translation service and the translation may not be very accurate.

Introduction to the technology "Snippet Tails" (English)

If you use this code and feel it is a useful tool, consider making a donation (through PayPal) to help support the project. You can donate as little or as much as you wish, any amount is greatly appreciated!

Italian page For the original Italian page, please click on the link: http://guru4.net/articoli/code-snippets/default.aspx

The most recent IDE Microsoft for NET have introduced one new technology in order to increase the productivity of the sviluppatori, call "Snippet Tails". Draft of template for the automatic generation of the blocks of code of more common use, easy richiamabili from the atmosphere of development and completely personalizzabili.

Currently the IDE that support the technology Snippet Tails are:

  • Microsoft Visual Study 2005

  • the products "express" derive from Microsoft Visual Study to you 2005, like as an example Microsoft Visual C # 2005 Express Edition

Famous: in this article reference will be made to uses of the Snippet Tails in Visual Study 2005 BETA 2. It is possible, as already happened in the passage of VS 2005 from BETA 1 to BETA 2, than Microsoft contributions of the changes to the technology with the release of the definitive version of the product; for information and documentations more complete and modernized sends back to the situated Microsoft Visual Study.

We have to disposition two techniques of generation of the code:

  • Insert Snippet (or Expansion Template) for the generation of types, more common members and of the costrutti of the language

  • Surround With in order to insert a block of code selected in a costrutto of the language

To activate the Snippets Tails

The way simpler in order to comprise the operation of snippet and the their usefullnesses is that one to try them. We can recall one snippet:

  1. from menu the Edit | Intellisense, selecting "Insert Snippet..." or "Surround With..."

  2. by means of shortcuts from keyboard, using the combinations: "Ctrl k, Ctrl x" or "Ctrl k, Ctrl s"

  3. from menu the contestuale attivabile with the click of the skillful key of the mouse, selecting "Insert Snippet..." or "Surround With..."

  4. through Intellisense (attivabile also with the combination of keys "spaziatrice Ctrl Barra"), digitando shortcut the recorded correspondent to a snippet, therefore pressing key TAB in order to activate the insertion of the code automatic rifle (normally from the window of Intellisense is necessary to press 2 times key TAB: before in order to select the snippet, the second one in order to activate it)

Practical example of I use: Insert Snippet...

We make an example concrete. In the code of one class digitiamo prop in order to activate snippet of creation of one the property for the class:

Selection of the Snippet Tails for the insertion of 
one property

Pressing two times key TAB comes inserted the code that creates one new property in reading and variable relative writing and the private one of support:

Code generated from the Snippet Tails for the 
insertion of one property

The portions evidenced to the inside of the generated code are noticed: to we it does not remain that to replace the predefined values (int for the type of return, myVar for the name of the field inner of support and MyProperty for the name of the property) with our values for having the property correctly implemented (it is possible to move itself easily between the several one placeholder by means of key TAB)

Practical example of I use: Surround With...

The seen class of example has not been inserted in a namespace: we make up for endured, always using one snippet.
Selezionamo the code of our class, therefore with the skillful key of the mouse we activate the menu contestuale (or using one of the modalities listed previously for the activation of the Snippets Tails):

Contestuale Menu:Surround With...

After to have activated the snippet, we select between the cartelle available (covered of recording of snippets)"Visual C #", therefore voice "namespace":

Selection of the Snippet Tails for the added one of 
the namespace

The code of our demonstrative class is hour inserted in a namespace. In order to complete the operation, like approval for the insertion of the property, it does not remain to us that to replace the placeholder MyNamespace with the space of the names wished:

Code generated from the Snippet Tails for the added 
one of the namespace

Management of the Snippets Tails

Microsoft puts to disposition a series of predefined models that they cover the more common requirements. It is possible to visualize the tails snippets records to you selecting Tails Snippets Manager from menu the Tools.
As we can see leaf through the bookcase of snippets available we notice that draft of simple rows XML (with extension snippet), present in the folder "VC#\Snippets \"of directory of installation of Visual the Study (as an example: "C:\Programmi\Microsoft Visual Study 8\VC#\Snippets \"). Be a matter itself of text rows you mail in a normal school folder, we can modify the template ones, create some of new leaving from zero or modifying one of those already present: it does not remain to us that to see "as the snippets are made".

Outline of the Snippet Tails

We open with editor of text (also a notepad, but using Visual Study 2005 we will have also Intellisense) one of the snippet simpler: class.snippet, that new class creates the declaration of one:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>class</Title>
      <Shortcut>class</Shortcut>
      <Description>Code snippet for class</Description>
      <Author>Microsoft Corporation</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
        <SnippetType>SurroundsWith</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>name</ID>
          <ToolTip>Class name</ToolTip>
          <Default>MyClass</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[class $name$
  {
    $selected$$end$
  }]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Although complete outline XML previews various elements, of continuation we will stop ourselves alone on the nodes of greater interest. For the complete outline Study is sent back to the documentation of Visual.

Element Description
Header It contains information generates them for the definition of the Snippet Tails
Title Title of the Snippet Tails
Shortcut Text used like shortcut for the insertion of the Snippet Tails
Description Description of the Snippet Tails
Author Author of the Snippet Tails
SnippetTypes It indicates in quale/i categories re-enters the Snippet Tails (to see SnippetType)
SnippetType It can assume the value SurroundsWith or ExpansionIndica and indicates in which category the Snippet Tails are available
Snippet It contains relative the specific declarations to the code of the Snippet Tails
Literal It defines one variable literal used in the code of the Snippet Tails. It is possible to declarethe ID with which it will come recalled, the descriptive ToolTip, the value of Default, the Type of variable and the Function to execute when the literal it receives the focus in the IDE (in the snippet of example - declaration of a class - last the two elements are not uses you)
Object With an analogous structure to Literal, it defines an element used in the code of the snippet but that probably it is defined to the outside of the snippet same
Tails Using the Literal and the Object it declares to you, defines the code that will come inserted recalling the Snippet Tails

We notice, in the example of code brought back over, than the variable ones (Literal or Object) they come recalled in the element Tails enclosing them between two characters $. If we as an example define a literal with ID = "MyLiteral" we will have to use the following sintassi:

$MyLiteral$

The code of class.snippet introduces but also two elements, recall to you like if they were variable but... it does not declare to you: $selected$ and $end$. Draft of two Literal predefined and interpreted from the IDE: the first one ("selected") indicates the position begins them of the cursore for the selection after that the snippet it has been activated, while "end" indicates some, like easy imaginable, the final position.

To create Snippet Tails

It arrives you to this point, having a little familiarity with XML and C #, will be already all much luminosity and, probably, you will be astonished - like it they have been I - of the semplicitÓ with which it is possible to realize one snippet. We are therefore ready in order to write our first Snippet Tails!

We imagine of wanting to create a model for the generation of the code of valorization of a DataView, that is that it implements in way automatic rifle the operations of:

  • creation of one logon to SQL Serveur

  • creation of a SqlDataAdapter using a commando T-SQL

  • creation and valorization of DataSet from the SqlDataAdapter

  • valorization of the DataView like DefaultView of the table of the DataSet

For parametrizzare the code and rendering it generic, therefore to be used like model, we must define variable following (literal):

  • ConnectionString - for the logon to database the SQL Serveur

  • Sql - for the formulation of commando T-SQL to execute

  • TableName - in order to define which table to use for the reading of the data

It does not remain to us that to create new rows of text, called dataview.snippet and to insert the following code:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>DataView</Title>
      <Shortcut>dataview</Shortcut>
      <Description>Code snippet per valorizzare un DataView</Description>
      <Author>Matteo Casati</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
        <SnippetType>SurroundsWith</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>ConnectionString</ID>
          <ToolTip>Stringa di connessione al database di SQL Server</ToolTip>
          <Default>Data Source=localhost;Initial Catalog=MyDatabase;User ID=sa;Password=;</Default>
        </Literal>
        <Literal>
          <ID>Sql</ID>
          <ToolTip>Istruzione SQL da eseguire</ToolTip>
          <Default>SELECT * FROM MyTable</Default>
        </Literal>
        <Literal>
          <ID>TableName</ID>
          <ToolTip>Nome della tabella da cui leggere i valori</ToolTip>
          <Default>MyTable</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
  <![CDATA[
      
SqlConnection cn = new SqlConnection("$ConnectionString$");
string sql = "$Sql$";
SqlDataAdapter cmd = new SqlDataAdapter(sql, cn);

DataSet ds = new DataSet();
cmd.Fill(ds, "$TableName$");

DataView dv = ds.Tables["$TableName$"].DefaultView;

      ]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

In way of all the analogous one we will be able to create models for the generation of the code that we think "repetitive" and that, normally, we write (or we could write) making "copy, it glue, it finds, you replace".

Useful instruments

As we have seen, the snippets they are of normal rows XML. Instruments exist however that us simplify the creation of snippets, reducing the error possibility:

  • Visual Study 2005: also not supplying a editor visual for the generation of snippets, outline XML supplies the Intellisense support second demanded from the Snippets Tails

  • Snippy - C # Tails Snippet Editor is a editor visual for the creation of snippets in C #

  • Snippet Editor for Visual Basic 2005 Beta 2 is a editor visual (distributed from Microsoft and suit of code source) for the creation of snippets in VB.NET

To add Snippet Tails to the snippet personal

Because ours snippets are usable are possible to import using them the instrument "Tails Snippets Manager" (from menu the Tools di Visual Study) or, more simply, to copy them in the folder "My Snippets Tails", situated - for snippets the C # - in "Visual Studio\Code Snippets\VC#\My Snippets Tails \" that current of Windows is found in the folder of documents of the customer.

Conclusions

The new IDE Microsoft offer a set of predefined tails snippets. The snippets they are created using a small set of elements XML and serve in order to simplify and to velocizzare the writing of the code blocks more common use. In adding to the predefined tails snippets, the sviluppatori have the possibility to create own the template ones that, once it records to you, will be usable to the inside of the development atmosphere.