Use the code snippet in VS to improve development efficiency

Source: Internet
Author: User
Tags repetition

Http://www.cnblogs.com/anderslly/archive/2009/02/16/vs2008-code-snippets.html

Http://www.cnblogs.com/jaic-xiao/archive/2008/10/14/Jie_Shao_Net_Gong_Ju_Code_Snippet_Yu_Sql_Server_2008_Gong_ Ju_ssms_tools_pack.html

Preface

Talking about templates in VS, I've covered how to create a project/item template that saves a lot of repetitive work when creating a project, which can improve development efficiency. After creating the project and the file, we have to start the specific coding, then there is a new repetitive work, it is necessary to write some similar or identical code, we need a way to manage the code, reduce the repetition of input.

A common example of this code might be when using the For statement structure:

Code
Int[] Array = {1, 2, 3, 4, 5};
for (int i = 0; i < array. Length; i++)
{
Console.WriteLine (Array[i]);
}


Or

Code
list<string> names = new List<string> {"Anders", "Bill", "Clark", "David"};
for (int i = 0; i < names. Count; i++)
{
if (Names[i]. StartsWith ("A"))
{
Console.WriteLine (Names[i]);
}
}


Obviously, the code for these two for loops is very similar: Enter for, select a variable to use as an index, the variable has an upper value, and several parentheses and semicolons. And the vast majority of the For loop is so, how to reduce the repetition of the input? One way to think of it is to save a for-loop code somewhere, such as a file, where you need a for, copy it, and change the variable name, initial value, and upper limit to use it.

The developers of VS are thoughtful and provide code snippet functionality to implement the above ideas. It saves the template for the For Loop code, and then gives it a shortcut key for. Now in the editor (which needs to be a C # file), enter for, and press TAB twice in succession, the following code appears:


Not only for the basic code, but also to locate the name of the variable, if you need to modify the variable name, if you want to change the index, the following two I will automatically change to index, and then press TAB, the cursor will jump to the next dark display, that is, length, here can modify the upper limit of index, Then enter, and the cursor jumps to the code body for the For loop:


Isn't it convenient? There are many other snippet, such as the input CW, press TAB twice to come out Console.WriteLine ().

Many times, the same functionality is different in different languages, so code Snippet (hereinafter referred to as Snippet) is language-specific, meaning that C # Snippet cannot be used for vb.net. The snippet in VS2008 supports C #, vb.net, and XML.

Management of Snippet

First of all, VS2008 provides a lot of built-in snippet, and we can also write our own or write to others in the import vs. Open the Code Snippets Manager window via the menu tools, Code Snippets Manager (or press ctrl+k, CTRL+B):


You can see the language list above, and now the C # is selected. You can import new snippet by importing. When using NUnit, because of the characteristics of the test code, there will be a lot of repeated input, so Scott Bellware provides NUnit snippet, I put it on my own blog: Bellwarenunitsnippet. Now import the. snippet file in the package.


Well, it's ready to use. For example, to enter a TC, press TAB twice, and the code comes out like this:


Enter the name of the testcase, enter it so you can type in the test code. Look at this snippet, there is only one change, it is testcase place.

Next, let's analyze the structure of the snippet file so that you can write your own snippet.

Snippet definition file parsing

Let's look at how snippet is implemented. According to the above TC example, we can assume that to store snippet, at least need the template code, placeholder, language type, shortcut keys, a few key information, each snippet. In fact, VS keeps this information in an XML file that corresponds to some node, similar to the template manifest file in the previous article.

The file that holds the snippet is an XML file, but its extension is. snippet. A snippet file can contain multiple snippet, just like the bellwarenunit.snippet above. Its basic structure is as follows:

XML Code
<?xml version= "1.0" encoding= "Utf-8"?>
<codesnippets xmlns= "Http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet" >
<codesnippet format= "1.0.0" >
<Header>
<title>code Snippet for Debug.WriteLine method.</title>
<Shortcut>dw</Shortcut>
<author>anders cui</author>
</Header>
<Snippet>
<code language= "CSharp" >
<! [cdata[
Debug.WriteLine ("Text");
]]>
</Code>
</Snippet>
</CodeSnippet>
<!--other snippets--
</CodeSnippets>


Now create a new XML file, enter the above code, here our snippet is the input Debug.WriteLine code. The root node of the file is codesnippets and can contain multiple <CodeSnippet> nodes. Notice its namespace, and with this, it's much easier to edit in vs.

Focus on the <CodeSnippet> node, which represents a snippet. It must contain a format Attribute (always see the discussion of Attribute and property, so keep it here) to represent the snippet version. In addition it must contain two sub-nodes:<Header> and <Snippet>.

For <Header> nodes, the most important is the title and shortcut, the name and accelerator of the snippet, and Snippettypes, which can contain several snippettype nodes, can have three kinds of values, Expansion , SurroundsWith, refactoring. Expansion allows the code to be inserted at the cursor; SurroundsWith allows the code to surround the selected code (like #region), refactoring specifies the snippet used in the C # refactoring process and is not available in custom snippet. If the value is not set, the snippet can be placed anywhere.

For more information about <Header>, see here.

For the <Snippet> node, it is where the code template is implemented. It consists of four child nodes.

1. <Code> node

    • Delimiter: delimiter, the default value is $, and you will see its usage later.
    • Types of Kind:snippet, such as method bodies, method declarations, type declarations, and so on.
    • Language: The language types that are applicable, such as C #, vb.net, and XML.

In our example above, we already have the Code node, and note that it is included in the <! [cdata[]]>, because the code is likely to contain some special characters.

In the above TC Snippet, after pressing Tab, VS will check testcase, so it is more convenient to modify, for the above DW Snippet, we naturally want vs selected "Text" section, which requires the following <Declarations> node.

2. <Declarations> node

The node consists of several <Literal> and <Object> nodes. They can be seen as placeholders. <Literal> used to specify some literal values,<object> is used to declare objects in the template.
For more information, see <Literal> and <Object>.

You need to think of "Text" as a placeholder, so add a <Literal> node:

XML Code
<Snippet>
<code language= "CSharp" >
<! [cdata[
Debug.WriteLine (Text );end
]]>
</Code>
<Declarations>
<Literal>
<ID>text</ID>
<tooltip>text to Write</tooltip>
<Default> "Text" </Default>
</Literal>
</Declarations>
</Snippet>


A placeholder has been added here< Span id= "mathjax-span-13" class= "Mrow" >t ex t , default value "Text", end of line e nd is a special placeholder that represents the position of the cursor when you press ENTER . The

3. <imports> node  

is used to specify the namespace references that should be added to the file when using snippet, although only vb.net is supported. The

4. <references> node  

is used to specify which assembly references should be added when using snippet, and only vb.net is supported: (

OK, Now we can test our snippet, save the file as a. snippet file, and then import it.


Isn't it good?

Code Snippet function

As mentioned earlier,,<imports> and <References> nodes can only be used for vb.net, and the code snippet function here can only be used in C #.

In the <Literal> and <Object> nodes, they all contain child nodes <Function>, which are part of VS, and sometimes useful. A total of three functions:

1. Generateswitchcases (enumerationliteral), generate a switch statement and a series of case statements based on the enumerated type provided, in fact, there is an example in C #:

Enter Confirm:


2. ClassName () to return the name of the class where snippet is located.

3. Simpletypename (TypeName), infers the simplest form of the TypeName parameter in the context in which the snippet is located.
Let's take simpletypename as an example to see how these functions are used:

XML Code
<Snippet>
<code language= "CSharp" >
<! [cdata[
NameOfDebug . WriteLine (Text );end
]]>
</Code>
<Declarations>
<Literal>
<ID>text</ID>
<tooltip>text to Write</tooltip>
<Default> "Text" </Default>
</Literal>
<literal editable= "false" >
<ID>NameOfDebug</ID>
<function>simpletypename (Global::system.diagnostics.debug) </Function>
</Literal>
</Declarations>
</Snippet>


This adds a literal to the previous snippet, why does it need to be done? We know that the System.Diagnostics namespace is not referenced by default, and if you use the Debug class, you also need to reference system.diagnostics. The beauty here is that vs will infer the simplest form of nameofdebug, and if there is no reference to system.diagnostics, it will precede the debug, otherwise it will not be added.

A few suggestions

First of all, the definition of snippet is in XML, so it is also a code, so in the name and other code, you have to choose a more meaningful or relevant names. One way to name shortcut keys is to use initials, such as assert.areequal (expected, actual); The shortcut key is AE.

Also, remember to fill in the contents of the ToolTip node, which you will see when using snippet.

Other Tools


Although snippet can simplify the code input, it is not very convenient to write, but it is better to use some visual tools, such as snippet Editor, interested to try.

In addition, there are many people in the world who are writing snippet, such as gotcodesnippets.com, so you can search for it before you start writing:)

Summary

This article describes the use and writing of code snippet, which can be seen as a template for snippets that are smaller in granularity than project/item templates, further increasing productivity.

Use the code snippet in VS to improve development efficiency

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.