Visual Basic 2005 Design and Development - Chapter 8 ppsx

34 212 0
Visual Basic 2005 Design and Development - Chapter 8 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Part II Meta-Development In this Part: Chapter 8 Snippets, Macros, and Add-ins Chapter 9 Scripting Chapter 10 Custom Controls and Components Chapter 11 Property Support Chapter 12 Attributes and XML Comments 12_053416 pt02.qxd 1/2/07 6:31 PM Page 203 12_053416 pt02.qxd 1/2/07 6:31 PM Page 204 Snippets, Macros, and Add-ins Visual Studio provides many tools that make writing code easier. This chapter describes three tools that you can use to automatically generate code: snippets, macros, and add-ins. Snippets let you copy a piece of code into an application. After you insert the code, snippet-editing tools let you make simple systematic replacements to customize the new code. Macros let you record actions you perform in a code editor and replay them later. By itself, that would only be useful if you needed to repeat the exact same series of operations. By editing the recorded macro, however, you can generate new code in very complicated ways. Like macros, add-ins let you generate complicated pieces of code. Add-ins have the additional advantage that they are compiled, so you can write an add-in for developers while not allowing them to view or modify it. Because an add-in is a Visual Studio project in its own right, it can take advantage of the full power of the development environment. Snippets An IntelliSense code snippet (or just snippet) is a piece of code stored in a special XML format, so it is easy to insert into your applications. Visual Studio comes with several hundreds of pre-built snip- pets that you can use to generate code for such tasks as activating a running application, clearing the console window, creating a sorted dictionary, or calculating the sine of an angle: Many of the pre-built snippets are quite simple. For example, the following code shows the snip- pet that calculates the sine of an angle: Dim radians As Double = 120 * Math.PI / 180 Dim sin As Double = Math.Sin(radians) 13_053416 ch08.qxd 1/2/07 6:31 PM Page 205 When you insert this snippet, the code’s “120” is highlighted by a green box and the cursor is positioned there. This is a replacement area. You should replace the default angle 120 with the angle you’re inter- ested in. If you hover the mouse over the replacement area, a tooltip gives you a hint about what you are supposed to do by saying, “Replace with the measurement in degrees.” Snippets can help you remember how to write the code for common programming tasks. They can auto- mate tedious, repetitive chores, and can help you remember the little details that are so easy to forget. For example, they can automatically add the appropriate Imports statements when you use routines that require them. They build the pieces of property procedures, including the procedures themselves, the private variables that store procedure values, attributes to give descriptions of the procedures and categories in the Properties window, and even comments. Snippets can even help you standardize your code. For example, suppose you have a standard comment block that you want every developer on the project to use at the beginning of every file. This block might include a copyright statement, the name of the module, the name of the developer who created the file, and places for revision history. You can help developers follow the standard by creating a snippet that contains the comment template. If developers insert the snippet into their modules, all of the files will have module-level comments in exactly the same format. The snippet’s replacement areas even help the developers insert the module’s name and the name of the developer who created the file. The following section describes in greater detail how to insert snippets. The sections after that one explain how to write your own snippets. Using Snippets To insert a snippet into your code, right-click where you want to insert and select the Insert Snippet com- mand. Visual Studio displays a cascading pop-up list, similar to the one shown in Figure 8-1. Figure 8-1: The Insert Snippet command lets you insert snippets from snippet folders. 206 Part II: Meta-Development 13_053416 ch08.qxd 1/2/07 6:31 PM Page 206 Scroll down to the folder that contains the snippet you want and double-click it. In some cases, the initial snippet folder will contain subfolders. Continue delving into the snippet folders until you find a list of actual snippets similar to the one shown in Figure 8-2. Then double-click the snippet you want to insert. Figure 8-2: Double-click the snippet that you want to insert. Figure 8-3 shows the code inserted by the Public Property snippet. Colored boxes indicate values that you should replace. In this example, the replacement values include the strings FirstName, String, and Misc. They also include blank values inside the quotes in the code’s Description and DefaultValue attributes. Figure 8-3: Make replacements in the snippet as necessary. 207 Chapter 8: Snippets, Macros, and Add-ins 13_053416 ch08.qxd 1/2/07 6:31 PM Page 207 If you hover the mouse over a replacement area, a tooltip tells you what value you should put there. Initially, the first replacement area for FirstName is highlighted. Enter the name you want to give this property. When you press the Tab key, the value you entered is copied to all of the FirstName replace- ment fields and the next replacement area is highlighted. Continue making replacements until you have replaced all of the values. If there is a shortcut assigned to a snippet, then you can use it to insert the snippet more quickly. Type the first several letters in the shortcut, followed by a question mark (?), and press Tab. Visual Studio dis- plays a pop-up list of snippets with the one matching the string you entered selected. Figure 8-4 shows the list displayed when I typed “propertysn?” Figure 8-4: Using snippet shortcuts you can insert snippets very quickly. If you use a snippet frequently, it will be faster to insert it using its shortcut than by navigating through the snippet folders. Making Snippets Snippets are stored in XML files with specific tags that identify the snippet’s name, code, replacement values, and so forth. To create a snippet, make a Visual Studio project. Open the Project menu and select Add New Item. Pick the XML File template, give the file a descriptive name with a .snippet extension, and click OK. For example, you might name a property snippet’s file Property.snippet. Actually, snippets are just text files in XML format, so you could write them using any text editor. However, when the Visual Studio IDE opens a snippet, it uses a special XML editor that makes editing the files easier. For example, it knows which tags should be allowed at different points. If you type “<” 208 Part II: Meta-Development 13_053416 ch08.qxd 1/2/07 6:31 PM Page 208 inside a Literal element, the editor displays a pop-up that lists the allowed sub-items: ! (for com- ments), ? (for XML processor instructions), Default, Function, ID, ToolTip, and Type. The edi- tor also flags XML errors such as unclosed tags, mismatched open and close tags, and so forth. Double-click the file to open it. Initially, the file only contains an XML declaration. After the declaration, you must add a series of XML tags to define the snippet. Rather than wading through all of the ugly details, take a look at the following example. The text that follows describes the key sections that you need to modify: <CodeSnippets> <CodeSnippet> <Header> <Title>Public Property</Title> <Shortcut>PropertySnippet</Shortcut> </Header> <Snippet> <Imports> <Import> <Namespace>System.ComponentModel</Namespace> </Import> <Import> <Namespace>System.Windows.Forms</Namespace> </Import> </Imports> <References> <Reference> <Assembly>System.Windows.Forms.dll</Assembly> </Reference> </References> <Declarations> <Literal> <ID>name</ID> <ToolTip>The property’s name.</ToolTip> <Default>FirstName</Default> </Literal> <Literal> <ID>data_type</ID> <ToolTip>The property’s data type.</ToolTip> <Default>String</Default> </Literal> </Declarations> <Code Language=”VB”> <![CDATA[ ‘’’ <summary> ‘’’ The $name$ property. ‘’’ </summary> ‘’’ <remarks>This property is implemented with property procedures.</remarks> Private m_$name$ As $data_type$ = “$default$” <Browsable(True)> _ Public Property $name$() As $data_type$ Get MessageBox.Show(“In $name$.Get”) Return m_$name$ End Get Set(ByVal value As $data_type$) 209 Chapter 8: Snippets, Macros, and Add-ins 13_053416 ch08.qxd 1/2/07 6:31 PM Page 209 MessageBox.Show(“In $name$.Set”) m_$name$ = value End Set End Property ]]> </Code> </Snippet> </CodeSnippet> </CodeSnippets> Within the Header section, the Title value gives the title displayed in the cascading snippet menus shown in Figure 8-2. The Shortcut value gives the snippet’s shortcut. If you type the first several letters from the shortcut followed by a question mark and a tab, Visual Studio displays a list of snippets with this one selected. The Snippet section contains several key subsections. The Imports section contains information about imports that the code in the snippet requires. This example contains one import: System.ComponentModel. When you use this snippet, if the module does not already have an Imports statement for this namespace, the snippet adds it at the top of the module. In this example, the statements would be as follows: Imports System.ComponentModel Imports System.Windows.Forms This example needs the System.ComponentModel namespace because it uses the Browsable attribute. It needs the Systems.Windows.Forms namespace to use the MessageBox class. The References section contains references that the snippet’s code needs. If the project doesn’t already have a reference to the indicated assembly, the snippet adds it. This example requires a reference to System.Windows.Forms.dll because that library contains the MessageBox class. The Declarations section defines replacement variables. Each Literal tag defines a word in the snip- pet code that the developer can replace. This example’s first Literal defines a token called “name.” The snippet code indicates a replacement value by enclosing the token’s ID in dollar signs, as in $name$. Tags within the Literal give the tooltip to display and the item’s default value. You should give a Literal a default value whenever possible, because it makes the value easier for the developer to see. The Declarations section can also contain Object tags to define replacements representing objects that are usually defined outside of the snippet’s code. Finally, the Code tag contains the snippet’s actual code. In this example, the tag’s Language attribute indicates that this is a Visual Basic snippet. The <![CDATA[ string allows an XML file to contain just about any text, including white spaces and carriage returns, until reaching the corresponding ]]>. Microsoft has produced a free snippet editor that lets you avoid the details of writing an XML file. Download it at http://msdn.microsoft.com/vbasic/downloads/tools/snippeteditor. 210 Part II: Meta-Development 13_053416 ch08.qxd 1/2/07 6:31 PM Page 210 Installing Snippets After you create a snippet file, put it in a directory where you want to store snippets. The cascading snippet menus shown in Figures 8-1 and 8-2 display the directory’s name, so give the directory a mean- ingful name. Next, open Visual Studio’s Tools menu and select the Code Snippets Manager command to display the tool shown in Figure 8-5. Click the Add button, browse to your snippets directory, and click Open. Back in the Code Snippets Manager, click OK. Figure 8-5: Use the Code Snippets Manager to add and remove snippet directories. Now, Visual Studio is ready to use the snippets in that directory. When you right-click in a code editor and select the Insert Snippet command, you should see the directory and any snippets defined in .snippet files within the directory. Sharing Snippets Because snippets are plain old text files, they are easy to share. You can email them to other developers, or post them on your Web site. You can put them in a shared snippet directory to ensure that every developer on your project uses the same snippets so that they get the benefit of consistency. You can also search the Web for snippets. You can download code snippets for Visual Studio at http://msdn.microsoft.com/vstudio/downloads/codesnippets. As of this writing, these are the snippets that come with Visual Studio 2005, so they should already be installed on your system. This is probably a good place to check for updates, however. 211 Chapter 8: Snippets, Macros, and Add-ins 13_053416 ch08.qxd 1/2/07 6:31 PM Page 211 You can search this book’s snippet library at www.vb-helper.com/snippets.html. If you come up with a good snippet that you’d like to share, send it to me at RodStephens@vb-helper.com and I’ll add it to the library. Macros Snippets are a fantastic way to automate building certain chunks of code in a fixed format, while allow- ing you to make simple replacements. By using snippets, you can simplify moderately complicated tasks and add some useful consistency to a development project. Although snippets are easy, they are fairly limited. They use a “design by example” approach, where you write code and then turn it into a snippet. This approach is extremely simple, but it’s not very flexi- ble. For example, the previous example that creates property procedures won’t work if you want to add a parameter to the property, as shown in the following code: ‘ Get or set a test score. Private m_Scores(0 To 9) As Double Public Property Score(ByVal test_number As Integer) As Double Get Return m_Scores(test_number) End Get Set(ByVal value As Double) m_Scores(test_number) = value End Set End Property Snippets also only create code; they don’t modify it or the Visual Studio IDE. Macros give you much greater flexibility. They let you write new code, modify existing code, and control the development environment. Visual Studio lets you record, write, edit, debug, and play back macros later, much as the Microsoft Office applications do (although the Microsoft Office applications use VBA as their macro language, whereas Visual Basic 2005 uses Visual Basic 2005 for macros). You can use macros to automate tasks that you need to perform frequently, such as the following: ❑ Writing a series of Visual Basic statements that are mostly the same ❑ Performing an action on similar code entities (for example, commenting functions or printing code documents) ❑ Altering the project’s structure (for example, adding files to it) ❑ Modifying the Visual Studio environment The following sections briefly describe how to record, edit, and use macros in Visual Studio. 212 Part II: Meta-Development 13_053416 ch08.qxd 1/2/07 6:31 PM Page 212 [...]... 8- 1 3 Enter a meaningful name for the template project and click OK Figure 8- 1 3: To make an add-in, select the Visual Studio Add-in template 222 13_053416 ch 08. qxd 1/2/07 6:31 PM Page 223 Chapter 8: Snippets, Macros, and Add-ins When you start a new add-in project, Visual Studio displays the Add-in Wizard shown in Figure 8- 1 4 The wizard gathers basic information about the add-in you want to build, and. .. connecting the add-in to the Visual Studio environment and interacting with the IDE When you click Next, the wizard displays the page shown in Figure 8- 1 5 to let you specify the language you want to use to write the add-in Select the Visual Basic option and click Next Figure 8- 1 4: The Add-in Wizard helps Figure 8- 1 5: Select Visual Basic to write the add-in using Visual Basic 223 13_053416 ch 08. qxd 1/2/07... description for your add-in These are displayed by the Add-in Manager described shortly Figure 8- 1 6: Check the IDEs that should run the add-in Figure 8- 1 7: Enter the name and description that the Add-in Manager should use for your add-in 224 13_053416 ch 08. qxd 1/2/07 6:31 PM Page 225 Chapter 8: Snippets, Macros, and Add-ins When you click Next, the wizard displays the page shown in Figure 8- 1 8 Check the first... 2 18 13_053416 ch 08. qxd 1/2/07 6:31 PM Page 219 Chapter 8: Snippets, Macros, and Add-ins Figure 8- 9 : You can use the Toolbars tab’s New button to make a new toolbar to provide easy access to macros On the Commands tab shown in Figure 8- 1 0, scroll the list on the left down and select the Macros entry Then, click and drag macros from the list on the right onto menus and toolbars Figure 8- 1 0: The Commands... use, right-click it in Macro Explorer, select Rename, and give the macro a new name Now, if you record a new macro, it is named TemporaryMacro and your old macro is saved 213 13_053416 ch 08. qxd 1/2/07 6:31 PM Page 214 Part II: Meta -Development Editing Macros To edit a macro, right-click it in Macro Explorer, and select Edit to make Visual Studio open the Macro IDE shown in Figure 8- 8 Figure 8- 8 : Visual. .. much as it lets you edit Visual Basic projects You can modify the macro’s code in the code editor shown in Figure 8- 8 much as you can modify Visual Basic code in the Visual Studio IDE You can even set breakpoints in the editor, and step through the code to debug it To organize your macros, you can use the Project Explorer shown on the left in Figure 8- 8 Right-click and add folders and modules to the projects... II: Meta -Development The wizard’s next page, shown in Figure 8- 1 6, lets you pick the applications that will run the add-in Your choices include the Visual Studio IDE and the Macro IDE Unless you really get into writing macros, you will normally build add-ins for the Visual Studio IDE Check the IDEs that should run the add-in and click Next to display the page shown in Figure 8- 1 7 Enter a name and description...13_053416 ch 08. qxd 1/2/07 6:31 PM Page 213 Chapter 8: Snippets, Macros, and Add-ins Recording Macros To record a macro, open the Tools menu, go to the Macros submenu, and select the Record TemporaryMacro command Visual Studio displays the Macro Recorder shown in Figure 8- 6 , and starts recording a macro Figure 8- 6 : The Macro Recorder lets you pause, stop, or cancel... use, and click Finish to create the add-in project 226 13_053416 ch 08. qxd 1/2/07 6:31 PM Page 227 Chapter 8: Snippets, Macros, and Add-ins Adding Add-in Code The Add-in Wizard generates a bunch of code that performs tasks such as connecting the add-in to the Tools menu, responding to events, and accessing the IDE object hierarchy Most of this work is done in the module Connect.vb To modify the add-in,... in Figure 8- 2 0 If you scroll down and select your add-in, you should see the About information in the “Product details” section 225 13_053416 ch 08. qxd 1/2/07 6:31 PM Page 226 Part II: Meta -Development Figure 8- 1 9: Enter About information Figure 8- 2 0: Visual Studio displays add-in information in its About dialog When you click the Next button, the Add-in Wizard displays a final page summarizing your selections . II Meta -Development In this Part: Chapter 8 Snippets, Macros, and Add-ins Chapter 9 Scripting Chapter 10 Custom Controls and Components Chapter 11 Property Support Chapter 12 Attributes and XML. right-click it in Macro Explorer, and select Edit to make Visual Studio open the Macro IDE shown in Figure 8- 8 . Figure 8- 8 : Visual Studio lets you edit macros much as it lets you edit Visual Basic. code, right-click where you want to insert and select the Insert Snippet com- mand. Visual Studio displays a cascading pop-up list, similar to the one shown in Figure 8- 1 . Figure 8- 1 : The Insert

Ngày đăng: 14/08/2014, 11:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan