Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual...

21
Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to think in terms of version numbers) to write Visual Basic and C# applications. Even more interesting, you can load tons of other file types and use the IDE as a resource editor, an image editor, an HTML browser, and so on. Old and Renewed Tools The Visual Studio .NET environment doesn’t look like the Visual Basic 6 IDE, so odds are that you’ll feel rather disoriented when you look at the new environment for the first time. Let’s have a quick exploration of the tools you’ll be using more often. The Start Page By default, at startup Visual Studio .NET shows its Start Page, an HTML page that lets you load one of your most recently used projects. (See Figure 1.) You can access areas of the Microsoft site and learn about updated tools, newsgroups, code downloads, and more by clicking on items in the leftmost column. Figure 1 Visual Studio .NET Start Page. The last item in this column, My Profile, lets you select a few important Visual Studio settings, as you can see in Figure 2. By using options on this page, you can have Visual Studio mimic behavior such as windows layout and keyboard settings of other environments, including Visual Basic 6 or Microsoft InterDev. I suggest that you attempt to become familiar with Visual Studio .NET “native” settings. It will surely take a while to abandon old habits, but this effort pays off in the long run, especially considering that you’ll probably live with this new environment for years.

Transcript of Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual...

Page 1: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to think in terms of version numbers) to write Visual Basic and C# applications. Even more interesting, you can load tons of other file types and use the IDE as a resource editor, an image editor, an HTML browser, and so on.

Old and Renewed Tools The Visual Studio .NET environment doesn’t look like the Visual Basic 6 IDE, so odds are that you’ll feel rather disoriented when you look at the new environment for the first time. Let’s have a quick exploration of the tools you’ll be using more often.

The Start Page By default, at startup Visual Studio .NET shows its Start Page, an HTML page that lets you load one of your most recently used projects. (See Figure 1.) You can access areas of the Microsoft site and learn about updated tools, newsgroups, code downloads, and more by clicking on items in the leftmost column.

Figure 1 Visual Studio .NET Start Page.

The last item in this column, My Profile, lets you select a few important Visual Studio settings, as you can see in Figure 2. By using options on this page, you can have Visual Studio mimic behavior such as windows layout and keyboard settings of other environments, including Visual Basic 6 or Microsoft InterDev. I suggest that you attempt to become familiar with Visual Studio .NET “native” settings. It will surely take a while to abandon old habits, but this effort pays off in the long run, especially considering that you’ll probably live with this new environment for years.

Page 2: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

On the other hand, you might want to preserve Visual Basic 6’s settings if you continue to develop code in that language and you don’t want to retrain your fingers as you switch among different environments.

Because most of the time you’ll work on a single project over a long period of time, I suggest that you change the default action at startup so that Visual Studio automatically loads the most recently used solution.

Figure 2 Setting a user profile from Visual Studio’s Start Page.

The Solution Explorer A Visual Studio solution is a group of projects that work together to create an application. They’re conceptually similar to Visual Basic 6’s project groups except that a Visual Studio solution can contain virtually any type of file, including HTML pages, XML documents and schemas, and XSLT files, bitmaps, cursors, icons, and resource and text files. Each solution corresponds to an .sln file on disk, which contains the names of the individual projects in the solution.

You create a new project by pointing to New on the File menu and clicking Project, and then selecting which type of project you want to create in the New Project dialog box. (See Figure 3.) Here’s a list of supported project types:

• Windows Application Win32 applications that use the Windows Forms namespace

• Class Library One or more .NET components that you use from inside another application

Page 3: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

• Windows Control Library One or more controls that can be used in a Windows Forms application

• ASP.NET Web Application A Web Form application

• ASP.NET Web Service An XML Web service application

• Web Control Library One or more controls that can be used in a Web Form application

• Console Application A command-line CUI (Character User Interface) Windows program

• Windows Service A Windows service application that can run before any user logs in to the computer

Figure 3 The Add New Project dialog box.

A key difference from Visual Basic 6 is that Visual Studio actually creates all the files in the project when you click the OK button and stores them in a directory named after the project, located under the directory you specify in the Location box. (For example, the options visible in Figure 3 would create a new project in the C:\NET_Projects\WindowsApplication3 directory.) Visual Basic projects are stored in .vbproj files, in XML syntax so that you can easily load and parse them should you need to do so.

You can add a new file to a project by clicking Add New Item on the File menu. (See Figure 4.) You can also add an existing file by clicking Add Existing Item on the File menu; if the file isn’t in the project’s main directory, it is copied there before being added to the project.

Page 4: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

Figure 4 The Add New Item dialog box.

The Solution Explorer is the main tool for working with solutions and individual projects. This tool is similar to the Project window in Visual Basic 6 except that it displays additional information, such as all the references to external components used by a given project. (See Figure 5.) By clicking on the third icon on the Solution Explorer’s toolbar, you can show or hide all the secondary files in each individual project, including executable or resource files. You can learn more about each file—and even rename it—by highlighting it in the Solution Explorer and then switching to the Properties window.

You can add a reference to a given project by right-clicking on the References folder. (This command corresponds to Add Reference on the Project menu.) The Add Reference dialog box (shown in Figure 6) lets you select among all installed .NET and COM components, as well as other projects under development in the IDE. Note that you select .NET components by the name of the DLL that contains them, which is information that you can derive from .NET SDK documentation. On the other hand, you select COM components by their ProgID, as you did under Visual Basic 6.

Page 5: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

Figure 5 The Solution Explorer window.

Figure 6 The Add Reference dialog box.

Page 6: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

The Object Browser and the Class View Window The Object Browser is your best friend when you start your explorations of .NET components. Given the hierarchical nature of the .NET Framework, the new Object Browser displays more information than its Visual Basic 6 version—for example, the base class from which a type derives and all the interfaces that a type implements. (See Figure 7.)

Figure 7 The Object Browser and the Class View window.

You can click the Find button on the Object Browser toolbar to search for all the objects that contain a character string; all the matching objects and methods appear in the Find Symbol Results window, near the bottom of the IDE main window. You can double-click on each item to display it in the class hierarchy.

By default, the Object Browser displays all the objects defined in the components referenced by any of the currently loaded projects; it also displays the types defined in the projects being edited. However, you can click the Customize button on the Object Browser toolbar to include additional .NET and COM components not referenced by any project. (You select these components using the Component Selector dialog box, which is similar to the one shown in Figure 6 except that it doesn’t have a Projects tab.)

The Class View window—also visible in Figure 7—is a sort of special object browser that displays only the types in the current solution by means of a hierarchical tree that goes down to individual fields and methods. You can use the Class View window to quickly jump to a field or routine definition and arrange members by their

Page 7: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

name, type, or access (Private, Public, Friend, and so on). You can even create a new folder and drag to it the types and methods you browse more frequently so that you can jump to them in a snap without having to look for them among a collection of hundreds of items.

C# developers can use commands in the Class View’s shortcut menu to quickly create new methods and properties, but this functionality hasn’t been implemented in this Visual Basic .NET release.

The Code Editor You’ll probably spend more time in the code editor than in any other Visual Studio window or tool, so you should learn as much as you can about its features and capabilities.

For starters, the code window has all the features of the Visual Basic 6 code editor, including color syntax highlighting, IntelliSense, and drag-and-drop editing. Unless you opted for the Visual Basic 6 profile on the Start Page, most keyboard shortcuts are different, however. Here’s a partial list of features you didn’t have under Visual Basic 6:

• Box mode selection You can select a rectangular portion of code by pressing the Alt key while you drag the mouse or press an arrow key.

• Smart indenting The editor automatically sets the most logical indents for code blocks such as For loops and Select Case statements.

• Automatic insertion of end constructs Visual Basic 6 adds an End Sub statement when you type a Sub statement and does the same also with Function and Property procedures. The new editor extends this functionality to If, Do, Select Case, Class, and Module blocks.

• Code navigation You can navigate through your code as if you were using a browser, by using the buttons on the standard toolbar, or by using the Ctrl+Minus and Ctrl+Shift+Minus keyboard commands.

• Word wrapping You can activate this feature when browsing a piece of code with very long lines. (Point to Advanced on the Edit menu and select Word Wrap or press Ctrl+R twice to toggle this feature on and off.)

• Line numbers This feature is very handy when you’re locating errors or discussing a code snippet with other developers. Clicking Go To on the Edit menu lets you jump to a line given its number. (This command works even if line numbers aren’t visible.)

• Improved Find and Replace You can now specify what you’re looking for by using wildcards or regular expressions; in addition, you can use the Mark All button to create bookmarks pointing to each found occurrence so that you can later visit all of them with the Next Bookmark command.

• Incremental search You don’t need to bring up the Find dialog box for simple searches: just press Ctrl+I and start typing what you’re looking for, and the caret will move to the first word that starts with the characters you’ve typed. When you

Page 8: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

type Ctrl+I again, the caret moves to the next occurrence. Use the Ctrl+Shift+I shortcut to move backward in your search.

• Outlining You can collapse a routine or an entire class by clicking on the minus symbol to the left of its first statement. (See the BubbleSort procedure in Figure 8.) You can control this feature with the commands in the Outlining submenu of the Edit menu.

• User-defined collapsible regions You can enclose a piece of code inside #Region and #End Region statements to make it collapsible. (Figure 8 shows one such region.)

• Clipboard Ring The editor remembers the 15 pieces of text copied in the Clipboard most recently, and you can paste any one of them in a cyclic fashion by clicking Cycle Clipboard Ring on the Edit menu (or the Ctrl+Shift+V keyboard shortcut). Or you can just drag items from the Clipboard Ring section in the Toolbox.

• Other editing commands You can convert a string to uppercase or lowercase, for example, and you can show or hide white spaces. (Reach these features from the Advanced submenu of the Edit menu.)

Figure 8 The code editor with line numbers enabled; note that line numbers account for collapsed regions of code.

Page 9: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

The preceding descriptions should suffice to let you experiment with these new features, but user-defined collapsible regions might require an additional explanation. To see how this feature works, place the caret anywhere in the code editor, type this statement, and press Enter:

#Region "My collapsible region"

The code editor creates the #End Region statement for you:

#Region "My collapsible region" #End Region

If you have already written the portion of code that you want to make collapsible, you just need the code in question inside the #Region block.

Another feature you might want to learn more about is regular expression searching, which you activate from inside the Find or Replace dialog box. For example, the :q regular expression searches all the quoted strings in code, :z searches for integer numbers, :n for floating point numbers, and :i for Visual Basic identifiers. You can combine these and other regular expressions for more complex searches—for example, :i = :q searches for string assignments and (Dim|Private|Public) :i As String searches for declaration of String variables.

You can get a partial list of supported regular expressions by clicking the button to the right of the Find What field. (See Figure 9.) One of the commands in this menu takes you to the help page that describes this feature in greater detail.

Page 10: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

Figure 9 The Find dialog box with its pop-up menu to help the developer with regular expression syntax.

The Form Designer and the Toolbox The form designer works more or less the same way it did under Visual Basic 6: you select a control from the one of the tabs in the Toolbox and drag it over the form’s surface. There are only minor differences worth mentioning:

• The designer’s tray area The Timer control and other controls invisible at run time are displayed in a special area below the form called the component tray.

• In-place menu editor Menus are just controls that can be edited in place, in a far more natural way than the clumsy menu editor that has accompanied Visual Basic for 10 years, virtually unchanged since version 1.

• Individual control locking Each control can be locked individually so that you don’t move it accidentally with the mouse. (You could either lock all controls or none of them in Visual Basic 6.)

• Visual TabIndex setting You can set the TabIndex property in a simple, visual fashion by clicking Tab Order on the Edit menu.

The Toolbox is similar to the one in Visual Basic 6 except that it supports both ListView display (as you can see in Figure 10) and the traditional Icon view (as in Visual Basic 6). The commands in the Toolbox’s context menu let you add or remove tabs, customize the Toolbox with additional .NET and COM components, and list items alphabetically. By default, the Toolbox runs in autohide mode, so it appears

Page 11: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

only when you move the mouse cursor near the left border of the IDE window. (I disabled this feature when I was capturing Figure 10 so that I could display the form’s designer in its entirety.)

Figure 10 The form designer, with the Toolbox on its left and the Properties window on its right; note that controls invisible at run time are displayed in the designer’s tray area.

The Components section of the toolbox contains a few .NET components that support visual editing of their properties, such as the FileSystemWatcher component. Because none of these components are visible at run time, they appear in the designer’s tray area, but you can edit their properties in the Properties window as if they were controls. The Clipboard Ring section of the toolbox contains snippets of text that you can copy into the Clipboard and that you can paste into the code editor using drag-and-drop.

New Tools Some of the new Visual Studio .NET features are used only for specific programming tasks, so I’ll cover them only when necessary. However, a few new tools can make your job much easier from day one, so this is the right place to introduce them.

Page 12: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

The Task List Window The Task List is used for annotating pieces of information of four different kinds, as you can see in Figure 11. In the first three cases, you can jump to the corresponding statement in code by double-clicking the Task List item:

• Compilation errors and warnings Compilation errors and warnings are marked with the same icon (a stack of paper sheets with a downward blue arrow), but compilation errors also have a red exclamation mark.

• User comments You can add a TODO user comment in the Task List by typing the following comment anywhere in the code window:

' TODO: text of the comment

You can also use other markers, such as HACK and UNDONE, and you can define your own markers or alter the priority of predefined markers in the Task List page of the Options dialog box.

• Named bookmarks You can add a named bookmark pointing to a statement in your code by right-clicking in the code editor and clicking Add Task List Shortcut on the shortcut menu.

• User-defined tasks You can add other items to the Task List window by clicking on the first entry in the Task List window and starting to type.

You must right-click the Task List, point to Show Tasks, and click All on the shortcut menu to see all types of Task List entries. Other commands on the shortcut menu let you filter the contents of this window by their type. In addition, named bookmarks and user-defined tasks have check boxes that you can select or deselect, and you can later use the commands in the Show Tasks submenu to filter items according to the state of their associated check boxes. You can click on a Task List column header to sort tasks by their description, filename, or line number.

Figure 11 The Task List window, with a compilation error, a compilation warning, a user comment, a named bookmark, and a user-defined task (in that order).

Page 13: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

The Server Explorer Window The Server Explorer window displays some of the resources located on the current or a remote computer, including Event Logs, Message Queues, Windows Services, and SQL Server databases. (See Figure 12.) Using this tool, you can perform the following operations:

• Right-click on the Data Connection node to create a new data connection; expand existing data connection nodes to view SQL Server databases, tables, and fields and browse their properties. (Note that properties are displayed in Visual Studio’s Properties window.) Data connections are very handy; with them, you can quickly create a database connection in code.

• Right-click on the Servers node to add a remote computer to the list of machines that can be administered from inside the Server Explorer.

• Expand the Event Logs categories (Application, System, and so on) to access event log entries grouped by the application or system services that created them; details of each event log entry are visible in Visual Studio’s Properties window. You can also right-click on the Event Logs node to launch the Event Viewer.

• Expand the Performance Counters node to browse the properties (but not the current value) of all the performance counters defined on the selected computer.

• View the properties of all the services installed on the selected computer; you can also start, stop, pause, and resume them.

• Administer one or more instances of SQL Servers. The Solution Explorer exposes most of the commands you can execute from inside the SQL Server Enterprise Manager, so you can create new databases, diagrams, tables, views, triggers, and indexes; retrieve data from tables and change their layout; edit, run, and debug stored procedures; and generate scripts for any database item.

Page 14: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

Figure 12 The Server Explorer window.

The Server Explorer is more than just an administration tool because it gives you a visual way to code against the components in its window. In fact, you can drag and drop the majority of the items from the Solution Explorer window onto a form designer’s tray area to create an instance of the corresponding .NET component. For example, drag the Services\IIS Admin Service node to the tray area and create a component named ServiceController1, which you can then reference from inside the form’s code module to start, stop, pause, and resume the Internet Information Services service, as here:

ServiceController1.Stop

The Command Window In the default Visual Studio window layout, the Command window is located near the bottom edge of the IDE window and shares the screen area with the Task List and Search Results window. (You can switch among these windows by using tabs.) The Command window can work in two distinct modes:

• In command mode, to execute Visual Studio commands such as loading a new file or searching a string in the code module. The Command window displays a > prompt when in command mode. You display the Command window in this mode

Page 15: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

by pointing to Other Windows on the View menu and clicking Command Window.

• In immediate mode, to evaluate expressions, invoke methods, and read or write variables and properties. The Command window doesn’t display a prompt when in this mode. You display the Command window in immediate mode by pointing to Windows on the Debug menu and clicking Immediate. (This mode can be activated only while you’re debugging a running application.)

Most of the commands available in command mode reflect the Visual Studio menu structure: you just have to discard the spaces from menu captions and use the dot to separate submenus. For example, the following command from the Command window is equivalent to clicking Add Existing Item on the File menu:

>File.AddExistingItem

Commands that display a dialog box can take arguments that correspond to the values you would enter in the dialog box’s fields. For example, the following command searches for the “End Sub” string in case-sensitive mode and follows the Up direction:

>Edit.Find "End Sub" /case /up

Most options can be shortened to one character and blended together; for example, the preceding command can be rewritten in a more concise form as follows:

>Edit.Find "End Sub" /cu

You don’t have to remember the spelling of every command because the Command window supports IntelliSense (see Figure 13); however, IntelliSense doesn’t support command arguments, and the only way to learn about them is by looking at Visual Studio documentation.

Figure 13 The Command window offers IntelliSense support when in command mode.

If you work often with a given command, you might want to create a shorter alias for it. You create a command alias using the alias command. For example, you can create the efuc alias for the Edit.Find /uc command as follows:

>alias efuc Edit.Find /uc

Page 16: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

After you’ve created the preceding alias, you can search a string in case- sensitive mode and follow in the Up direction with the following command:

>efuc "End Sub"

Visual Studio comes with several aliases already defined; you can list them by typing the alias command without an argument. Another way to invoke a command without typing its entire name is by assigning it a keyboard shortcut. (See the “Macro Explorer” section later in this file.)

You can switch the Command window to immediate mode by pointing to Windows on the Debug menu and clicking Immediate or by typing the immed command while in command mode:

>immed

When in immediate mode, the Command window behaves much like the Visual Basic 6 Immediate window: you can assign variables, run procedures, and invoke methods in standard Visual Basic syntax. For example, if you break the program inside a form class, you can change the form’s caption using this statement:

Me.Text = "my new window title"

As in Visual Basic 6, you display the value of a variable, property, or expression by prefixing it with a ? (question mark):

? Me.Text

You can run a Visual Studio command while in immediate mode by prefixing the command with the > symbol, as you see here:

>efuc "Property "

You can switch back from immediate mode to command mode by typing >cmd.

Debug Windows The Visual Studio .NET debugger is much more powerful than the integrated debugger that comes with Visual Basic 6. Figure 14 shows the many commands available on the Debug menu and a few of the windows you can use to debug your application, including these:

• The Breakpoint window, from which you can create, view, disable, and delete breakpoints in code. Visual Studio .NET supports breakpoints that always fire, fire when a condition is true, fire when a particular expression’s value changes, or fire only when they are hit a given number of times.

• Watch windows, which display the value of one or more expressions that you enter. (Visual Studio supports up to four Watch windows.)

• The Me window, which displays the value of all the properties of the object whose code is executing.

Page 17: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

• The Autos window, which displays the value of all the variables referenced in the current statement and the three statements on either side of the current statement.

• The Locals window, which displays the value of all the properties of the running object and the local variables and arguments of the current procedure.

• The Call Stack window, which displays all the pending procedures that called the current one.

• The Threads window, which displays information about all the running threads.

• The Modules window, which lists all the DLLs used by the program being debugged. The path and the version of each DLL are displayed, so you can use this tool to detect subtle versioning problems.

• Memory windows, which display the contents of memory as bytes and ASCII strings; you can watch up to four memory regions at the same time. (If you know what you’re doing, you can even modify memory with this tool.)

• The Disassembly window, in which you see the native code produced by each statement of your Visual Basic or C# program and even step through each assembly instruction.

• The Registers window, in which you see the contents of individual CPU registers. (This window is commonly used with the Disassembly window.)

Figure 14 All the commands in the Windows Debug and Debug menus. You can also see a few debug windows in the background, such as Disassembly, Registers, Breakpoints, Call Stack, and Me.

Page 18: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

Using the commands in the Debug menu, you can display two additional dialog boxes:

• The Processes dialog box, which lists all the running Windows processes and lets you select which ones you want to debug; this tool is great for debugging multiple applications at once.

• The Exceptions dialog box, which lets you decide what happens when a given exception occurs.

I’ll describe a few of these debugging windows later in this book.

Macro Explorer One of the most exciting features of the new version of Visual Studio is its ability to record and play macros to automate repetitive editing actions. Even better, you can browse the actual macro code and modify it if you want.

You record a macro by pointing to Macro on the Tools menu and clicking Record TemporaryMacro (or pressing the Ctrl+Shift+R keyboard shortcut), and then using the mouse or typing something in the code editor; the macro recorder also records menu commands, find and replace commands, window activations, and select actions in the Solution Explorer.

When you have completed your action, stop recording by pressing Ctrl+Shift+R again, or just click the Stop Recording button on the Recorder toolbar that has appeared in the meantime. You can also cancel the recording without saving by clicking the Cancel Recording button on this toolbar.

If you didn’t cancel the macro recording, a new macro named TemporaryMacro will have been created. You can play all the actions in this macro by pointing to Macros on the Tools menu and clicking Run TemporaryMacro or by pressing the Ctrl+Shift+P keyboard shortcut.

Each time you record a new macro, the macro named TemporaryMacro is overwritten, so you should rename it something else if you want to save the macro you’ve just recorded. Do so by pointing to Macros on the Tools menu and clicking Macro Explorer to open the Macro Explorer, which you can see in Figure 15. Then right-click on TemporaryMacro, click Rename on the shortcut menu, and change the macro’s name.

Note If you’re a curious developer, click Edit in the shortcut menu to open the Macro IDE and look at the code produced for you by the macro recorder. The Macro IDE is a complete environment for writing, running, and debugging macros.

Page 19: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

Figure 15 The Macro Explorer.

You can run a nontemporary macro in three ways:

• Double-click it in the Macro Explorer (or click Run on the shortcut menu).

• Type its name in the Command window in command mode. This action works because your new macro has, in effect, become a Visual Studio command.

• Assign it a keyboard shortcut. You can do this from inside the Keyboard page of the Options dialog box, as shown in Figure 16. (Click Options on the Tools menu to display this dialog box.) You can use this dialog box to assign keyboard shortcuts to any Visual Studio command, not just the commands you create by recording a macro.

Page 20: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

Figure 16 The Keyboard page in the Options dialog box lets you assign a keyboard shortcut to any Visual Studio built-in command as well as your own macros.

If you want to learn more about macros, look at the items under the Samples node in the Macro Explorer. These macros come with Visual Studio and are excellent examples of macro programming; a few of these macros are useful in themselves. For example, the VSEditor.FillCommentParagraph macro reformats a multiline comment with the specified right margin, and VSEditor.SaveBackup saves the current document with the .bak extension.

Running a Visual Basic Console Application Earlier in this file, I showed you how to use the VBC compiler to create console applications with Visual Basic .NET. In this section, I’ll show you how to create a console application from inside the Visual Studio IDE.

First point to New on the File menu, and click Project; select Console Application in the Templates pane on the right of the New Project dialog box. Then name the project FirstConsoleApp, and click OK. Visual Studio then creates a project with two files: Module1.vb and AssemblyInfo.vb. (All Visual Basic projects contain the latter file: its purpose will be clear only in Chapter 13, so let’s ignore it for now.) Module1.vb contains the following code template:

Module Module1 Sub Main() End Sub End Module

Page 21: Introduction to Visual Studio - hesab.net Documents/Introduction to... · Introduction to Visual Studio .NET You can use Visual Studio .NET (or Visual Studio 7.1, if you prefer to

All console applications use the System.Console object, which represents the console window. This object exposes several properties and methods, but we will use only three of them:

• The ReadLine method waits for the end user to enter a value and press the Enter key; it then returns the typed string.

• The Write method outputs a string to the console window.

• The WriteLine method is similar to the Write method but also appends a newline character.

You can embed numbered placeholders in the output string you pass to the Write and WriteLine methods; these placeholders are replaced by the value of additional arguments passed to the method. The following code shows how to use these placeholders:

Module Module1 Sub Main() Dim username As String ' Ask for user name. Console.Write("Enter your name: ") username = Console.ReadLine() ' Say hi, and tell current time. Console.WriteLine("Hello, {0}. Current time is {1}", _ username, Now) End Sub End Module

You can run a program from inside the Visual Studio IDE by pressing the F5 key (as in Visual Basic 6), which corresponds to the Start command on the Debug menu. The problem with this command is that the console window is closed as soon as the Main procedure is exited, so you can’t see the output from the last Console.WriteLine method.

You can work around this issue by inserting a call to the Console.ReadLine method just before the End Sub statement. Or you can run the program by pressing the Ctrl+F5 key (or the Start Without Debugging command on the Debug menu); in this case, the console window is closed when the user presses a key. (See Figure 17.) However, as the command name implies, the program is compiled without debugging support, and you can’t set breakpoints or check variable values during its execution.

Figure 17 Output of the sample console application when run with the Debug command from the Start Without Debugging menu.