Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Professional Visual Studio 2005 (2006) [eng]

.pdf
Скачиваний:
117
Добавлен:
16.08.2013
Размер:
21.9 Mб
Скачать

Chapter 18

Only Visual Basic has the option to filter the member list down to commonly accessed properties, methods, and events.

You can also use a similar list to help you complete variable and object names. Simply type the initial few characters of the variable or object you need and use the keyboard shortcut Ctrl+Space. An extended list of all variables, objects, methods, data types, and more is displayed, with the first entry matching the characters you typed highlighted (see Figure 18-4). You can then navigate to the item you need.

Figure 18-4

In this case, C# and other languages can automatically show the list without you typing the keyboard shortcut.

This list is also useful when you’ve encountered a compilation error. For instance, if you mistype an object name, Visual Studio will mark it with IntelliSense — the blue wavy line underneath the problematic name. Place the cursor anywhere in the bad name and press the keyboard shortcut Ctrl+Space to force Visual Studio 2005 to display the full member list from which you can choose the correct name.

Stub Completion

In addition to word and phrase completion, the IntelliSense engine has another feature known as stub completion. This feature can be seen in its basic form when you create a function by writing the declaration of the function and pressing Enter. Visual Studio will automatically reformat the line, including adding the appropriate ByVal keyword for parameters that don’t explicitly define their context, and also adding an End Function line to enclose the function code.

Visual Studio 2005 takes this an extra step further by enabling you to do the same for interface and method overloading. When you add certain code constructs such as an interface in a C# class definition, Visual Studio will give you the opportunity to automatically generate the code necessary to implement the interface. To show you how this works, the following steps outline a task using the IntelliSense engine to generate an interface implementation in a simple class:

1.Start Visual Studio 2005 and create a C# WindowsApplication project. When the IDE has finished generating the initial code, open Form1.cs in Code view and navigate to the bottom of the namespace code structure.

2.At the top of the file, add a using statement to provide a shortcut to the System.Collections namespace:

236

IntelliSense

using System.Collections;

3.Add the following line of code to start a new class definition:

public class MyCollection : IEnumerable

As you type the IEnumerable interface, Visual Studio will first add a red wavy line at the end to indicate that the class definition is missing its curly braces, and then add a smart tag indicator at the beginning of the interface name (see Figure 18-5).

Figure 18-5

4.Hover your mouse pointer over the smart tag indicator. When the drop-down icon appears, click it to open the menu of possible actions. You should also see the tooltip explaining what the interface does, as shown in Figure 18-6.

Figure 18-6

5.Click the command “Explicitly implement interface ‘IEnumerable’” and Visual Studio 2005 will automatically generate the rest of the code necessary to implement the minimum interface definition. Because it detects that the class definition itself isn’t complete, it will also add the braces to correct that issue at the same time. Figure 18-7 shows what the final interface will look like.

Figure 18-7

Event handlers can also be automatically generated by Visual Studio 2005. The IDE does this in a similar manner to interface implementation. When you write the first portion of the statement (for instance, myBase.OnClick +=), Visual Studio gives you a suggested completion that you can select by simply pressing Tab.

237

Chapter 18

Parameter Information

In old versions of Microsoft development tools, such as Visual Basic 6, as you created the call to a function, IntelliSense would display the parameter information as you typed. Thankfully, this incredibly useful feature is still present in Visual Studio 2005.

The problem with the old way parameter information was displayed was that it would only be shown if you were actually modifying the function call. Therefore, you could see this helpful tooltip as you created the function call or when you changed it, but not if you were just viewing the code. The result was that programmers sometimes inadvertently introduced bugs into their code because they intentionally modified function calls so they could view the parameter information associated with the call.

Visual Studio 2005 eliminates that risk by providing an easily accessible command to display the information without modifying the code. Pressing the keyboard shortcut Ctrl+Shift+Space (or Ctrl+Shift+I) will display the information about the function call, as displayed in Figure 18-8. You can also access this information through the Edit IntelliSense Parameter Info menu command.

Figure 18-8

Quick Info

In a similar vein, sometimes you want to see the information about an object or interface without modifying the code. The Ctrl+I keyboard shortcut will display a brief tooltip explaining what the object is and how it was declared (see Figure 18-9).

You can also display this tooltip through the Edit IntelliSense Quick Info menu command.

Figure 18-9

IntelliSense Options

Visual Studio 2005 sets up a number of default options for your experience with IntelliSense, but you can change many of these in the Options dialog if they don’t suit your own way of doing things. Some of these items are specific to individual languages — for example, Visual Basic programmers tend to utilize IntelliSense features more than C# and C++ developers.

General Options

The first options to look at are found in the Environment section, under the Keyboard group. Every command available in Visual Studio has a specific entry in the keyboard mapping list (see Figure 18-10).

238

IntelliSense

Figure 18-10

You can overwrite the predefined keyboard shortcuts, or add an additional keyboard shortcut. The commands for the IntelliSense commands are as follows:

Command Name

Default Shortcut

Command Description

 

 

 

Edit.QuickInfo

Ctrl+I

Displays the Quick Info information about

 

 

the currently selected item

Edit.CompleteWord

Ctrl+Space

Attempts to complete a word if there is a

 

 

single match, or displays a list to choose

 

 

from if multiple terms match

Edit.ParameterInfo

Ctrl+Shift+Space

Displays the information about the

 

or Ctrl+Shift+I

parameter list in a function call

Edit.InsertSnippet

Ctrl+K, Ctrl+X

Invokes the Code Snippet dialog from

 

 

which you can select a code snippet to

 

 

insert code automatically

Edit.GenerateMethodStub

Ctrl+K, Ctrl+M

Generates the full method stub from a

 

 

template

Edit.GenerateImplement

None

Generates the abstract class definitions

AbstractClassStubs

from a stub

 

Edit.GenerateImplement

None

Generates the explicit implementation of

InterfaceStubsExplicitly

 

an interface for a class definition

Edit.GenerateImplement

None

Generates the implicit implementation of

InterfaceStubsImplicitly

 

an interface for a class definition

 

 

 

239

Chapter 18

Note that some of these shortcuts are the same kind of chords shown in Chapter 5. Use the techniques discussed in Chapter 5 to add additional keyboard shortcuts to any of these commands.

Statement Completion

You can control how IntelliSense works on a global language scale (see Figure 18-11) or per individual language. In the General tab of the language group, you want to change the Statement completion options to control how member lists should be displayed, if at all.

Figure 18-11

C#- and J#-Specific Options

Besides the general IDE and language options for IntelliSense, both C# and J# provide an additional IntelliSense tab in their own set of options. Displayed in Figure 18-12, the IntelliSense for these languages can be further customized to fine-tune how the IntelliSense features should be invoked and utilized.

First, you can turn off completion lists so they do not appear automatically, as discussed earlier in this chapter. Some developers prefer this so that the member lists don’t get in the way of their code listings. If the completion list is not to be automatically displayed but instead only shown when you manually invoke it, you can choose what is to be included in the lists in addition to the normal entries, including keywords and code snippet shortcuts.

To select an entry in a member list, you can use any of the characters shown in the Selection In Completion List section, or optionally after the space bar is pressed. Finally, as mentioned previously, Visual Studio will automatically highlight the last used member in a list, which you can turn off for these languages or just clear the history.

240

IntelliSense

Figure 18-12

Extended IntelliSense

In addition to these aspects of IntelliSense, Visual Studio 2005 also implements extended IDE functionality that falls into the IntelliSense feature set. These features are discussed in detail in other chapters in this book, as referenced in the following discussion, but this chapter provides a quick summary of what’s included in IntelliSense.

Code Snippets

Code snippets are sections of code that can be automatically generated and pasted into your own code, including associated references and Imports statements, and with variable phrases marked for easy replacement. To invoke the Code Snippets dialog, press the keyboard shortcut chord, Ctrl+K, Ctrl+X. Navigate the hierarchy of snippet folders until you find the one you need (as shown in Figure 18-13). If you know the shortcut for the snippet, you can simply type it and press Tab, and Visual Studio will invoke the snippet without the displaying the dialog. In Chapter 19, you’ll see just how powerful code snippets are.

Figure 18-13

241

Chapter 18

XML Comments

XML comments were discussed in Chapter 12 as a way of providing automated documentation for your projects and solutions. However, another advantage to using XML commenting in your program code is that Visual Studio can use it in its IntelliSense engine to display tooltips and parameter information beyond the simple variable-is-type information you see in normal user-defined classes.

Adding Your Own IntelliSense

You can also add your own IntelliSense schemas, normally useful for XML and HTML editing by creating a correctly formatted XML file and installing it into the Common7\Packages\schemas\xml subfolder inside your Visual Studio installation directory (the default location is C:\Program Files\Microsoft Visual Studio 8). The creation of such a schema file is beyond the scope of this book, but you can find schema files on the Internet by searching for IntelliSense Schema.

Summar y

IntelliSense functionality extends beyond the main code window. Various other windows, such as the Command and Immediate tool windows, can harness the power of IntelliSense through statement and parameter completion. Any keywords, or even variables and objects, known in the current context during a debugging session can be accessed through the IntelliSense member lists.

In addition, Visual Studio 2005 loans the IntelliSense member lists to temporary objects. For example, consider inline string variables. When you use string literals in your code, you can access their properties and methods just as if they were string variables. Figure 18-14 illustrates this feature in action, displaying the member list for a string literal, complete with tooltip and parameter information about the currently highlighted member.

Figure 18-14

IntelliSense in all its forms enhances the Visual Studio experience beyond most other tools available to you. Constantly monitoring your keystrokes to give you visual feedback or automatic code completion and generation, IntelliSense enables to be extremely effective at writing code quickly and correctly the first time. In the next chapter, you’ll dive into the details behind code snippets, a powerful addition to the IntelliSense lineup for Visual Studio 2005.

242

Code Snippets

Code snippets are small chunks of code that can be inserted into an application’s code base and then customized to meet the application’s specific requirements. They are usually generic in nature and serve one specific purpose. Code snippets do not generate full-blown applications or whole form definitions — project and item templates are used for such purposes. Instead, code snippets shortcut the programming task by automating frequently used code structures or obscure program code blocks that are not easy to remember.

In this chapter you’ll see how code snippets have matured in Visual Studio 2005 to be powerful tools that can improve coding efficiency enormously, particularly for programmers who perform repetitive tasks with similar behaviors.

Code Snippets Revealed

Code snippet functionality has been around in many forms for a long time, but Microsoft has not included it in their development environments natively until the release of Visual Studio 2005, preferring to let third parties create various add-ins for languages such as Visual Basic 6 and the early versions of Visual Studio .NET.

Visual Studio 2005 marks the introduction of a proper code snippet feature built directly into the IDE. It allows code snippets that include not only blocks of code, but also multiple sections of code to be inserted in different locations within the module. In addition, a type of variable can be defined that makes it clear to see what parts of the snippet are to be customized and what sections can be left as is.

Original Code Snippets

The original code snippets from previous versions of Visual Studio were simple at best. These snippets were used to store a block of plain text that could be then inserted into a code module when desired. The process to create and use them was simple as well: Select a section of code and

Chapter 19

drag it over to the Toolbox. This creates an entry for it in the Toolbox with a default name equal to the first line of the code. You can rename it like any other element in the Toolbox, and to use it, simply drag the code to the desired location in the Code view and release the left mouse button (see Figure 19-1).

Figure 19-1

Many speakers used this simple technology to more easily display large code blocks in presentations, but in a real-world situation it was not as effective as it could have been, because often you had to remember to use multiple items to generate code that would compile.

It was also hard to share these so-called snippets, and equally hard to modify them. Nevertheless, this method of keeping small sections of code is still available to programmers in Visual Studio 2005, and it can prove useful when you don’t need a permanent record of the code, but rather want to copy a series of code blocks for use immediately or in the near future.

“Real” Code Snippets

Now, in Visual Studio 2005, code snippet technology refers to something completely different. Code snippets are XML-based files containing sections of code that can include not only normal source code, but references and Imports statements and replaceable parameters as well.

244

Code Snippets

Visual Studio 2005 ships with many predefined code snippets in the three main languages — Visual Basic, C#, and J#. These snippets are arranged hierarchically in a logical fashion so that you can easily locate the appropriate snippet. Rather than locate the snippet in the Toolbox, you can use menu commands or keyboard shortcuts to bring up the main list of groups.

New code snippets can be created to automate almost any coding task and then stored in this code snippet library. Because each snippet is stored in a special XML file, you can even share them with other developers.

Using Snippets in Visual Basic

Code snippets are a natural addition to the Visual Basic developer’s toolset. They provide a shortcut way to insert code that either is difficult to remember or is used often with minor tweaks. One common problem some programmers have is remembering the correct references and Imports statements required to get a specific section of code working properly; code snippets in Visual Basic solve this problem by including all the necessary associations as well as the actual code.

To use a code snippet you should first locate where you want the generated code to be placed in the program listing and position the cursor at that point. You don’t have to worry about the associated references and Imports statements, as they will be placed in the correct location.

There are three scopes under which a snippet can be inserted:

Class Declaration: The snippet will actually include a class declaration, so it should not be inserted into an existing class definition.

Member Declaration: This snippet scope will include code that defines members, such as functions and event handler routines. This means it should be inserted outside an existing member.

Member Body: This scope is for snippets that are inserted into an already defined member, such as an event handler routine.

Once you’ve determined where the snippet is to be placed, the easiest way to bring up the Insert Snippet dialog is to use the keyboard shortcut chord of Ctrl+K, Ctrl+X (remember that a chord is a way of stringing multiple keyboard shortcuts together). There are two alternative methods to start the Insert Snippet process. The first is to right-click at the intended insertion point in the code window and select Insert Snippet from the context menu that is displayed. The other option is to use the Edit IntelliSense Insert Snippet menu command.

The Insert Snippet dialog is a special kind of IntelliSense (hence its location in the menu structure) that appears inline in the code window. Initially it displays the words Insert Snippet along with a drop-down list of code snippet groups from which to choose. Once you select the group that contains the snippet you require, it will show you the list of snippets from which you simply double-click the one you need.

Because you can organize the snippet library into many levels, you may find that the snippet you need is multiple levels deep in the Insert Snippet dialog. Figure 19-2 displays an Insert Snippet dialog in which the user has navigated through two levels of groups and then located a snippet named Draw a Pie Chart.

245