38,99 €
The ultimate developers' guide to Visual Studio 2012
This expert Wrox guide is what you need to get up and running quickly on Visual Studio 2012. Written by a Microsoft Visual C# MVP, it guides you through the integrated development environment (IDE), showing you how to maximize all new tools and improvements.
Professional Visual Studio 2012 uses a unique, IDE-centric approach to help you get up and running quickly on this exciting new release.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 1658
Veröffentlichungsjahr: 2012
CONTENTS
Part I: Integrated Development Environment
Chapter 1: A Quick Tour
Getting Started
The Visual Studio IDE
Summary
Chapter 2: The Solution Explorer, Toolbox, and Properties
The Solution Explorer
The Toolbox
Properties
Summary
Chapter 3: Options and Customizations
The Start Page
Window Layout
The Editor Space
Other Options
Importing and Exporting Settings
Summary
Chapter 4: The Visual Studio Workspace
The Code Editor
The Command Window
The Immediate Window
The Class View
The Error List
The Object Browser
The Code Definition Window
The Call Hierarchy Window
The Document Outline Tool Window
Reorganizing Tool Windows
Summary
Chapter 5: Find and Replace and Help
Quick Find/Replace
Find/Replace in Files
Navigate To
Accessing Help
Summary
Part II: Getting Started
Chapter 6: Solutions, Projects, and Items
Solution Structure
Solution File Format
Solution Properties
Project Types
Project Files Format
Project Properties
Web Application Project Properties
Web Site Projects
Summary
Chapter 7: Intellisense and Bookmarks
IntelliSense Explained
JavaScript IntelliSense
IntelliSense Options
Extended IntelliSense
Bookmarks and the Bookmark Window
Summary
Chapter 8: Code Snippets and Refactoring
Code Snippets Revealed
Accessing Refactoring Support
Refactoring Actions
Summary
Chapter 9: Server Explorer
Server Connections
Data Connections
SharePoint Connections
Summary
Chapter 10: Modeling with the Class Designer
Creating a Class Diagram
The Design Surface
The Toolbox
The Class Details
The Properties Window
Layout
Exporting Diagrams
Code Generation and Refactoring
Modeling Power Toys for Visual Studio
Summary
Part III: Digging Deeper
Chapter 11: Unit Testing
Your First Test Case
Asserting the Facts
Initializing and Cleaning Up
Testing Context
Advanced Unit Testing
Testing Code Contracts
Summary
Chapter 12: Documentation with XML Comments
Inline Commenting
XML Comments
Using XML Comments
Generating Documentation with GhostDoc
Compiling Documentation with Sandcastle
Task List Comments
Summary
Chapter 13: Code Consistency Tools
Source Control
Coding Standards
Summary
Chapter 14: Code Generation with T4
Creating a T4 Template
T4 Building Blocks
How T4 Works
T4 Directives
Troubleshooting
Generating Code Assets
Runtime Text Templates
Tips and Tricks
Summary
Chapter 15: Project and Item Templates
Creating Templates
Extending Templates
Starter Kits
Online Templates
Summary
Chapter 16: Language-Specific Features
Hitting a Nail with the Right Hammer
A Tale of Two Languages
Visual Basic
F#
Summary
Part IV: Rich Client Applications
Chapter 17: Windows Forms Applications
Getting Started
The Windows Form
Form Design Preferences
Adding and Positioning Controls
Container Controls
Docking and Anchoring Controls
Summary
Chapter 18: Windows Presentation Foundation (WPF)
What Is WPF?
Getting Started with WPF
The WPF Designer and XAML Editor
Styling Your Application
Windows Forms Interoperability
Debugging with the WPF Visualizer
Summary
Chapter 19: Office Business Applications
Choosing an Office Project Type
Creating a Document-Level Customization
Creating an Application Add-in
Debugging Office Applications
Deploying Office Applications
Summary
Chapter 20: Windows Store Applications
What Is a Windows Store Application?
Creating a Windows Store Application
Summary
Part V: Web Applications
Chapter 21: ASP.NET Web Forms
Web Application Versus Web Site Projects
Creating Web Projects
Designing Web Forms
Web Controls
Master Pages
Rich Client-Side Development
ASP.NET Web Site Administration
Summary
Chapter 22: ASP.NET MVC
Model View Controller
Getting Started with ASP.NET MVC
Choosing a Model
Controllers and Action Methods
Rendering a UI with Views
Advanced MVC
Summary
Chapter 23: Silverlight
What Is Silverlight?
Getting Started with Silverlight
Navigation Framework
Theming
Enabling Running Out of Browser
Summary
Chapter 24: Dynamic Data
Creating a Dynamic Data Web Application
Customizing the Data Model
Customizing the Presentation
Enabling Dynamic Data for Existing Projects
Summary
Chapter 25: Sharepoint
Preparing the Development Environment
Exploring SharePoint 2010
Creating a SharePoint Project
Building Custom SharePoint Components
Working with Features
Packaging and Deployment
Summary
Chapter 26: Windows Azure
The Windows Azure Platform
SQL Azure
AppFabric
Azure Websites
Azure Virtual Machines
Summary
Part VI: Data
Chapter 27: Visual Database Tools
Database Windows in Visual Studio 2012
Editing Data
Summary
Chapter 28: Datasets and Databinding
DataSets Overview
Binding Data
Working with Data Sources
Summary
Chapter 29: Language Integrated Queries (LINQ)
LINQ Providers
Old-School Queries
Query Pieces
Debugging and Execution
LINQ to XML
Querying XML
Schema Support
LINQ to SQL
LINQPad
Summary
Chapter 30: The ADO.NET Entity Framework
What Is the Entity Framework?
Getting Started
Creating an Entity Model
Querying the Entity Model
Advanced Functionality
Summary
Chapter 31: Reporting
Getting Started with Reporting
Designing Reports
Rendering Reports
Deploying Reports
Summary
Part VII: Application Services
Chapter 32: Windows Communication Foundation (WCF)
What Is WCF?
Getting Started
Defining Contracts
Configuring WCF Service Endpoints
Hosting WCF Services
Consuming a WCF Service
Summary
Chapter 33: Windows Workflow Foundation (WF)
What Is Windows Workflow Foundation?
Why Use Windows Workflow?
Workflow Concepts
Getting Started
The Workflow Foundation Designer
Creating a Workflow
Hosting the Workflow Designer
Summary
Chapter 34: Client Application Services
Client Services
Role Authorization
User Authentication
Settings
Login Form
Offline Support
Summary
Chapter 35: Synchronization Services
Occasionally Connected Applications
Server Direct
Getting Started with Synchronization Services
Synchronization Services over N-Tiers
Summary
Chapter 36: WCF RIA Services
Getting Started
Domain Services
Domain Operations
Consuming a Domain Service in Silverlight
Summary
Part VIII: Configuration and Resources
Chapter 37: Configuration Files
.Config Files
Configuration Schema
Application Settings
User Settings
Referenced Projects with Settings
Summary
Chapter 38: Connection Strings
Connection String Wizard
SQL Server Format
In-Code Construction
Encrypting Connection Strings
LocalDB
Summary
Chapter 39: Resource Files
What Are Resources?
Resourcing Your Application
Satellite Resources
Accessing Specifics
Coding Resource Files
Custom Resources
Summary
Part IX: Debugging
Chapter 40: Using The Debugging Windows
The Code Window
The Breakpoints Window
The Output Window
The Immediate Window
The Watch Windows
The Code Execution Windows
The Memory Windows
IntelliTrace (Ultimate Edition Only)
The Parallel Debugging Windows
Exceptions
Summary
Chapter 41: Debugging with Breakpoints
Breakpoints
Tracepoints
Execution Control
Edit and Continue
Summary
Chapter 42: Datatips, Debug Proxies, and Visualizers
DataTips
Debugger Attributes
Type Proxies
Visualizers
Advanced Techniques
Summary
Chapter 43: Debugging Web Applications
Debugging Server-Side ASP.NET Code
Debugging Client-Side JavaScript
Debugging Silverlight
Tracing
Health Monitoring
Summary
Chapter 44: Advanced Debugging Techniques
Start Actions
Debugging with Code
Debugging Running Applications
.NET Framework Source
Multithreaded and Parallelized Application Debugging
Debugging SQL Server Stored Procedures
Mixed-Mode Debugging
Post-Mortem Debugging
Summary
Part X: Build and Deployment
Chapter 45: Upgrading with Visual Studio 2012
Upgrading from Visual Studio 2010
Upgrading to .NET Framework 4.5
Summary
Chapter 46: Build Customization
General Build Options
Manual Dependencies
The Visual Basic Compile Page
C# Build Pages
MSBuild
Summary
Chapter 47: Assembly Versioning and Signing
Assembly Naming
Version Consistency
Strongly Named Assemblies
The Global Assembly Cache
Signing an Assembly
Summary
Chapter 48: Obfuscation, Application Monitoring, and Management
The MSIL Disassembler
Decompilers
Obfuscating Your Code
Application Monitoring and Management
Summary
Chapter 49: Packaging and Deployment
Windows Installer XML Toolset
ClickOnce
Summary
Chapter 50: Web Application Deployment
Website Deployment
Web Application Deployment
Web Project Installers
The Web Platform Installer
Summary
Part XI: Customizing and Extending Visual Studio
Chapter 51: The Automation Model
Visual Studio Extensibility Options
The Visual Studio Automation Model
Summary
Chapter 52: Add-Ins
Developing an Add-in
Deploying Add-ins
Summary
Chapter 53: Managed Extensibility Framework (MEF)
Getting Started with MEF
The Visual Studio Editor
Extending the Editor
Summary
Part XII: Visual Studio Ultimate
Chapter 54: Visual Studio Ultimate for Architects
Modeling Projects
Exploring Code
Summary
Chapter 55: Visual Studio Ultimate for Developers
Code Metrics
Managed Code Analysis Tool
C/C++ Code Analysis Tool
Profiling Tools
Standalone Profiler
IntelliTrace
Database Tools
Summary
Chapter 56: Visual Studio Ultimate for Testers
Automated Tests
Relating Code and Tests
Visual Studio Test Management
Microsoft Test Manager
Summary
Chapter 57: Team Foundation Server
Team Project
Process Templates
Work Item Tracking
Excel and Project Integration
Version Control
Team Foundation Build
Reporting and Business Intelligence
Team Portal
Web Access
Summary
Introduction
Advertisements
CHAPTER 1:
A Quick Tour
CHAPTER 2:
The Solution Explorer, Toolbox, and Properties
CHAPTER 3:
Options and Customizations
CHAPTER 4:
The Visual Studio Workspace
CHAPTER 5:
Find and Replace and Help
WHAT’S IN THIS CHAPTER?
Installing and getting started with Visual Studio 2012
Creating and running your first application
Debugging and deploying an application
Ever since software has been developed, there has been a need for tools to help write, compile, debug, and deploy applications. Microsoft Visual Studio 2012 is the next iteration in the continual evolution of a best-of-breed integrated development environment (IDE).
This chapter introduces the Visual Studio 2012 user experience and shows you how to work with the various menus, toolbars, and windows. It serves as a quick tour of the IDE, and as such it doesn’t go into detail about what settings can be changed or how to go about customizing the layout because these topics are explored in the following chapters.
With each iteration of the Visual Studio product, the installation process has been incrementally improved, meaning that you can get up and running with Visual Studio 2012 with minimal fuss. This section walks you through the installation process and getting started with the IDE.
When you launch Visual Studio 2012 setup, you’ll see the dialog in Figure 1-1 enabling you to specify the location for the installation. After you have read the licensing information (in great detail, of course), you can click the check box to accept the terms and move to the next screen in the installation sequence. You’ll also notice an option to join the Customer Experience Improvement program. If you do so, anonymous information about how you use the product will be sent to Microsoft occasionally. And just so you have a sense of how that information is used, realize that many of the user interface changes that you’re about to see were determined based on this feedback.
FIGURE 1-1
Visual Studio 2012 naturally has a number of mandatory features. Because these features are built in, the installation process doesn’t bother mentioning them. However, you can select from a number of optional features, as shown in Figure 1-2. Choose the features you believe you need (keeping in mind that you can always add or remove them later) and click Install to begin the process.
FIGURE 1-2
At this point, you’ll see the updated progress dialog, as shown in Figure 1-3. Depending on which components you already have installed on your computer, you may be prompted to restart your computer midway through the installation process. When all the components have been successfully installed, a Setup Summary dialog indicates that there were no problems with the installation process.
FIGURE 1-3
When you launch Visual Studio, the Microsoft Visual Studio 2012 splash screen appears. Like a lot of splash screens, it provides information about the version of the product and to whom it has been licensed, as shown in Figure 1-4.
FIGURE 1-4
The first time you run Visual Studio 2012, you’ll see the splash screen only for a short period before you are prompted to select the default environment settings. It may seem unusual to ask those who haven’t used a product before how they imagine themselves using it. Because Microsoft has consolidated a number of languages and technologies into a single IDE, that IDE must account for the subtle (and sometimes not so subtle) differences in the way developers work.
Take a moment to review the various options in this list, as shown in Figure 1-5. The differences between them as reflected in the IDE vary. You’ll find that the environment settings affect the position and visibility of various windows, menus, toolbars, and even keyboard shortcuts. You can’t see the differences while you’re in this list (naturally). But if you select a particular option, such as General Development Settings, a description of the changes that will be applied appears to the right. Chapter 3, “Options and Customizations,” covers how you can change your default environment settings at a later stage.
FIGURE 1-5
Depending on which set of environment settings you select, when you click the Start Visual Studio button, you will most likely see a dialog indicating that Visual Studio is configuring the development environment. When this process is complete, Visual Studio 2012 opens, ready for you to start working, as shown in Figure 1-6.
FIGURE 1-6
Regardless of the environment settings you select, you’ll see the Start Page in the center of the screen. However, the contents of the Start Page and the surrounding toolbars and tool windows can vary.
Before you launch into building your first application, you must take a step back to look at the components that make up the Visual Studio 2012 IDE. Menus and toolbars are positioned along the top of the environment, and a selection of subwindows, or panes, appears on the left, right, and bottom of the main window area. In the center is the main editor space. Whenever you open a code file, an XML document, a form, or some other file, it appears in this space for editing. With each file you open, a tab is created so that you can easily switch between opened files.
On either side of the editor space is a set of tool windows. These areas provide additional contextual information and functionality. For the general developer settings, the default layout includes the Solution Explorer and Class View on the right, and the Server Explorer and Toolbox on the left. The tool windows on the left are in their collapsed, or unpinned, state. If you click a tool window’s title, it expands; it collapses again when it no longer has focus or you move the cursor to another area of the screen. When a tool window is expanded, you see a series of three icons at the top right of the window, similar to those shown in the left image of Figure 1-7.
FIGURE 1-7
If you want the tool window to remain in its expanded, or pinned, state, you can click the middle icon, which looks like a pin. The pin rotates 90 degrees to indicate that the window is now pinned. Clicking the third icon, the X, closes the window. If later you want to reopen this or another tool window, you can select it from the View menu.
The right image in Figure 1-7 shows the context menu that appears when the first icon, the down arrow, is clicked. Each item in this list represents a different way to arrange the tool window. As you would imagine, the Float option enables the tool window to be placed anywhere on the screen, independent of the main IDE window. This is useful if you have multiple screens because you can move the various tool windows onto the additional screen, allowing the editor space to use the maximum screen real estate. Selecting the Dock as Tabbed Document option makes the tool window into an additional tab in the editor space. In Chapter 4, “The Visual Studio Workspace,” you’ll learn how to effectively manage the workspace by docking and pinning tool windows.
Now that you have seen an overview of the Visual Studio 2012 IDE, this section walks you through creating a simple application that demonstrates working with some of these components. This is, of course, the mandatory “Hello World” sample that every developer needs to know, and it can be done in either Visual Basic .NET or C#, depending on what you feel more comfortable with.
FIGURE 1-8
FIGURE 1-9
FIGURE 1-10
FIGURE 1-11
FIGURE 1-12
FIGURE 1-13
You’ve now seen how the various components of Visual Studio 2012 work together to build an application. The following list outlines the typical process of creating a solution:
In subsequent chapters, you’ll learn how to customize the IDE to more closely fit your own working style, and how Visual Studio 2012 takes a lot of the guesswork out of the application development process. You’ll also see a number of best practices for working with Visual Studio 2012 that you can reuse as a developer.
WHAT’S IN THIS CHAPTER?
Arranging files with the Solution Explorer
Adding projects, items, and references to your solution
Working with the Properties tool window
Include your own properties in the Properties tool window
In Chapter 1, “A Quick Tour,” you briefly saw and interacted with a number of the components that make up the Visual Studio 2012 IDE. Now you get an opportunity to work with three of the most commonly used tool windows: the Solution Explorer, the Toolbox, and Properties.
Throughout this and other chapters you see references to keyboard shortcuts, such as Ctrl+S. In these cases, we assume the use of the general development settings, as shown in Chapter 1. Other profiles may have different key combinations. And, as you will see in upcoming chapters, you can use the Quick Launch area to get to commands regardless of the development settings that you use.
Whenever you create or open an application, or for that matter just a single file, Visual Studio 2012 uses the concept of a solution to tie everything together. Typically, a solution is made up of one or more projects, each of which can have multiple items associated with it. In the past these items were typically just files, but increasingly projects are made up of items that may consist of multiple files, or in some cases no files at all. Chapter 6, “Solutions, Projects, and Items,” goes into more detail about projects, the structure of solutions, and how items are related.
The Solution Explorer tool window (Ctrl+Alt+L) provides a convenient visual representation of the solution, projects, and items, as shown in Figure 2-1. In this figure you can see three projects presented in a tree: a C# WPF application, a C# WCF service library, and a VB class library.
FIGURE 2-1
Each project has an icon associated with it that typically indicates the type of project and the language it is written in. There are some exceptions to this rule: Some projects, such as SQL Server or Modeling projects, aren’t tied to a specific language.
One node is particularly noticeable because the font is boldfaced. This indicates that this project is the startup project — in other words, the project that is launched when you select Debug ⇒ Start Debugging or press F5. To change the startup project, right-click the project you want to nominate and select Set as StartUp Project. You can also nominate multiple projects as startup projects via the Solution Properties dialog, which you can reach by selecting Properties from the right-click menu of the Solution node.
The toolbar across the top of the Solution Explorer gives access to a number of different functions related to the solution, from the ability to collapse all the files in the tree to creating a new instance of the Solution Explorer. For example, the Show All Files button (see Figure 2-2) expands the solution listing to display the additional files and folders.
FIGURE 2-2
In this expanded view you can see all the files and folders contained under the project structure. Unfortunately, if the Filesystem changes, the Solution Explorer does not automatically update to reflect these changes. Use the Refresh button to make sure you see the current list of files and folders.
The Solution Explorer toolbar is contextually aware, with different buttons displayed depending on the type of node selected. This is shown in Figure 2-2, where there are two folders that are not part of the project (as indicated by the faded icon color) and the remaining buttons from Figure 2-1 are not visible.
There is another, relatively unusual, mechanism for navigating through the projects and files in a solution. To the left of each item in the tree is an icon, which when clicked shows a different context menu. One of the changes that appear in Visual Studio 2012 is the addition of a new option in the context menu called Scope to This. When the Scope to This option is clicked, the contents of the Solution Explorer change so that the selected node in the solution becomes the top level of the tree view. Figure 2-3 shows the view when Scope to This has been clicked for the GettingStarted project.
FIGURE 2-3
Along with navigating down the solution using the Scope to This option, the Solution Explorer also allows for moving backward and forward through the navigation. At the top left of the Solution Explorer’s toolbar, there is a left arrow that you can use to navigate up the hierarchy. So if that arrow were clicked, the full solution would be displayed, as shown in Figure 2-2. And there is also a right-facing arrow that, when clicked, navigates forward into the scoped view.
New to Visual Studio 2012, the expanded view also shows the properties and methods for a given class. When you click the icon to the left of a code file, the properties and methods become visible. The context menus have also changed to reflect the selected item. When you right-click a class, the context menu includes Base Types, Derived Types, and Is Used By options. These options change the scope of the Solution Explorer to the base class, the derived classes, and the classes used by the selected class, respectively.
As you continue navigating into the properties and methods, the context menu includes Calls, Is Called By, and Is Used By. These options scope the Solution Explorer to the classes that call this class, classes that are called by this class, and classes that are used by this class, respectively.
One of the more interesting features of Visual Studio 2012 is the file preview capability of Solution Explorer. One of the buttons at the top of the Solution Explorer is Preview Selected Items (shown in Figure 2-4). When it has been selected, as you navigate through the files in the Solution Explorer (to “navigate,” the file must be selected either with the mouse or by using the cursor), the file appears on the Preview tab (Figure 2-4).
FIGURE 2-4
At this moment, the file has not been modified but is simply open to look at. You are free to navigate through the file as you would any other file. However, when you navigate to another file in the Solution Explorer, the Preview tab is replaced with the new file. In other words, it is no longer required to have a proliferation of tabs to view the contents of various files in your solution.
When you decide to stop previewing the file, it automatically moves to the tabs on the left side of your editor window. You make the choice to stop previewing either by editing the file directly (by typing, for example) or by selecting the Open option from the drop-down list on the right of the Preview tab.
In addition to providing a convenient way to manage projects and items, the Solution Explorer has a dynamic context menu that gives you quick access to some of the most common tasks, such as building the solution or individual projects, accessing the build configuration manager, and opening files. Figure 2-5 shows how the context menu varies depending on which item is selected in the Solution Explorer.
FIGURE 2-5
The first items in the left and center menus relate to building either the entire solution or the selected project. In most cases, selecting Build is the most efficient option, because it only builds projects where one or more of the contained files have changed. However, in some cases you may need to force a Rebuild, which builds all dependent projects regardless of their states. If you just want to remove all the additional files that are created during the build process, you can invoke Clean. This option can be useful if you want to package your solution to e-mail it to someone — you wouldn’t want to include all the temporary or output files that are created by the build.
For most items in the Solution Explorer, the first section of the context menu is similar to the right menu in Figure 2-5: The default Open and Open With items allow you to determine how the item will be opened. This is of particular use when you work with XML resource files. Visual Studio 2012 opens this file type using the built-in resource editor, but this prevents you from making certain changes and doesn’t support all data types you might want to include. (Chapter 39, “Resource Files,” goes into how you can use your own data types in resource files.) By using the Open With menu item, you can use the XML Editor instead.
The most common activities carried out in the Solution Explorer are the addition, removal, and renaming of projects and items. To add a new project to an existing solution, select Add ⇒ New Project from the context menu off the Solution node. This invokes the dialog in Figure 2-6, which has undergone a few minor changes since earlier versions of Visual Studio. Project templates can now be sorted and searched. The pane on the right side displays information about the selected project, such as the type of project and its description. (Chapter 15, “Project and Item Templates,” covers creating your own Project and Item templates, including setting these properties.)
FIGURE 2-6
In the Installed templates hierarchy on the left side of the Add New Project dialog, the templates are primarily arranged by language, and then by technology. The templates include Office project types, enabling you to build both application- and document-level add-ins for most of the Office products. Though the Office add-ins still use Visual Studio Tools for Office (VSTO), this is built into Visual Studio 2012 instead of being an additional installation. Chapter 19, “Office Business Applications,” shows how you can use these project types to build add-ins for the core Office applications. There are also tabs for Recent templates and Online templates. The Online templates can be sorted and searched in the same way as your Installed templates; although the sort criteria has been extended to include creation date, ratings, and downloaded frequency.
The other thing you will notice in this dialog is the ability to select different framework versions. If you have existing projects that you don’t want to have to migrate forward to a more recent version of the .NET Framework, you can still immediately take advantage of the current features, such as improved IntelliSense. The alternative would have been to have both Visual Studio 2012 and a previous version installed to build projects for earlier framework versions. The framework selection is also included in the search criteria, limiting the list of available project templates to those that are compatible with the selected .NET Framework version.
One of the worst and most poorly understood features in Visual Studio is the concept of a Web Site project. This is distinct from a Web Application project, which can be added via the aforementioned Add New Project dialog. To add a Web Site project you need to select Add ⇒ Web Site from the context menu off the Solution node. This displays a dialog similar to the one shown in Figure 2-7, where you can select the type of web project to be created. In most cases, this simply determines the type of default item that is to be created in the project.
FIGURE 2-7
When you have a project or two, you need to start adding items. You do this via the Add context menu item off the project node in the Solution Explorer. The first submenu, New Item, launches the Add New Item dialog, as shown in Figure 2-8.
FIGURE 2-8
In addition to listing only those item templates that are relevant to the project you have selected, the Add New Item dialog enables you to search the installed templates, as well as go online to look for templates generated by third parties.
Returning to the Add context menu, you will notice a number of predefined shortcuts such as User Control and Class. The shortcuts that appear depend on the type of project to which the item is being added. These do little more than bypass the stage of locating the appropriate template within the Add New Item dialog. Regardless, the Add New Item dialog is still displayed because you need to assign a name to the item being created.
It is important to make the distinction that you are adding items rather than files to the project. Though a lot of the templates contain only a single file, some, like the Window or User Control, add multiple files to your project.
Each new software development technology that is released promises better reuse, but few can actually deliver on this promise. One way that Visual Studio 2012 supports reusable components is via the references for a project. If you expand out any project, you can observe a number of .NET Framework libraries, such as System and System.Core, which need to be referenced by a project to be built. Essentially, a reference enables the compiler to resolve type, property, field, and method names back to the assembly where they are defined. If you want to reuse a class from a third-party library, or even your own .NET assembly, you need to add a reference to it via the Add Reference context menu item on the project node of the Solution Explorer.
When you launch the Reference Manager dialog, as shown in Figure 2-9, Visual Studio 2012 interrogates the local computer, the Global Assembly Cache, and your solution to present a list of known libraries that can be referenced. This includes both .NET and COM references that are separated into different lists, as well as projects and recently used references. In earlier versions of Visual Studio this dialog was notoriously slow to load. Visual Studio 2010 saw an improvement, but because the list of .NET assemblies was lazy loaded after the dialog was displayed, the resulting user experience was not completely satisfactory. Visual Studio 2012 appears to have finally gotten it right. The dialog displays almost instantly, showing the assemblies that are part of the .NET Framework first.
FIGURE 2-9
As in other project-based development environments going back as far as the first versions of VB, you can add references to projects contained in your solution, rather than adding the compiled binary components. The advantage to this model is that it’s easier to debug into the referenced component and helps ensure you are running the latest version of all components, but for large solutions this may become unwieldy.
The other type of reference that the Solution Explorer caters to is service references. In earlier versions of Visual Studio, these references were referred to as Web references, but with the advent of the Windows Communication Foundation (WCF) there is now a more generic Add Service Reference menu item. This invokes the Add Service Reference dialog, which you can see in Figure 2-10. In this example the drop-down feature of the Discover button has been used to look for Services in Solution.
FIGURE 2-10
Unfortunately, this dialog is another case of Microsoft not understanding the usage pattern properly. Though the dialog itself is resizable, the status response message area is not, making it hard to read any errors generated. Luckily, if any errors are thrown while Visual Studio 2012 attempts to access the service information, a hyperlink is provided that opens the Add Service Reference Error dialog. This generally gives you enough information to resolve the problem.
In the lower left corner of Figure 2-10 is an Advanced button. The Service Reference Settings dialog that this launches enables you to customize which types are defined as part of the service reference. By default, all the types used by the service are re-created in the client application unless they are implemented in an assembly that is referenced by both the service and the application. The Data Type area of this dialog is used to change this behavior. There is also an Add Web Reference button in the lower left corner of the Service Reference Settings dialog, which enables you to add more traditional .NET Web service references. This might be important if you have some limitations or are trying to support intersystem operability. Adding services to your application is covered in more detail in Chapter 32, “Windows Communication Foundation (WCF).”
One of the major advantages over many other IDEs that Microsoft has offered developers is true drag-and-drop placement of elements during the design of both web and rich client applications. These elements are all available in the Toolbox (Ctrl+Alt+X), a tool window accessible via the View menu.
The Toolbox window contains all the available components for the currently active document being shown in the main workspace. These can be visual components, such as buttons and textboxes; invisible, service-oriented objects, such as timers and system event logs; or even designer elements, such as class and interface objects used in the Class Designer view.
Visual Studio 2012 presents the available components in groups rather than as one big mess of controls. This default grouping enables you to more easily locate the controls you need — for example, data-related components are in their own Data group.
By default, groups are presented in List view (see the left side of Figure 2-11). Each component is represented by its own icon and the name of the component. This differs from the very old way of displaying the available objects when the Toolbox was simply a stacked list of icons that left you guessing as to what some of the more obscure components were, as shown with the Common WPF Controls group on the right side of Figure 2-11. You can change the view of each control group individually — right-click anywhere within the group area and deselect the List View option in the context menu.
FIGURE 2-11
Regardless of how the components are presented, the way they are used in a program is usually the same: Click and drag the desired component onto the design surface of the active document, or double-click the component’s entry for Visual Studio to automatically add an instance. Visual components, such as buttons and textboxes, appear in the design area where they can be repositioned, resized, and otherwise adjusted via the property grid. Nonvisual components, such as the Timer control, appear as icons, with associated labels, in a nonvisual area below the design area, as shown in Figure 2-12.
FIGURE 2-12
At the top-left side of Figure 2-11 is a group called Reference Library Controls with a single component, MyControl. Reference_Library is actually the name of a class library that is defined in the same solution, and it contains the MyControl control. When you start to build your own components or controls, instead of your having to manually create a new tab and go through the process of adding each item to the Toolbox, Visual Studio 2012 automatically interrogates all the projects in your solution. If any components or controls are identified (essentially any class that implements System.ComponentModel.IComponent or System.Windows.FrameworkElement for WPF and Silverlight), a new tab is created for that project and the appropriate items are added with a default icon and class name (in this case MyControl), as you can see on the left in Figure 2-11. For components, this is the same icon that appears in the nonvisual part of the design area when you use the component.
To customize how your items appear in the Toolbox, you need to add a 16 × 16 pixel bitmap to the same project as your component or control. Next, select the newly inserted bitmap in the Solution Explorer and navigate to the Properties window. Make sure the Build property is set to Embedded Resource. All you now need to do is attribute your control with the ToolboxBitmap attribute:
VB
<ToolboxBitmap(GetType(MyControl), "MyControlIcon.bmp")> Public Class MyControl
C#
[ToolboxBitmap(typeof(MyControl), "MyControlIcon.bmp")] public class MyControl
This attribute uses the type reference for MyControl to locate the appropriate assembly from which to extract the MyControlIcon.bmp embedded resource. Other overloads of this attribute can use a file path as the only argument. In this case you don’t even need to add the bitmap to your project.
Unfortunately, you can’t customize the way the automatically generated items appear in the Toolbox. However, if you manually add an item to the Toolbox and select your components, you’ll see your custom icon. Alternatively, if you have a component and you drag it onto a form, you’ll see your icon appear in the nonvisual space on the designer.
It is also worth noting that customizing the Toolbox and designer experience for Windows Presentation Foundation (WPF) controls uses the notion of a Metadata store instead of attributes. This typically results in additional assemblies that can be used to tailor the design experience in both Visual Studio 2012 and Expression Blend.
Having Toolbox items in alphabetical order is a good default because it enables you to locate items that are unfamiliar. However, if you’re using only a handful of components and are frustrated by having to continuously scroll up and down, you can create your own groups of controls and move existing object types around.
Repositioning an individual component is easy. Locate it in the Toolbox, and click and drag it to the new location. When you’re happy with where it is, release the mouse button and the component moves to the new spot in the list. You can move it to a different group in the same way — just keep dragging the component up or down the Toolbox until you have located the right group. These actions work in both List and Icon views.
If you want to copy the component from one group to another, rather than move it, hold down the Ctrl key as you drag, and the process duplicates the control so that it appears in both groups.
Sometimes it’s nice to have your own group to host the controls and components you use the most. To create a new group in the Toolbox, right-click anywhere in the Toolbox area and select the Add Tab command. A new blank tab will be added to the bottom of the Toolbox with a prompt for you to name it. After you name the tab, you can then add components to it by following the steps described in this section.
When you first start Visual Studio 2012, the items within each group are arranged alphabetically. However, after moving items around, you may find that they’re in a bewildering state and you may decide that you simply need to start again. All you have to do is right-click anywhere within the group and choose the Sort Items Alphabetically command.
By default, controls are added to the Toolbox according to their class names. This means you end up with some names that are hard to understand, particularly if you add COM controls to your Toolbox. Visual Studio 2012 enables you to modify a component’s name to something more understandable.
To change the name of a component, right-click the component’s entry in the Toolbox and select the Rename Item command. An edit field appears inline in place of the original caption, enabling you to name it however you like, even with special characters.
If you’ve become even more confused, with components in unusual groups, and you have lost sight of where everything is, you can choose Reset Toolbox from the same right-click context menu. This restores all the groups in the Toolbox to their original states, with components sorted alphabetically and in the groups in which they started.
New to Visual Studio 2012 is the search capability that is found in the Toolbox. At the top of the Toolbox, there is a Search area. As you type characters into this area, the components in the Toolbox are filtered to match. The search is implemented so that it finds the characters that have been typed anyplace they exist in the name of the control. Because the search is performed across all the groups, this is a convenient way to locate controls, provided that you know all or part of the name. Figure 2-13 shows what the Toolbox might look like after “Tex” has been entered into the Search area.
FIGURE 2-13
Sometimes you’ll find that a particular component you need is not present in the lists displayed in the Toolbox. Most of the main .NET components are already present, but some are not. For example, the WebClient class component is not displayed in the Toolbox by default. Managed applications can also use COM components in their design. When added to the Toolbox, COM objects can be used in much the same way as regular .NET components, and if coded correctly you can program against them in precisely the same way using the Properties window and referring to their methods, properties, and events in code.
To add a component to your Toolbox layout, right-click anywhere within the group of components you want to add it to and select Choose Items. After a moment (this process can take a few seconds on a slower machine because the machine needs to interrogate the .NET cache to determine all the possible components you can choose from), you are presented with a list of .NET Framework components, as Figure 2-14 shows. One of the nice enhancements with Visual Studio 2012 is that there is now a progress bar indicating the assemblies that are being loaded. This is different from previous versions, where the only indication that this work was being done was the mouse cursor changing to its busy image.
FIGURE 2-14
Scroll through the list to locate the item you want to add to the Toolbox and check the corresponding check box. You can add multiple items at the same time by selecting each of them before clicking the OK button to apply your changes. At this time you can also remove items from the Toolbox by deselecting them from the list. Note that this removes the items from any groups to which they belong, not just from the group you are currently editing.
If you find it hard to locate the item you need, you can use the Filter box, which filters the list based on name, namespace, and assembly name. On rare occasions the item may not be listed at all. This can happen with nonstandard components, such as ones that you build yourself or that are not registered in the Global Assembly Cache (GAC). You can still add them by using the Browse button to locate the physical file on the computer. After you select and deselect the items you need, click the OK button to save them to the Toolbox layout.
COM components, WPF components, Silverlight components, Workflow components, and Activities components can be added in the same manner. Simply switch over to the relevant tab in the dialog window to view the list of available, properly registered COM components to add. Again, you can use the Browse button to locate controls that may not appear in the list.
One of the most frequently used tool windows built into Visual Studio 2012 is the Properties window (F4), as shown in Figure 2-15. The Properties window is made up of a property grid and is contextually aware, displaying only relevant properties of the currently selected item, whether that item is a node in the Solution Explorer or an element in the form design area. Each line represents a property with its name and corresponding value in two columns. The right side of Figure 2-15 shows the updated property grid for WPF applications, which includes a preview icon and search capabilities.
FIGURE 2-15
The Properties window is capable of grouping properties, or sorting them alphabetically — you can toggle this layout using the first two buttons at the top of the Properties window. It has built-in editors for a range of system types, such as colors, fonts, anchors, and docking, which are invoked when you click into the value column of the property to be changed. When a property is selected, as shown in the center of Figure 2-15, the property name is highlighted, and a description is presented in the lower region of the property grid.
In the Properties window, read-only properties are indicated in gray and you cannot modify their values. The value Say Hello!! for the Text property on the center of Figure 2-15 is boldfaced, which indicates that this is not the default value for this property. Similarly on the right side of Figure 2-15, the Text property has a filled-in black square to the right of the value, indicating the value has been specified. If you inspect the following code that is generated by the designer, you will notice that a line exists for each property that is boldfaced in the property grid — adding a line of code for every property on a control would significantly increase the time to render the form.
VB
C#
In addition to displaying properties for a selected item, the Properties window also provides a design experience for wiring up event handlers. The Properties window on the left side of Figure 2-16 illustrates the event view that is accessible via the lightning bolt button at the top of the Properties window. In this case, you can see that there is an event handler for the click event. To wire up another event, you can either select from a list of existing methods via a drop-down list in the value column, or you can double-click the value column. This creates a new event-handler method and wires it up to the event. If you use the first method you can notice that only methods that match the event signature are listed.
FIGURE 2-16
Certain components, such as the DataGridView, expose a number of commands, or shortcuts, which can be executed via the Properties window. On the right side of Figure 2-16 you can see two commands for the DataGridView: Edit Columns and Add Column. When you click either of these command links, you are presented with a dialog for performing that action. If the commands are not immediately visible, right-click the Properties window and select Commands from the context menu.
If the Properties window has only a small amount of screen real estate, it can be difficult to scroll through the list of properties. If you right-click in the property grid, you can uncheck the Command and Description options to hide these sections of the Properties window.
You have just seen how Visual Studio 2012 highlights properties that have changed by boldfacing the value. The question that you need to ask is, How does Visual Studio 2012 know what the default value is? The answer is that when the Properties window interrogates an object to determine what properties to display in the property grid, it looks for a number of design attributes. These attributes can be used to control which properties are displayed, the editor that is used to edit the value, and what the default value is. To show how you can use these attributes on your own components, start with adding a simple automatic property to your component:
VB
Public Property Description As String
C#
public string Description { get; set; }