Partager via


Visual Studio 2008 and C# Express 2008

This chapter is excerpted from Learning C# 3.0: Master the fundamentals of C# 3.0 by Jesse Liberty, Brian MacDonald, published by O'Reilly Media

Learning C# 3.0

Logo

Buy Now

In Chapter 1, C# and .NET Programming, you learned that you can create your C# applications using Notepad. In this chapter, you'll learn why you never will. Microsoft developed Visual Studio 2008 to facilitate the creation of Windows and web applications. You will find that this integrated development environment (IDE) is a very powerful tool that will greatly simplify your work.

Visual Studio 2008 offers many advantages to the .NET developer, among them:

  • A modern interface, using a tabbed document metaphor for code and layout screens, and dockable toolbars and information windows.

  • Convenient access to multiple design and code windows (this will make more sense when you are creating web applications, as shown in Chapter 20, ADO.NET and Relational Databases).

  • WYSIWYG (What You See Is What You Get) visual design of Windows and Web Forms.

  • Code completion, which allows you to enter code with fewer errors and less typing.

  • IntelliSense, which displays tips for every method, providing the return type and the types of all the parameters.

  • Dynamic, context-sensitive help, which allows you to view topics and samples relevant to the code you are writing at the moment. You can also search the complete SDK library from within the IDE.

  • Immediate flagging of syntax errors, which allows you to fix problems as they are entered.

  • A Start Page, which provides easy access to new and existing projects.

  • The same code editor for all .NET languages, which shortens the learning curve. Each language can have specialized aspects, but all languages benefit from shared features, such as incremental search, code outlining, collapsing text, line numbering, and color-coded keywords.

  • An HTML editor, which provides both Design and HTML views that update each other in real time.

  • A Solution Explorer, which displays all the files that make up your solution in outline form.

  • An integrated debugger, which allows you to step through code, observe program runtime behavior, and set breakpoints, even across multiple languages and multiple processes.

  • Customization capability, which allows you to set user preferences for IDE appearance and behavior.

  • Integrated support for source control software.

  • A built-in task list.

  • The ability to modify your controls' properties, either declaratively or through the Properties window.

  • The ability to integrate custom controls that you create or purchase from a third party.

  • Rapid and easy deployment, including the ability to copy an entire website development project from one machine to another.

  • The ability to integrate third-party tools into Visual Studio.

  • The ability to program extensions to Visual Studio.

  • The ability to rename methods, properties, and so forth and have them renamed automatically throughout the program.

  • A Server Explorer, which allows you to log on to servers that you have network access to, access the data and services on those servers, drag-and-drop data sources onto controls, and perform a variety of other chores.

  • Integrated build and compile support.

  • The ability to drag-and-drop controls onto your web page, either in Design mode or in HTML mode.

Visual Studio 2008 and Visual C# 2008 Express are highly useful tools that can save you hours of repetitive tasks. They are also large and complex programs, so it is impossible for us to explore every nook and cranny in this chapter. Instead, we'll take you on a quick tour of the interface and lay the foundation for understanding and using C# Express, which is our IDE of choice for this book, as well as point out some of the nastier traps you might run into along the way.

Tip

Just about every feature we describe in this chapter can also be found in Visual Studio 2008. If there are any significant differences, we'll point them out specifically, but for the most part, you can treat the two IDEs as identical.

Before You Read Further

This chapter has a lot of information in it, and you won't need all of it all at once. In fact, much of the information will not even apply to console applications, but will be valuable when you are ready to create Windows or web applications.

Many readers like to skim this chapter the first time through, and then come back for the details later. But it is your book, you paid for it (you did pay for it, didn't you?), and so you are free to read the entire chapter, take notes as you go, skip it entirely, or otherwise use it to your best advantage.

Whether or not you read this chapter, we do strongly recommend that you spend time (lots and lots of time) exploring C# Express in detail. You will forever be surprised at how much is in there and how much you can set it up to behave as you want; it is your principal development tool. Ignoring C# Express would be like a race car driver never looking under the hood. In time, you not only want to know how to change the oil, but also want to understand how the valves work and why the linkage sticks.

The Start Page

The Start Page is the first thing you see when you open C# Express (unless you configure it otherwise). From here, you can create new projects or open a project you worked on in a previous session. You can also find out what is new in .NET, access .NET newsgroups and websites, search for help online, download useful code, or adjust C# Express to your personal requirements. Figure 2.1, "The C# Express Start Page is the first thing you'll see when you start C# Express. From here, there are many different links to get you started." shows a typical Start Page, which you already saw briefly in Chapter 1, C# and .NET Programming.

The Start Page has a window on the left that includes a list of your recent projects; you can click on any one to open it. Below those links, you'll find the Open link, which lets you open any existing project on your computer. Under that is the Create link, which lets you create a new project. The Getting Started box on the lower left provides links to features and helpful sites. Most of the real estate on the Start Page is taken up by the large box in the middle, which contains useful articles from MSDN online, if you have an active Internet connection.

Projects and Solutions

A C# program is built from source files, which are text files containing the code you write. Source code files are named with the .cs extension. The Program.cs file you created in Chapter 1, C# and .NET Programming is an example.

A typical C# Express 2008 application can have a number of other files (such as assembly information files, references, icons, data connections, and more). C# Express 2008 organizes these files into a container called a project.

Figure 2.1. The C# Express Start Page is the first thing you'll see when you start C# Express. From here, there are many different links to get you started.

The C# Express Start Page is the first thing you'll see when you start C# Express. From here, there are many different links to get you started.

C# Express 2008 provides two types of containers for your source code, folders, files, and related material: the project and the solution. A project is a set of files that work together to create an executable program (.exe) or a dynamic link library (.dll). Large, complex projects may contain multiple .dll files.

A solution is a set of related projects, although it may also have just one project-which is what you'll do most often in this book. Each time you create a new project, C# Express 2008 either adds it to an existing solution or creates a new solution.

Solutions are defined within a file named for the solution, and they have the extension .sln. The .sln file contains metadata, which is basically information about the data. The metadata describes the projects that compose the solution and information about building the solution. You won't have to worry about these for the most part.

Tip

Visual Studio 2008 also creates a file with the same base name as the .sln file, but with the filename extension .sou (such as mySolution.sln and mySolution.sou). The .sou file contains metadata used to customize the IDE for the specific user.

There are a number of ways to open an existing solution. The simplest way is to select Open Project from the Start menu (which opens a project and its enclosing solution). Alternatively, you can open a solution in C# Express 2008 just by double-clicking the .sln file in Windows Explorer.

Typically, the build process results in the contents of a project being compiled into an executable (.exe) file or a dynamic link library (.dll) file. This book focuses on creating executable files.

Tip

The metadata describing the project is contained in a separate file named after the project with the extension .csproj. The project file contains version information, build settings, and references to other source files to include as part of the project.

Project Types

You can create many types of projects in the full version of Visual Studio 2008, including:

  • Console Application projects

  • Windows Application projects

  • Windows Service projects

  • WPF Application projects

  • WPF Browser Application projects

  • Windows Control Library projects

  • Web Control Library projects

  • Class Library projects

  • Smart device templates

  • Crystal Reports Windows Application projects

  • SQL Server projects

  • Word and Excel Document and Template projects

Note that web applications are missing from this list. Web applications do not use projects, just solutions.

Visual C# Express, being a "light" version of the Visual Studio product, can't produce nearly as many types of projects. C# Express is limited to console applications, Windows Forms applications, WPF applications, WPF browser applications, and class libraries.

A typical .NET application comprises many items: source files (such as .cs files), assemblies (such as .exe and .dll files) and assembly information files, data sources (such as .mdb files), references, and icons, as well as miscellaneous other files and folders. Visual Studio 2008 makes all of this easier for you by organizing these items into a folder that represents the project. The project folder is housed in a solution. When you create a new project, Visual Studio 2008 automatically creates the solution.

Templates

When you create a new project with C# Express, you'll see the New Project dialog box, shown in Figure 2.2, "The New Project dialog is where every new C# application starts.".

Figure 2.2. The New Project dialog is where every new C# application starts.

The New Project dialog is where every new C# application starts.

In the New Project dialog, if you're using Visual C# Express, you'll see only the templates you can choose from for your project. If you're using Visual Studio 2008, this dialog box will look different, with two panes. You select the project type (in the lefthand pane) and the template (in the right). There are a variety of templates for each project type. A template is a file that C# Express 2008 uses to set up the initial state of your project.

If you're using Visual Studio 2008, for the examples in this book you'll always choose Visual C# for the project type, and in most cases you'll choose Console Application as the template. Specify the name of the directory in which your project will be stored in the Location box and name your project in the Name box. C# Express doesn't give you the option of choosing the file location; the files are stored in your local My Documents folder, in a subfolder called Visual Studio 2008.

Tip

Project names can contain any standard characters, except leading or trailing spaces, Windows or DOS keywords, and any of the following special characters: # % & * | \ : " < > ? /.

Inside the Integrated Development Environment

The C# Express IDE is centered on its editor. An editor is much like a word processor, except that it produces simple text (that is, text with no formatting, such as bold and italics). All source code files are simple text files. The color that you saw applied to some of the text in the Hello World project in Chapter 1, C# and .NET Programming isn't just formatting; it's a form of highlighting that Visual Studio applies to help you differentiate between keywords, comments, and other kinds of code elements.

The C# Express IDE also provides support for building graphical user interfaces (GUIs), which are integral to Windows and web projects. The following pages introduce some of the key features of the IDE.

The IDE is a Multiple Document Interface (MDI) application, much like other Windows applications you may be used to, such as Word and Excel. There is a main window, and within the main window are a number of smaller windows. The central window is the text editing window. Figure 2.3, "The IDE is where you'll be spending most of your time as a C# developer. Notice that the interface contains multiple windows." shows the basic layout.

Figure 2.3. The IDE is where you'll be spending most of your time as a C# developer. Notice that the interface contains multiple windows.

The IDE is where you'll be spending most of your time as a C# developer. Notice that the interface contains multiple windows.

To the left of the editing window are a number of tabbed windows that contain tools you may need when creating Windows and web applications. To the right of the editing window are both stacked and tabbed windows. Shown on top is the Solution Explorer, which allows you to examine and manipulate the files in the solution. Below the Solution Explorer is the Properties window. The Properties window is used extensively when you're creating web and Windows desktop applications, but you won't see it when you create console applications.

In Visual Studio 2008, at the bottom of the IDE are five tabbed windows-Error List, Task List, Output, Find Results, and Find Symbol Results-but they don't appear in C# Express.

All of these windows, plus the Toolbox, are resizable and dockable. You can resize any of them by placing the mouse cursor over the edge you want to move. The cursor will change to a double-arrow resizing cursor, at which point you can drag the window edge one way or the other, just like most other windows in the Windows interface.

Right-clicking on the title bar of a dockable window pops up a menu with five mutually exclusive check items:

  • Floating
    The window will not dock when dragged against the edge of the C# Express 2008 window. The floating window can be placed anywhere on the desktop, even outside the C# Express 2008 window.

  • Dockable
    The window can be dragged and docked along any side of the C# Express 2008 window, as you'll see later in this chapter.

  • Tabbed Document
    The window occupies the work surface, with a set of tabs for navigation.

  • Auto Hide
    The window will disappear, indicated only by a tab, when the cursor is not over the window. It will reappear when the cursor is over the tab. A pushpin in the upper-right corner of the window will be pointing down when Auto Hide is turned off and pointing sideways when it is turned on.

  • Hide
    The window disappears. To see the window again (to unhide it), use the View main menu item.

If you click the title bar of a window and drag it, it floats free. You can now place it where you want. C# Express 2008 provides guides to help you with locating the window. To see this at work, grab the Properties window and pull it free of its current position. As you move about, the IDE positioning indicators appear, as shown in Figure 2.4, "You can reposition all of the windows in the IDE wherever you like. The arrow icons are a help when you're positioning windows.".

As you click on each positioning indicator, a shadow appears to show you where the window would go if you release the mouse. Notice in the center of the editing window that there is a cluster of five indicators. If you choose the center square, the window will be tabbed with the current window. To put the Properties window back where it belongs, hover over the Solution Explorer window; a five-part indicator will appear, and you can select the lower indicator to place the Properties window below the tabbed set of the Solution Explorer.

You can also double-click on either the title bar or the tab to dock and undock the window. Double-clicking on the title while docked undocks the entire group. Double-clicking on the tab undocks just the one window, leaving the rest of the group docked.

Figure 2.4. You can reposition all of the windows in the IDE wherever you like. The arrow icons are a help when you're positioning windows.

You can reposition all of the windows in the IDE wherever you like. The arrow icons are a help when you're positioning windows.

Building and Running Applications

You can run your application at any time by selecting either Start or Start Without Debugging from the Debug menu, or you can accomplish the same results by pressing either F5 or Ctrl-F5, respectively. You can also start the program by clicking the Start icon () on the Standard toolbar.

For console applications, as we mentioned in Chapter 1, C# and .NET Programming, the advantage of running the program with Ctrl-F5 is that C# Express 2008 will open your application in a console window, display its results, and then add a line to press a key when you are ready. This keeps the window open until you've seen the results and pressed a key, at which point the window will close. If you choose Start (with debugging) on a console application, if the application doesn't require any user input (as Hello World doesn't), the console window may appear and disappear too quickly for you to see what it did.

You can build the program (that is, generate the .exe and .dll files) by selecting a command under the Build menu. You have the option of building the entire solution or only the currently selected project.

The menus provide access to many of the commands and capabilities of C# Express 2008. The more commonly used menu commands are duplicated with toolbar buttons for ease of use.

The menus and toolbars are context-sensitive, meaning that the available selection depends on what part of the IDE is currently selected, and what activities are expected or allowed. For example, if the current active window is a code-editing window for a console application such as Hello World, the top-level menu commands are File, Edit, View, Refactor, Project, Build, Debug, Data, Tools, Test (only in the full Visual Studio), Window, and Help.

Many of the menu items have keyboard shortcuts, listed adjacent to the menu item itself. These are composed of one or more keys (referred to as a chord), pressed simultaneously. Shortcut keys can be a huge productivity boost because you can use them to perform common tasks quickly, without removing your hands from the keyboard, but it's really a matter of personal preference.

The following sections describe some of the more important menu items and their submenus, focusing on those aspects that are interesting and different from common Windows commands.

The File Menu

The File menu provides access to a number of file-, project-, and solution-related commands. Many of these commands are context-sensitive.

As in most Windows applications, the New menu item creates new items to work on, the Open item opens existing items, and the Save item saves your work. One item you may not have seen before is Save All, which will save all the open files in an open solution. This can be very useful when you're working with a large solution.

The Edit Menu

The Edit menu contains the text editing and searching commands that one would expect, but also includes commands useful in editing code. The most useful are discussed next.

The Clipboard Ring

The Clipboard Ring is like copy-and-paste on steroids. You can copy a number of different selections to the Windows clipboard, using the Edit → Cut (Ctrl-X) or Edit → Copy (Ctrl-C) command. Then use Ctrl-Shift-V to cycle through all the selections, and paste the correct one when it comes around.

Tip

You can change C# Express hot keys systematically or individually; the ones we refer to here and throughout this book are the "standard keys" used when programming in C#. Your mileage may vary.

This submenu item is context-sensitive and is visible only when editing a code window.

Find and Replace

C# Express 2008 includes a number of advanced Find and Replace options that you'll use frequently. The most common ones are discussed in this section.

Quick Find and Quick Replace. These are just slightly jazzed names for slightly jazzed versions of the typical Find and Replace. You can access Quick Find with Ctrl-F and Quick Replace with Ctrl-H. Both commands bring up essentially the same dialog boxes, switchable by a tab at the top of the dialog box, as shown in Figure 2.5, "The Find and Replace features work mostly like they do in any Windows application, although in C# Express, you have the option of searching single files or the whole solution, and other advanced features such as regular expressions.".

The search string defaults to the text currently selected in the code window, or, if nothing is selected, to the text immediately after the current cursor location.

The "Look in" drop-down offers a choice of Current Document, All Open Documents, Current Project, Entire Solution, or Current Method.

You can expand or collapse the search options by clicking on the plus/minus button next to the "Find options" item. By default, "Search hidden text" is checked, which allows the search to include code sections currently collapsed in the code window. The Use checkbox allows the use of either regular expressions or wildcards.

Tip

Regular expressions are a language unto themselves, expressly designed for incredibly powerful and sophisticated searches. A full explanation of regular expressions is beyond the scope of this book, and isn't really necessary for the sorts of searches you normally conduct when writing code. For a complete discussion of regular expressions, see the SDK documentation, or Mastering Regular Expressions, Third Edition, by Jeffrey E. F. Friedl (O'Reilly).

Figure 2.5. The Find and Replace features work mostly like they do in any Windows application, although in C# Express, you have the option of searching single files or the whole solution, and other advanced features such as regular expressions.

The Find and Replace features work mostly like they do in any Windows application, although in C# Express, you have the option of searching single files or the whole solution, and other advanced features such as regular expressions.

If the Use checkbox is checked, the Expression Builder button to the right of the "Find what" text box becomes enabled, providing a very handy way to insert valid regular expression or wildcard characters.

Once you've entered a search string in the "Find what" text box, the Find Next button becomes enabled. In Quick Find mode, there is also a Bookmark All button, which finds all occurrences of the search string and places a bookmark (described shortly) next to the code.

In Quick Replace mode, there is also a "Replace with" text box, and buttons for replacing either a single occurrence or all occurrences of the search string.

Find in Files. Find in Files (Ctrl-Shift-F) is a very powerful search utility that finds text strings anywhere in a directory or in subdirectories (subfolders). It presents the dialog box shown in Figure 2.6, "The Find and Replace in Files feature lets you search in files other than the one you're working with right now.". Checkboxes present several self-explanatory options, including the ability to search using either wildcards or regular expressions. Depending on how many files you have in your solution, you may want to use this kind of search as your default first choice.

Find Symbol. Clicking the Find Symbol command (Alt-F12) will bring up the Find Symbol dialog box, which allows you to search for symbols (such as namespaces, classes, and interfaces) and their members (such as properties, methods, events, and variables). It also allows you to search in external components for which the source code is not available.

Figure 2.6. The Find and Replace in Files feature lets you search in files other than the one you're working with right now.

The Find and Replace in Files feature lets you search in files other than the one you're working with right now.

The search results will be displayed in a window labeled Find Symbol Results. From there, you can move to each location in the code by double-clicking on each result.

Go To

The Go To command brings up the Go To Line dialog box, which allows you to enter a line number and immediately go to that line. It is context-sensitive and is visible only when editing a text window.

Insert File As Text

The Insert File As Text command allows you to insert the contents of any file into your source code, as though you had typed it in. It is context-sensitive and is visible only when editing a text window.

You'll see a standard file-browsing dialog box to search for the file you want to insert. The default file extension will correspond to the project language, but you can search for any file with any extension.

Advanced

The Advanced command is context-sensitive and is visible only when editing a code window. It has many submenu items. These include commands for:

  • Viewing whitespace (making tabs and space characters visible on the screen)

  • Toggling word wrap

  • Commenting and uncommenting blocks of text

  • Increasing and decreasing line indenting

  • Incremental searching (see "Incremental search")

The following three options are available only in Visual Studio, not C# Express:

  • Creating or removing tabs in a selection (converting spaces to tabs and vice versa)

  • Forcing selected text to uppercase or lowercase

  • Deleting horizontal whitespace

Incremental search allows you to search an editing window by entering the search string character by character. As you enter each character the cursor moves to the first occurrence of matching text.

To use incremental search in a window, select the command on the Advanced submenu, or press Ctrl-I. The cursor icon will change to a pair of binoculars with an arrow indicating the direction of the search. Begin typing the text string to search for.

The case sensitivity of an incremental search will come from the previous Find, Replace, Find in Files, or Replace in Files search (described earlier).

The search will proceed downward and from left to right from the current location. To search backward, use Ctrl-Shift-I.

The key combinations listed in Table 2.1, "Incremental searching" apply to incremental searching.

Table 2.1. Incremental searching

Key combination

Description

Esc

Stop the search.

Backspace

Remove a character from the search text.

Ctrl-Shift-I

Change the direction of the search.

Ctrl-I

Move to the next occurrence in the file for the current search text.

Bookmarks

Bookmarks are useful for marking spots in your code and easily navigating from marked spot to marked spot. There are several context-sensitive commands on the Bookmarks submenu (listed in Table 2.2, "Bookmark commands"). Note that, unless you add the item to the task list, bookmarks are lost when you close the file, although they are saved when you close the solution (as long as the file was still open).

Table 2.2. Bookmark commands

Command

Description

Toggle Bookmark

Places or removes a bookmark at the current line. When a bookmark is set, a blue rectangular icon will appear in the column along the left edge of the code window.

Enable/Disable

Enables or disables the checkboxes for all bookmarks in the Bookmarks window (does not remove bookmarks).

Previous Bookmark

Moves to the previous bookmark.

Next Bookmark

Moves to the next bookmark.

Clear

Removes the bookmark.

Previous Bookmark in Folder (Visual Studio only)

Moves to the previous bookmark in the folder.

Next Bookmark in Folder (Visual Studio only)

Moves to the next bookmark in the folder.

Previous Bookmark in Document

Moves to the previous bookmark in the current document.

Next Bookmark in Document

Moves to the next bookmark in the current document.

Add Task List Shortcut

Adds an entry to the task list (described in "The View Menu" later in this chapter) for the current line. When a task list entry is set, a curved arrow icon appears in the column along the left edge of the code window.

This menu item appears only when the current window is a code window.

Outlining

C# Express 2008 allows you to outline, or collapse and expand, sections of your code to make it easier to view the overall structure. When a section is collapsed, it appears with a plus sign in a box along the left edge of the code window. Clicking on the plus sign expands the region.

You can nest the outlined regions so that one section can contain one or more other collapsed sections. Several commands are available to facilitate outlining (shown in Table 2.3, "Outlining commands").

Table 2.3. Outlining commands

Command

Description

Toggle Outlining Expansion

Reverses the current outlining state of the innermost section in which the cursor lies.

Toggle All Outlining

Sets all sections to the same outlining state. If some sections are expanded and some are collapsed, all will become collapsed.

Stop Outlining

Expands all sections and removes the outlining symbols from view.

Collapse to Definitions

Automatically creates sections for each procedure in the code window and collapses them all.

You can set the default behavior of outlining using the Tools → Options menu item. Go to Text Editor, and then the specific language for which you want to set the options.

IntelliSense

Microsoft IntelliSense technology makes your life much easier. It has real-time, context-sensitive help available, which appears right under your cursor. Code completion automatically completes your thoughts for you, drastically reducing your typing (and therefore, your typing errors). Drop-down lists provide all methods and properties possible in the current context, available at a keystroke or mouse click.

You can configure the default IntelliSense features by going to Tools → Options and then the language-specific pages under Text Editor.

Most of the IntelliSense features appear as you type inside a code window or allow the mouse to hover over a portion of the code. In addition, the Edit → IntelliSense menu item offers numerous commands, the most important of which are shown in Table 2.4, "IntelliSense commands".

Table 2.4. IntelliSense commands

Command

Description

List Members

Displays a list of all possible members available for the current context. Keystrokes incrementally search the list. Press any key to insert the highlighted selection into your code; that key becomes the next character after the inserted name. Use the Tab key to select without entering any additional characters.

This can also be accessed by right-clicking and selecting List Member from the context-sensitive menu.

Parameter Info

Displays a list of numbers, names, and types of parameters required for a method, sub, function, or attribute.

Quick Info

Displays the complete declaration for any identifier (such as a variable name or class name) in your code. This is also enabled by hovering the mouse cursor over any identifier.

Complete Word

Automatically completes the typing of any identifier once you type in enough characters to uniquely identify it. This works only if the identifier is being entered in a valid location in the code.

Insert Snippet

Displays a selection of code snippets to insert, such as the complete syntax for a switch case block or an if block.

Surround With

Displays a selection of code snippets to surround a block of code, such as a class declaration.

The member list presents itself when you type a dot operator following any class or member name.

Every member of the class is listed, and each member's type is indicated by an icon. There are icons for methods, fields, properties, events, and so forth. In addition, each icon may have a second icon overlaid to indicate the accessibility of the member: public, private, protected, and so on. If there is no accessibility icon, the member is public.

Tip

If the member list does not appear, make sure you have added all the necessary using statements.

Two of the subcommands under the IntelliSense menu item, Insert Snippet and Surround With, tap into a great feature to reduce typing and minimize errors: code snippets. A code snippet is a chunk of code that replaces an alias. A short alias is replaced with a much longer code snippet. For example, the alias switch would be replaced with:

switch ( switch_on )
{
   default:
}

with the expression switch_on highlighted in yellow and the cursor in place, ready to type in your own expression. In fact, all the editable fields will be highlighted, and you can use the Tab key to navigate through them, or Shift-Tab to go backward. Any changes made to the editable field are immediately propagated to all the instances of that field in the code snippet. Press Enter or Esc to end the field editing and return to normal editing.

To do a straight alias replacement, either select Insert Snippet from the menu, or more easily, press Ctrl-K, Ctrl-X. Or, just type an alias in the code window and an IntelliSense menu will pop up with a list of aliases, with the current one highlighted. Press Tab to insert the snippet.

Alternatively, a code snippet can surround highlighted lines of code-say, with a for construct. To surround lines of code with a code snippet construct, highlight the code and then either select Surround With from the menu or press Ctrl-K, Ctrl-S.

The View Menu

The View menu is a context-sensitive menu that provides access to the myriad windows available in the C# Express 2008 IDE. You will probably keep many of these windows open all the time; others you will use rarely, if at all.

The View menu is context-sensitive. For example, with an ASP.NET content file on the work surface, the first three menu items will be Code, Designer, and Markup; the Code and Designer menu items will be omitted if you're looking at a code-behind file. You don't need to worry about what these terms mean for now; you'll see them in the closing chapters of the book.

When the application is running, a number of other windows, primarily used for debugging, become visible or available. You access these windows via the Debug → Windows menu item, not from the View menu item.

C# Express 2008 can store several different window layouts. In particular, it remembers a completely different set of open windows during debug sessions than it does during normal editing. These layouts are stored per-user, not per-project or per-solution.

Class View

The Class View window (Ctrl-Shift-C) shows all the classes in the solution in a hierarchical manner. A typical Class View window, somewhat expanded, is shown in Figure 2.7, "The Class View window, obviously enough, shows the classes in your solution. You won't have many of these at first, but Windows applications will have plenty.".

As with the Solution Explorer, you can right-click any item in the Class View window, which exposes a pop-up menu with a number of context-sensitive menu items. This can provide a convenient way to sort the display of classes in a project or solution, or to add a method, property, or field to a class.

Code Definition

The Code Definition window (Ctrl-W, D) is used in developing web pages, but is available only in the full version of Visual Studio.

Error List

The Error List window (Ctrl-W, Ctrl-E), which is available in all editor views, displays errors, warnings, and messages generated as you edit and compile your project. Syntax errors flagged by IntelliSense are displayed here, as well as deployment errors. Double-clicking on an error in this list will open the offending file and move the cursor to the error location.

Output

The Output window (Ctrl-Alt-O) displays status messages from the IDE, such as build progress. You can set the Output window to display by default when a build starts by going to Tools → Options → Projects and Solutions → General and checking "Show Output window when build starts".

This window is available in all editor views.

Figure 2.7. The Class View window, obviously enough, shows the classes in your solution. You won't have many of these at first, but Windows applications will have plenty.

The Class View window, obviously enough, shows the classes in your solution. You won't have many of these at first, but Windows applications will have plenty.

Properties

The Properties window (F4) displays all the properties for the currently selected item. Some of the properties (such as Font) may have subproperties, indicated by a plus sign next to their entries in the window. The property values on the right side of the window are editable.

One thing that can be confusing is that certain items have more than one set of properties. For example, a Form content file can show two different sets of properties, depending on whether you select the source file in the Solution Explorer or the form as shown in the Design view.

A typical Properties window is shown in Figure 2.8, "You won't use the Properties window much with console applications, but when you design Windows Forms, you'll use it a lot.".

Figure 2.8. You won't use the Properties window much with console applications, but when you design Windows Forms, you'll use it a lot.

You won't use the Properties window much with console applications, but when you design Windows Forms, you'll use it a lot.

The name and type of the current object are displayed in the field at the top of the window. In Figure 2.8, "You won't use the Properties window much with console applications, but when you design Windows Forms, you'll use it a lot.", it is an object named Form1, of type Form, contained in the System.Windows.Forms namespace.

You can edit most properties in place in the Properties window. The Font property has subproperties that you can set directly in the window by clicking on the plus sign to expand its subproperties, and then editing the subproperties in place.

The Properties window has several buttons just below the name and type of the object. The first two buttons on the left toggle the list by category or alphabetically. The next two buttons from the left toggle between displaying properties for the selected item and displaying events for the selected item. The rightmost button displays property pages for the object, if there are any.

Tip

Some objects have both a Properties window and property pages. The property pages display additional properties not shown in the Properties window.

The box below the list of properties displays a brief description of the selected property.

Task List

In large applications, keeping a to-do list can be quite helpful. C# Express 2008 provides this functionality with the Task List window.

Toolbox

The Toolbox command (Ctrl-Alt-X) displays the Toolbox if it is not currently displayed. If it is currently displayed, nothing happens-it does not toggle the display. To hide the Toolbox, click on the X in the Toolbox title bar.

Other Windows

Several other windows have been relegated to a submenu called Other Windows. These include:

  • The Command window (Ctrl-Alt-A)
    You use this window to enter commands directly.

  • The Object Test Bench window
    This window lets you conduct tests on your classes as you write them, but only in Visual Studio.

  • The Property Manager window
    You use this window only for C++ projects; it isn't available in C# Express.

  • The Resource View window (Ctrl-Shift-E)
    This window displays the resource files included in the project. Resources are nonexecutable data deployed with an application, such as icons and graphics, culture-specific text messages, and persisted data objects.

  • The Macro Explorer window (Alt-F8)
    Visual Studio 2008 offers the ability to automate repetitive chores with macros. A macro is a set of instructions written in VB.NET, either created manually or recorded by the IDE, saved in a file. The Macro Explorer is the one of the main tools for viewing, managing, and executing macros. It provides access into the Macro IDE.

  • The Start Page
    This item simply reopens the Start Page, if you closed it.

  • The Web Browser
    This item opens a web browser within the Visual Studio window.

The Refactor Menu

Refactoring is the process of taking code duplicated in various parts of your program and extracting it out to a callable method. This is an advanced procedure, so you won't see any refactoring in this book.

Tip

For details on refactoring, we highly recommend the book Refactoring: Improving the Design of Existing Code, by Martin Fowler et al. (Addison-Wesley Professional).

The Refactor menu item is available when you're looking at a code window for a web page, user control, or language source code file. It is also available from context menus when you right-click on an identifier in a Class View, Object Browser, or Solution Explorer window.

The refactoring menu items will modify your code-for example, extracting common code to a method and then calling that method in the place from which it was extracted.

The Project Menu

The Project menu provides functionality related to project management. It is visible only when the solution is selected in the Solution Explorer. All of the functionality exposed by the Project menu is also available in the Solution Explorer, by right-clicking on the solution.

The Build Menu

The Build menu offers menu items for building the current project (highlighted in the Solution Explorer) or the solution. It also exposes the Configuration Manager for configuring the build process.

The Debug Menu

The Debug menu allows you to start an application with or without debugging, set breakpoints in the code, and control the debugging session.

The Data Menu

The context-sensitive Data menu is visible only when in Design mode when creating, for example, web applications.

The Format Menu

The Format menu is visible only in Design mode when creating, for example, web applications; further, the commands under it are context-sensitive to the control(s) currently selected.

The Tools Menu

The Tools menu presents commands accessing a wide variety of functionality, ranging from connecting to databases to accessing external tools to setting IDE options. Some of the more useful commands are described in the following sections.

Connect to Device

The Connect to Device command (available only in Visual Studio) brings up a dialog box that allows you to connect to either a physical mobile device or an emulator.

Device Emulator Manager

The Device Emulator Manager command (also available only in Visual Studio) helps you keep track of the various settings for devices and their emulators for which you may be developing.

Connect to Database

The Connect to Database command brings up the dialog box that allows you to select a server, log in to that server, and connect to the database on the server. Microsoft SQL Server is the default database (surprise!), but the Change button allows you to connect to any number of other databases, including any for which there are Oracle or ODBC providers.

Connect to Server

The Connect to Server command (available only in Visual Studio) brings up a dialog box that lets you enter a remote server to connect to, either by name or by IP address.

Code Snippets Manager

The Code Snippets Manager command (Ctrl-K, Ctrl-B) brings up the Code Snippets Manager dialog box, which allows you to maintain the code snippets (described in "IntelliSense" earlier in this chapter). This dialog box allows you to add or remove code snippets for any of the supported languages. You can also import code snippets and search online for code snippets.

Choose Toolbox Items

The Choose Toolbox Items command brings up the Choose Toolbox dialog box, allowing you to add COM components and custom controls. The details of doing so are beyond the scope of this book, but they are covered in full in Programming ASP.NET 3.5 by Jesse Liberty et al. (O'Reilly).

External Tools

Depending on the options selected at the time C# Express 2008 was installed on your machine, you may have one or more external tools available on the Tools menu. These might include tools such as Create GUID and Dotfuscator Community Edition. (Use of these tools is beyond the scope of this book.)

The Tools → External Tools command allows you to add additional external tools to the Tools menu. When you select this command, you are presented with the External Tools dialog box. This dialog box has fields for the tool title, the command to execute the tool, any arguments and the initial directory, as well as several checkboxes for different behaviors.

Import and Export Settings

The Import and Export Settings command brings up the Import and Export Settings dialog box, which is a wizard for importing and exporting IDE settings. With this wizard, you can transfer your carefully wrought IDE settings from one machine to the next.

Options

The Options command also brings up the Options dialog box that allows you to set a wide variety of options, ranging from the number of items to display in lists of recently used items to HTML Designer options.

The Window Menu

The Window menu is the same as the Window menu you'll find in most standard Windows applications. It displays a list of all the currently open windows, allowing you to bring any window to the foreground by clicking on it. Note that all the file windows currently displayed in the IDE also have tabs along the top edge of the work surface, below the toolbars (unless you have selected MDI mode in Tools → Options → Environment → General), and you can select windows by clicking on a tab.

The Help Menu

The Help menu provides access to a number of submenus.

If you are developing on a machine with enough horsepower, Dynamic Help is a wonderful thing. Otherwise, it can diminish the responsiveness of the IDE.

Summary

  • Visual Studio 2008 is a powerful tool with many features to make writing programs easier.

  • The Start Page provides an overview of your programming environment and a list of recent projects.

  • A solution is a set of related projects, and a project is a set of related code files and associated resources, such as images and so on.

  • Visual Studio 2008 has a number of templates that allow you to create particular types of projects, such as windows or web applications.

  • Among other things, C# Express 2008 provides WYSIWYG support for building, testing, and debugging graphical user interfaces (GUIs).

  • Every window in C# Express 2008 can be resized and moved.

  • To run your application, select Start or Start Without Debugging, or press F5 or Ctrl-F5.

  • The Clipboard Ring can hold a number of different selections that you can cycle through.

  • The Find and Replace feature lets you locate text strings in the current file or other files, using normal text or regular expressions.

  • Bookmarks enable you to mark spots in your code so that you can easily find them later.

  • IntelliSense saves you keystrokes and can help you discover methods and required arguments by (for example) listing possible completions to what you're typing.

  • The Properties window displays properties for the currently selected item.

There's your whirlwind tour of the C# Express interface. If you're new to programming, the IDE probably looks quite intimidating-it has a lot more features and windows than your average Windows application. As with any Windows application, though, you'll quickly find that you use some of the features quite often, and those will become second nature, allowing you to ignore the rest until you need them. We don't expect you to be an expert on the IDE after just reading this chapter, but we do hope you're a bit more comfortable with it. Now, enough poking about in the Toolbox-let's hammer some nails! It's time to start learning the basics of the C# language, starting with types, variables, and constants, and that's what's ahead in Chapter 3, C# Language Fundamentals.

Test Your Knowledge: Quiz

Question 2-1. What is the difference between a project and a solution?

Question 2-2. How do you move windows in the IDE?

Question 2-3. What does the pushpin do on a window?

Question 2-4. What is the difference between pressing F5 and pressing Ctrl-F5 from within C# Express 2008?

Question 2-5. What is the Clipboard Ring?

Question 2-6. How do you retrieve items from the Clipboard Ring?

Question 2-7. What is Find Symbol for?

Question 2-8. What are bookmarks?

Question 2-9. What is IntelliSense?

Question 2-10. What is a code snippet?

Test Your Knowledge: Exercises

Exercise 2-1. Insert a bookmark before the Console.Writeline( ) statement in Hello World. Navigate away from it and then use the Bookmarks menu item to return to it.

Exercise 2-2. Undock the Solution Explorer window from the right side of the IDE and move it to the left. Leave it there if you like, or move it back.

Exercise 2-3. Insert a code snippet for a for loop from the Edit → IntelliSense menu into your Hello World program after the WriteLine( ) statement. (It won't do anything for now; you'll learn about for loops in Chapter 5, Branching.)