Chapter 6. Solutions, Projects, and Items

WHAT'S IN THIS CHAPTER?

  • Creating and configuring solutions and projects

  • Controlling how an application is compiled, debugged, and deployed

  • Configuring the many project-related properties

  • Including resources and settings with an application

  • Enforcing good coding practices with the Code Analysis Tools

  • Modifying the configuration, packaging, and deployment options for web applications

Other than the simplest applications, such as Hello World, most applications require more than one source file. This raises a number of issues, such as how the files will be named, where they will be located, and whether they can be reused. Within Visual Studio 2010, the concept of a solution, containing a series of projects, made up of a series of items, is used to enable developers to track, manage, and work with their source files. The IDE has a number of built-in features that aim to simplify this process, while still allowing developers to get the most out of their applications. This chapter examines the structure of solutions and projects, looking at available project types and how they can be configured.

SOLUTION STRUCTURE

Whenever you're working within Visual Studio, you will have a solution open. When you're editing an ad hoc file, this will be a temporary solution that you can elect to discard when you have completed your work. However, the solution enables you to manage the files that you're currently working with, so in most cases saving the solution means that you can return to what you were doing at a later date without having to locate and reopen the files on which you were working.

Note

Solutions should be thought of as a container of related projects. The projects within a solution do not need to be of the same language or project type. For example, a single solution could contain an ASP.NET web application written in Visual Basic, an F# library, and a C# WPF application. The solution allows you to open all these projects together in the IDE and manage the build and deployment configuration for them as a whole.

The most common way to structure applications written within Visual Studio is to have a single solution containing a number of projects. Each project can then be made up of a series of both code files and folders. The main window in which you work with solutions and projects is the Solution Explorer, shown in Figure 6-1.

Figure 6-1

Figure 6-1. Figure 6-1

Within a project, folders are used to organize the source code and have no application meaning associated with them (with the exception of web applications, which can have specially named folders that have specific meaning in this context). Some developers use folder names that correspond to the namespace to which the classes belong. For example, if class Person is found within a folder called DataClasses in a project called FirstProject, the fully qualified name of the class could be FirstProject.DataClasses.Person.

Solution folders are a useful way to organize the projects in a large solution. Solution folders are visible only in the Solution Explorer — a physical folder is not created on the filesystem. Actions such as Build or Unload can be performed easily on all projects in a solution folder. Solution folders can also be collapsed or hidden so that you can work more easily in the Solution Explorer. Projects that are hidden are still built when you build the solution. Because solution folders do not map to a physical folder, they can be added, renamed, or deleted at any time without causing invalid file references or source control issues.

Note

Miscellaneous Files is a special solution folder that can be used to keep track of other files that have been opened in Visual Studio but are not part of any projects in the solution. The Miscellaneous Files solution folder is not visible by default. You can find the settings to enable it under Tools

Figure 6-1

There is a common misconception that projects necessarily correspond to .NET assemblies. Although this is generally true, it is possible for multiple projects to represent a single .NET assembly. However, this case is not supported by Visual Studio 2010, so this book assumes that a project will correspond to an assembly.

In Visual Studio 2010, although the format for the solution file has not changed, you cannot open a solution file that was created with Visual Studio 2010 with Visual Studio 2008. However, project files can be opened with both Visual Studio 2008 and Visual Studio 2010.

In addition to tracking which files are contained within an application, solution and project files can record other information, such as how a particular file should be compiled, project settings, resources, and much more. Visual Studio 2010 includes non-modal dialog for editing project properties, whereas solution properties still open in a separate window. As you might expect, the project properties are those properties pertaining only to the project in question, such as assembly information and references, whereas solution properties determine the overall build configurations for the application.

SOLUTION FILE FORMAT

Visual Studio 2010 actually creates two files for a solution, with extensions .suo and .sln (solution file). The first of these is a rather uninteresting binary file, and hence difficult to edit. It contains user-specific information — for example, which files were open when the solution was last closed and the location of breakpoints. This file is marked as hidden, so it won't appear in the solution folder using Windows Explorer unless you have enabled the option to show hidden files.

Warning

Occasionally the .suo file becomes corrupted and causes unexpected behavior when building and editing applications. If Visual Studio becomes unstable for a particular solution, you should exit and delete the .suo file. It will be re-created by Visual Studio the next time the solution is opened.

The .sln solution file contains information about the solution, such as the list of projects, build configurations, and other settings that are not project-specific. Unlike many files used by Visual Studio 2010, the solution file is not an XML document. Instead it stores information in blocks, as shown in the following example solution file:

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 10
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "FirstProject",
    "FirstProjectFirstProject.vbproj", "{D4FAF2DD-A26C-444A-9FEE-2788B5F5FDD2}"
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
         Debug|Any CPU = Debug|Any CPU
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
     {D4FAF2DD-A26C-444A-9FEE-2788B5F5FDD2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
     {D4FAF2DD-A26C-444A-9FEE-2788B5F5FDD2}.Debug|Any CPU.Build.0 = Debug|Any CPU
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
EndGlobal

In this example, the solution consists of a single project, FirstProject, and a Global section outlining settings that apply to the solution. For instance, the solution itself will be visible in the Solution Explorer because the HideSolutionNode setting is FALSE. If you were to change this value to TRUE, the solution name would not be displayed in Visual Studio.

Note

As long as a solution consists of projects that do not target the .NET Framework version 4.0, you can open the solution with Visual Studio 2008 by performing a quick edit to the .sln file. Simply replace the first two lines of the file with the following, and the solution will open with no errors:

Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008

SOLUTION PROPERTIES

You can reach the solution Properties dialog by right-clicking the Solution node in the Solution Explorer and selecting Properties. This dialog contains two nodes to partition Common and Configuration properties, as shown in Figure 6-2.

Figure 6-2

Figure 6-2. Figure 6-2

The following sections describe the Common and Configuration properties nodes in more detail.

Common Properties

You have three options when defining the Startup Project for an application, and they're somewhat self-explanatory. Selecting Current Selection starts the project that has current focus in the Solution Explorer. Single Startup ensures that the same project starts up each time. This is the default selection, because most applications have only a single startup project. The last option, Multiple Startup Projects, allows for multiple projects to be started in a particular order. This can be useful if you have a client/server application specified in a single solution and you want them both to be running. When running multiple projects, it is also relevant to control the order in which they start up. Use the up and down arrows next to the project list to control the order in which projects are started.

The Project Dependencies section is used to indicate other projects on which a specific project is dependent. For the most part, Visual Studio will manage this for you as you add and remove project references for a given project. However, sometimes you may want to create dependencies between projects to ensure that they are built in the correct order. Visual Studio uses its list of dependencies to determine the order in which projects should be built. This window prevents you from inadvertently adding circular references and from removing necessary project dependencies.

In the Debug Source Files section, you can provide a list of directories through which Visual Studio can search for source files when debugging. This is the default list that is searched before the Find Source dialog is displayed. You can also list source files that Visual Studio should not try to locate. If you click Cancel when prompted to locate a source file, the file will be added to this list.

The Code Analysis Settings section is available only in the Visual Studio Team Suite editions. This allows you to select the static code analysis rule set that will be run for each project. Code Analysis is discussed in more detail later in the chapter.

Configuration Properties

Both projects and solutions have build configurations associated with them that determine which items are built and how. It can be somewhat confusing because there is actually no correlation between a project configuration, which determines how things are built, and a solution configuration, which determines which projects are built, other than they might have the same name. A new solution will define both Debug and Release (solution) configurations, which correspond to building all projects within the solution in Debug or Release (project) configurations.

For example, a new solution configuration called Test can be created, which consists of two projects: MyClassLibrary and MyClassLibraryTest. When you build your application in Test configuration, you want MyClassLibrary to be built in Release mode so you're testing as close to what you would release as possible. However, to be able to step through your test code, you want to build the test project in Debug mode.

When you build in Release mode, you don't want the Test solution to be built or deployed with your application. In this case, you can specify in the Test solution configuration that you want the MyClassLibrary project to be built in Release mode, and that the MyClassLibraryTest project should not be built.

Note

You can switch between configurations easily via the Configuration drop-down on the standard toolbar. However, it is not as easy to switch between platforms, because the Platform drop-down is not on any of the toolbars. To make this available, select View

Configuration Properties

You will notice that when the Configuration Properties node is selected from the Solution Properties dialog as shown in Figure 6-2, the Configuration and Platform drop-down boxes are enabled. The Configuration drop-down contains each of the available solution configurations (Debug and Release by default), Active, and All. Similarly, the Platform drop-down contains each of the available platforms. Whenever these drop-downs appear and are enabled, you can specify the settings on that page on a per-configuration and/or per-platform basis. You can also use the Configuration Manager button to add additional solution configurations and/or platforms.

When adding additional solution configurations, there is an option (checked by default) to create corresponding project configurations for existing projects (projects will be set to build with this configuration by default for this new solution configuration), and an option to base the new configuration on an existing configuration. If the Create Project Configurations option is checked and the new configuration is based on an existing configuration, the new project configurations will copy the project configurations specified for the existing configuration.

The options available for creating new platform configurations are limited by the types of CPU available: Itanium, x86, and x64. Again, the new platform configuration can be based on existing configurations, and the option to create project platform configurations is also available.

The other thing you can specify in the solution configuration file is the type of CPU for which you are building. This is particularly relevant if you want to deploy to 64-bit architecture machines.

You can reach all these solution settings directly from the right-click context menu from the Solution node in the Solution Explorer window. Whereas the Set Startup Projects menu item opens the solution configuration window, the Configuration Manager, Project Dependencies, and Project Build Order items open the Configuration Manager and Project Dependencies window. The Project Dependencies and Project Build Order menu items will be visible only if you have more than one project in your solution.

Figure 6-3

Figure 6-3. Figure 6-3

When the Project Build Order item is selected, this opens the Project Dependencies window and lists the build order, as shown in Figure 6-3. This tab reveals the order in which projects will be built, according to the dependencies. This can be useful if you are maintaining references to project binary assemblies rather than project references, and it can be used to double-check that projects are being built in the correct order.

PROJECT TYPES

Within Visual Studio, the projects for Visual Basic and C# are broadly classified into different categories. With the exception of Web Site projects, which are discussed separately later in this chapter, each project contains a project file (.vbproj or .csproj) that conforms to the MSBuild schema. Selecting a project template creates a new project, of a specific project type, and populates it with initial classes and settings. Following are some of the more common categories of projects as they are grouped under Visual Studio:

  • Windows: The Windows project category is the broadest category and includes most of the common project types that run on end-user operating systems. This includes the Windows Forms executable projects, Console application projects, and Windows Presentation Foundation (WPF) applications. These project types create an executable (.exe) assembly that is executed directly by an end user. The Windows category also includes several types of library assemblies that can easily be referenced by other projects. These include both class libraries and control libraries for Windows Forms and WPF applications. A class library reuses the familiar DLL extension. The Windows Service project type can also be found in this category.

  • Web: The Web category includes the project types that run under ASP.NET. This includes ASP.NET web applications, XML web services, and control libraries for use in web applications and rich AJAX-enabled web applications.

  • Office: As its name suggests, the Office category creates managed code add-ins for Microsoft Office products, such as Outlook, Word, or Excel. These project types use Visual Studio Tools for Office (VSTO), and are capable of creating add-ins for most products in both the Office 2003 and Office 2007 product suite.

  • SharePoint: Another self-describing category, this contains projects that target Windows SharePoint Services, such as SharePoint Workflows or Team Sites.

  • Database: The Database category contains a project type for creating code that can be used with SQL Server. This includes stored procedures, user-defined types and functions, triggers, and custom aggregate functions.

  • Reporting: This category includes a project type that is ideal for quickly generating complex reports against a data source.

  • Silverlight: This contains project types for creating Silverlight Applications or Class Library projects.

  • Test: The Test category includes a project type for projects that contain tests using the MSTest unit testing framework.

  • WCF: This contains a number of project types for creating applications that provide Windows Communication Foundation (WCF) services.

  • Workflow: This contains a number of project types for sequential and state machine workflow libraries and applications.

The New Project dialog box in Visual Studio 2010, shown in Figure 6-4, allows you to browse and create any of these project types. The target .NET Framework version is listed in a drop-down selector in the top right-hand corner of this dialog box. If a project type is not supported by the selected .NET Framework version, such as a WPF application under .NET Framework 2.0, that project type will not be displayed.

Figure 6-4

Figure 6-4. Figure 6-4

PROJECT FILES FORMAT

The project files (.csproj, .vbproj, or .fsproj) are text files in an XML document format that conforms to the MSBuild schema. The XML schema files for the latest version of MSBuild are installed with the .NET Framework, by default in C:WINDOWSMicrosoft.NETFrameworkv4.0.20506MSBuildMicrosoft.Build.Core.xsd.

Note

To view the project file in XML format, right-click the project and select Unload. Then right-click the project again and select Edit <project name>. This will display the project file in the XML editor, complete with IntelliSense.

The project file stores the build and configuration settings that have been specified for the project and details about all the files that are included in the project. In some cases, a user-specific project file is also created (.csproj.user or .vbproj.user), which stores user preferences such as startup and debugging options. The .user file is also an XML file that conforms to the MSBuild schema.

PROJECT PROPERTIES

You can reach the project properties by either right-clicking the Project node in Solution Explorer and then selecting Properties, or by double-clicking My Project (Properties in C#) just under the Project node. In contrast to solution properties, the project properties do not display in a modal dialog. Instead they appear as an additional tab alongside your code files. This was done in part to make it easier to navigate between code files and project properties, but it also makes it possible to open project properties of multiple projects at the same time. Figure 6-5 illustrates the project settings for a Visual Basic Windows Forms project. This section walks you through the vertical tabs on the project editor for both Visual Basic and C# projects.

Figure 6-5

Figure 6-5. Figure 6-5

The project properties editor contains a series of vertical tabs that group the properties. As changes are made to properties in the tabs, a star is added to the corresponding vertical tab. This functionality is limited, however, because it does not indicate which fields within the tab have been modified.

Application

The Application tab, visible in Figure 6-5 for a Visual Basic Windows Forms project, enables the developer to set the information about the assembly that will be created when the project is compiled. These include attributes such as the output type (that is, Windows or Console Application, Class Library, Windows Service, or a Web Control Library), application icon, and startup object. The Application tab for C# applications, shown in Figure 6-6, has a different format, and provides options such as the ability to select the target .NET Framework version.

Note

To change the .NET Framework version on a Visual Basic project, use the Advanced Compile Options on the Compile tab.

Figure 6-6

Figure 6-6. Figure 6-6

Assembly Information

Attributes that previously had to be configured by hand in the AssemblyInfo file contained in the project can also be set via the Assembly Information button. This information is important, because it shows up when an application is installed and when the properties of a file are viewed in Windows Explorer. Figure 6-7 (left) shows the assembly information for a sample application and Figure 6-7 (right) shows the properties of the compiled executable.

Figure 6-7

Figure 6-7. Figure 6-7

Each of the properties set in the Assembly Information dialog is represented by an attribute that is applied to the assembly. This means that the assembly can be queried in code to retrieve this information. In Visual Basic, the My.Application.Info namespace provides an easy way to retrieve this information.

User Account Control Settings

Visual Studio 2010 provides support for developing applications that work with User Account Control (UAC) under Windows Vista and Windows 7. This involves generating an assembly manifest file, which is an XML file that notifies the operating system if an application requires administrative privileges on startup. In Visual Basic applications, the View Windows Settings button on the Application tab can be used to generate and add an assembly manifest file for UAC to your application. The following code shows the default manifest file that is generated by Visual Studio.

<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"
       xmlns:asmv1="urn:schemas-microsoft-com:asm.v1"
       xmlns:asmv2="urn:schemas-microsoft-com:asm.v2"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC Manifest Options
           If you want to change the Windows User Account Control level replace the
           requestedExecutionLevel node with one of the following.

        <requestedExecutionLevel  level="asInvoker" />
        <requestedExecutionLevel  level="requireAdministrator" />
        <requestedExecutionLevel  level="highestAvailable" />

           If you want to utilize File and Registry Virtualization for backward
           compatibility then delete the requestedExecutionLevel node.
        -->
        <requestedExecutionLevel level="asInvoker" />
      </requestedPrivileges>
      <applicationRequestMinimum>
        <defaultAssemblyRequest permissionSetReference="Custom" />
        <PermissionSet ID="Custom" SameSite="site" />
      </applicationRequestMinimum>
    </security>
  </trustInfo>
</asmv1:assembly>

If the UAC-requested execution level is changed from the default asInvoker to require Administrator, Windows will present a UAC prompt when the application is launched. If you have UAC enabled, Visual Studio 2010 will also prompt to restart in administrator mode if an application requiring admin rights is started in Debug mode. Figure 6-8 shows the prompt that is shown on Windows allowing you to restart Visual Studio in administrator mode.

If you agree to the restart, Visual Studio will not only restart with administrative privileges, it will also reopen your solution including all files you had opened. It will even remember the last cursor position.

Figure 6-8

Figure 6-8. Figure 6-8

Application Framework (Visual Basic Only)

Additional application settings are available for Visual Basic Windows Forms projects because they can use the Application Framework that is exclusive to Visual Basic. This extends the standard event model to provide a series of application events and settings that control the behavior of the application. You can enable the Application Framework by checking the Enable Application Framework checkbox. The following three checkboxes control the behavior of the Application Framework:

  • Enable XP Visual Styles: XP visual styles are a feature that significantly improves the look and feel of applications running on Windows XP or later, because it provides a much smoother interface through the use of rounded buttons and controls that dynamically change color as the mouse passes over them. Visual Basic applications enable XP styles by default and can be disabled from the Project Settings dialog, or controlled from within code through the EnableVisualStyles method on the Application class.

  • Make Single Instance Application: Most applications support multiple instances running concurrently. However, an application opened more than two or three times may be run only once, with successive executions simply invoking the original application. Such an application could be a document editor, whereby successive executions simply open a different document. This functionality can be easily added by marking the application as a single instance.

  • Save My.Settings on Shutdown: Selecting the Save My.Settings on Shutdown option ensures that any changes made to user-scoped settings will be preserved, saving the settings provided prior to the application shutting down.

This section also allows you to select an authentication mode for the application. By default this is set to Windows, which uses the currently logged-on user. Selecting Application-defined allows you to use a custom authentication module.

You can also identify a form to be used as a splash screen when the application is first launched, and specify the shutdown behavior of the application.

Compile (Visual Basic Only)

The Compile section of the project settings, as shown in Figure 6-9, enables the developer to control how and where the project is built. For example, the output path can be modified so that it points to an alternative location. This might be important if the output is to be used elsewhere in the build process.

Figure 6-9

Figure 6-9. Figure 6-9

The Configuration drop-down selector at the top of the tab page allows different build settings for the Debug and Release build configuration.

If your dialog is missing the Configuration drop-down selector, you need to check the Show Advanced Build Configurations property in the Projects and Solutions node of the Options window, accessible from the Tools menu. Unfortunately, this property is not checked for some of the setting profiles — for example, the Visual Basic Developer profile.

Some Visual Basic–specific properties can be configured in the Compile pane. Option Explicit determines whether variables that are used in code have to be explicitly defined. Option Strict forces the type of variables to be defined, rather than it being late-bound. Option Compare determines whether strings are compared using binary or text comparison operators. Option Infer specifies whether to allow local type inference in variable declarations or whether the type must be explicitly stated.

Note

All four of these compile options can be controlled at either the Project or File-level. File-level compiler options will override the Project-level options.

The Compile pane also defines a number of different compiler options that can be adjusted to improve the reliability of your code. For example, unused variables may only warrant a warning, whereas a path that doesn't return a value is more serious and should generate a build error. It is possible either to disable all these warnings or treat all of them as errors.

Visual Basic developers also have the capability to generate XML documentation. Of course, because the documentation takes time to generate, it is recommended that you disable this option for debug builds. This will speed up the debugging cycle; however, when turned off warnings will not be given for missing XML documentation.

The last element of the Compile pane is the Build Events button. Click this button to view commands that can be executed prior to and after the build. Because not all builds are successful, the execution of the post-build event can depend on a successful build. C# projects have a separate Build Events tab in the project properties pages for configuring pre- and post-build events.

Build (C# and F# Only)

The Build tab, shown in Figure 6-10, is the C# equivalent of the Visual Basic Compile tab. This tab enables the developer to specify the project's build configuration settings. For example, the Optimize code setting can be enabled, which results in assemblies that are smaller, faster, and more efficient. However, these optimizations typically increase the build time, and as such are not recommended for the Debug build.

Figure 6-10

Figure 6-10. Figure 6-10

On the Build tab, the DEBUG and TRACE compilation constants can be enabled. Alternatively, you can easily define your own constants by specifying them in the Conditional compilation symbols textbox. The value of these constants can be queried from code at compile-time. For example, the DEBUG constant can be queried as follows:

C#
#if(DEBUG)
    MessageBox.Show("The debug constant is defined");
#endif
VB
#If DEBUG Then
    MessageBox.Show("The debug constant is defined")
#End If

The compilation constants are defined on the Advanced Compiler Settings dialog, which can be displayed by clicking the Advanced Compile Options... button on the Compile tab.

The Configuration drop-down selector at the top of the tab page allows different build settings for the Debug and Release build configuration. You can find more information on the Build options in Chapter 45.

Build Events (C# and F# Only)

The Build Events tab allows you to perform additional actions before or after the build process. In Figure 6-11, you can see a post-build event that executes the FXCop Static Code Analysis tool after every successful build.

Figure 6-11

Figure 6-11. Figure 6-11

You can use environment variables such as ProgramFiles in your command lines by enclosing them with the percent character. A number of macros are also available, such as ProjectPath. These macros are listed on the Edit Pre-build and Edit Post-build dialog box.

Debug

The Debug tab, shown in Figure 6-12, determines how the application will be executed when run from within Visual Studio 2010. This tab is not visible for web applications — instead the Web tab is used to configure similar options.

Figure 6-12

Figure 6-12. Figure 6-12

Start Action

When a project is set to start up, this set of radio buttons controls what actually happens when the application is run. Initially, this is set to start the project, which will call the Startup object specified on the Application tab. The other options are to either run an executable or launch a specific web site.

Start Options

The options that can be specified when running an application are additional command-line arguments (generally used in conjunction with an executable start action) and the initial working directory. You can also specify to start the application on a remote computer. Of course, this is possible only when debugging is enabled on a remote machine.

Enable Debuggers

Debugging can be extended to include unmanaged code and SQL Server. The Visual Studio hosting process can also be enabled here. This process has a number of benefits associated with the performance and functionality of the debugger. The benefits fall into three categories. First, the hosting process acts as a background host for the application you are debugging. In order to debug a managed application, various administrative tasks must be performed, such as creating an AppDomain and associating the debugger, which take time. With the hosting process enabled, these tasks are handled in the background, resulting in a much quicker load time during debugging.

Second, in Visual Studio 2010, it is quite easy to create, debug, and deploy applications that run under partial trust. The hosting process is an important tool in this process because it gives you the ability to run and debug an application in partial trust. Without this process, the application would run in full trust mode, preventing you from debugging the application in partial trust mode.

The last benefit that the hosting process provides is design-time evaluation of expressions. This is in effect an optical illusion, because the hosting process is actually running in the background. However, using the Immediate window as you're writing your code means that you can easily evaluate expressions, call methods, and even hit breakpoints without running up the entire application.

References (Visual Basic Only)

The References tab enables the developer to reference classes in other .NET assemblies, projects, and native DLLs. Once the project or DLL has been added to the references list, a class can be accessed either by its full name, including namespace, or the namespace can be imported into a code file so the class can be referenced by just the class name. Figure 6-13 shows the References tab for a project that has a reference to a number of framework assemblies.

Figure 6-13

Figure 6-13. Figure 6-13

One of the features of this tab for Visual Basic developers is the Unused References button, which performs a search to determine which references can be removed. It is also possible to add a reference path, which will include all assemblies in that location.

Once an assembly has been added to the reference list, any public class contained within that assembly can be referenced within the project. Where a class is embedded in a namespace (which might be a nested hierarchy), referencing a class requires the full class name. Both Visual Basic and C# provide a mechanism for importing namespaces so that classes can be referenced directly. The References section allows namespaces to be globally imported for all classes in the project, without them being explicitly imported within the class file.

References to external assemblies can either be File references or Project references. File references are direct references to an individual assembly. File references are created by using the Browse tab of the Add Reference dialog box. Project references are references to a project within the solution. All assemblies that are outputted by that project are dynamically added as references. Project references are created by using the Project tab of the Add Reference dialog box.

Warning

You should generally not add a File reference to a project that exists in the same solution. If a project requires a reference to another project in that solution, a Project reference should be used.

The advantage of a Project reference is that it creates a dependency between the projects in the build system. The dependent project will be built if it has changed since the last time the referencing project was built. A File reference doesn't create a build dependency, so it's possible to build the referencing project without building the dependent project. However, this can result in problems with the referencing project expecting a different version from what is included in the output.

Resources

Project resources can be added and removed via the Resources tab, shown in Figure 6-14. In the example shown, four icons have been added to this application. Resources can be images, text, icons, files, or any other serializable class.

Figure 6-14

Figure 6-14. Figure 6-14

This interface makes working with resource files at design time very easy. Chapter 38 examines in more detail how resource files can be used to store application constants and internationalize your application.

Services

Client application services allow Windows-based applications to use the authentication, roles, and profile services that were introduced with Microsoft ASP.NET 2.0. The client services enable multiple web- and Windows-based applications to centralize user profiles and user-administration functionality.

Figure 6-15 shows the Services tab, which is used to configure client application services for Windows applications. When enabling the services, the URL of the ASP.NET service host must be specified for each service. This will be stored in the app.config file. The following client services are supported:

  • Authentication: This enables the user's identity to be verified using either the native Windows authentication, or a custom forms-based authentication that is provided by the application.

  • Roles: This obtains the roles an authenticated user has been assigned. This enables you to allow certain users access to different parts of the application. For example, additional administrative functions may be made available to admin users.

  • Web Settings: This stores per-user application settings on the server, which allows them to be shared across multiple computers and applications.

Figure 6-15

Figure 6-15. Figure 6-15

Client application services utilize a provider model for web services extensibility. The service providers include offline support that uses a local cache to ensure that it can still operate even when a network connection is not available.

Client application services are discussed further in Chapter 33.

Settings

Project settings can be of any type and simply reflect a name/value pair whose value can be retrieved at run time. Settings can be scoped to either the Application or the User, as shown in Figure 6-16. Settings are stored internally in the Settings.settings file and the app.config file. When the application is compiled this file is renamed according to the executable being generated — for example, SampleApplication.exe.config.

Figure 6-16

Figure 6-16. Figure 6-16

Application-scoped settings are read-only at run time, and can only be changed by manually editing the config file. User settings can be dynamically changed at run time, and may have a different value saved for each user who runs the application. The default values for User settings are stored in the app.config file, and the per-user settings are stored in a user.config file under the user's private data path.

Application and User settings are described in more detail in Chapter 36.

Reference Paths (C# and F# Only)

The Reference Paths tab, shown in Figure 6-17, is used to specify additional directories that are searched for referenced assemblies.

Figure 6-17

Figure 6-17. Figure 6-17

When an assembly reference has been added, Visual Studio resolves the reference by looking in the following directories in order:

  1. The project directory.

  2. Directories specified in this Reference Paths list.

  3. Directories displaying files in the Add Reference dialog box.

  4. The obj directory for the project. This is generally only relevant to COM interop assemblies.

Signing

Figure 6-18 shows the Signing tab, which provides developers with the capability to determine how assemblies are signed in preparation for deployment. An assembly can be signed by selecting a key file. A new key file can be created by selecting <New...> from the file selector drop-down.

Figure 6-18

Figure 6-18. Figure 6-18

The ClickOnce deployment model for applications enables an application to be published to a web site where a user can click once to download and install the application. Because this model is supposed to support deployment over the Internet, an organization must be able to sign the deployment package. The Signing tab provides an interface for specifying the certificate to use to sign the ClickOnce manifests.

Chapter 46 provides more detail on assembly signing and Chapter 48 discusses ClickOnce deployments.

My Extensions (Visual Basic Only)

The My Extensions tab, shown in Figure 6-19, allows you to add reference to an assembly that extends the Visual Basic My namespace, using the extension methods feature. Extension methods were initially introduced to enable LINQ to be shipped without requiring major changes to the base class library. They allow developers to add new methods to an existing class, without having to use inheritance to create a subclass or recompile the original type.

Figure 6-19

Figure 6-19. Figure 6-19

The My namespace was designed to provide simplified access to common library methods. For example, My.Application.Log provides methods to write an entry or exception to a log file using a single line of code. As such it is the ideal namespace to add custom classes and methods that provide useful utility functions, global state or configuration information, or a service that can be used by multiple applications.

Security

Applications deployed using the ClickOnce deployment model may be required to run under limited or partial trust. For example, if a low-privilege user selects a ClickOnce application from a web site across the Internet, the application will need to run with partial trust as defined by the Internet zone. This typically means that the application can't access the local filesystem, has limited networking ability, and can't access other local devices such as printers, databases, and computer ports.

The Security tab, illustrated in Figure 6-20, allows you to define the trust level that is required by your application to operate correctly.

Figure 6-20

Figure 6-20. Figure 6-20

Modifying the permission set that is required for a ClickOnce application may limit who can download, install, and operate the application. For the widest audience, specify that an application should run in partial trust mode with security set to the defaults for the Internet zone. Alternatively, specifying that an application requires full trust ensures that the application has full access to all local resources, but will necessarily limit the audience to local administrators.

Publish

The ClickOnce deployment model can be divided into two phases: initially publishing the application and subsequent updates, and the download and installation of both the original application and subsequent revisions. You can deploy an existing application using the ClickOnce model using the Publish tab, shown in Figure 6-21.

Figure 6-21

Figure 6-21. Figure 6-21

If the install mode for a ClickOnce application is set to be available offline when it is initially downloaded from the web site, it will be installed on the local computer. This will place the application in the Start menu and the Add/Remove Programs list. When the application is run and a connection to the original web site is available, the application will determine whether any updates are available. If there are updates, users will be prompted to determine whether they want the updates to be installed.

The ClickOnce deployment model is explained more thoroughly in Chapter 48.

Code Analysis (VSTS Premium and Ultimate Editions Only)

Most developers who have ever worked in a team have had to work with an agreed-upon set of coding standards. Organizations typically use an existing standard or create their own. Unfortunately, standards are useful only if they can be enforced, and the only way that this can be effectively done is using a tool. In the past this had to be done using an external utility, such as FXCop. The VSTS Premium and Ultimate Editions of Visual Studio 2010 have the capability to carry out static code analysis from within the IDE.

The Code Analysis tab, shown in Figure 6-22, can be used to enable code analysis as part of the build process. Because this can be quite a time-consuming process, it may be included only in release or test build configurations. Regardless of whether code analysis has been enabled for a project, it can be manually invoked from the Build menu.

Figure 6-22

Figure 6-22. Figure 6-22

Not all rules defined in the Code Analysis pane are suitable for all organizations or applications. This pane gives the developer control over which rules are applied, and whether they generate a warning or a build error. Deselecting the rule in the Rules column disables the rule. Double-clicking a cell in the Status column toggles what happens when a rule fails to be met between a warning and a build error.

FXCop is covered in Chapter 13 and the native Visual Studio Code Analysis tools are discussed further in Chapter 55.

WEB APPLICATION PROJECT PROPERTIES

Due to the unique requirements of web applications, four additional project property tabs are available to ASP.NET Web Application projects. These tabs control how web applications are run from Visual Studio as well as the packaging and deployment options.

Web

The Web tab, shown in Figure 6-23, controls how Web Application projects are launched when executed from within Visual Studio. Visual Studio ships with a built-in web server suitable for development purposes. The Web tab enables you to configure the port and virtual path that this runs under. You may also choose to enable NTLM authentication.

Note

The Edit and Continue option allows editing of code-behind and standalone class files during a debug session. Editing of the HTML in an .aspx or .ascx page is allowed regardless of this setting; however, editing inline code in an .aspx page or an .ascx file is never allowed.

Figure 6-23

Figure 6-23. Figure 6-23

The debugging options for web applications are explored in Chapter 42.

Silverlight Applications

The Silverlight Applications tab provides an easy way to provide a link to a Silverlight project and host it within an ASP.NET Web Application.

Figure 6-24

Figure 6-24. Figure 6-24

When you add a Silverlight application to a Web Application project, you can select an existing Silverlight project if one exists in the current solution, or create a new Silverlight project as shown in Figure 6-24. The dialog box allows you to select the location and language for the new project, as well as options for how the Silverlight application will be included in the current web application.

If you accept the defaults when you add a new Silverlight application, Visual Studio will create a reference to the new project and generate three files in the web application: a static HTML page, an ASP.NET web form, and a JavaScript file that contains logic for loading Silverlight applications and installing the run time if required.

Chapter 22 explores the development of Silverlight applications and the options for hosting them within an existing web application.

Package/Publish Web

Application deployment has always been a difficult challenge, especially when it comes to complex web applications. A typical web application comprises not only a large number of source files and assemblies, but also images, style sheets, and JavaScript files. To complicate matters further, it may be dependent on a specific configuration of the IIS web server.

Visual Studio 2010 simplifies this process by allowing you to package a Web Application project with all of the necessary files and settings contained in a single compressed (.zip) file. Figure 6-25 shows the packaging and deployment options that are available to an ASP.NET Web Application.

Figure 6-25

Figure 6-25. Figure 6-25

Further discussion on web application deployment is included in Chapter 49.

Package/Publish SQL

All but the simplest of web applications are backed by a database of some description. For ASP.NET Web applications this is typically a SQL Server database.

The Visual Studio 2010 web packaging and deployment functionality includes support for packaging one or more SQL Server databases. As illustrated in Figure 6-26, when you create a package you can specify a connection string for your source database and allow Visual Studio to create SQL scripts for the database schema only or schema and data. You can also provide custom SQL scripts to be executed either before or after the auto-generated script.

Figure 6-26

Figure 6-26. Figure 6-26

Chapter 49 explores the web application deployment options in more detail.

WEB SITE PROJECTS

The Web Site project functions quite differently from other project types. Web Site projects do not include a .csproj or .vbproj file, which means they have a number of limitations in terms of build options, project resources, and managing references. Instead, Web Site projects use the folder structure to define the contents of the project. All files within the folder structure are implicitly part of the project.

Web Site projects provide the advantage of dynamic compilation, which allows pages to be edited without rebuilding the entire site. The file can be saved and simply reloaded in the browser. As such they enable extremely short code and debug cycles. Microsoft first introduced Web Site projects with Visual Studio 2005; however, it was quickly inundated with customer feedback to reintroduce the Application Project model, which had been provided as an additional download. By the release of Service Pack 1, Web Application projects were back within Visual Studio as a native project type.

Note

Since Visual Studio 2005, an ongoing debate has been raging about which is -better — Web Site projects or Web Application projects. Unfortunately, there is no simple answer to this debate. Each has its own pros and cons, and the decision comes down to your requirements and your preferred development workflow.

You can find further discussion on Web Site and Web Application projects in Chapter 20.

SUMMARY

In this chapter you have seen how a solution and projects can be configured using the user interfaces provided within Visual Studio 2010. In particular, this chapter showed you how to do the following:

  • Create and configure solutions and projects.

  • Control how an application is compiled, debugged, and deployed.

  • Configure the many project-related properties.

  • Include resources and settings with an application.

  • Enforce good coding practices with the Code Analysis Tools.

  • Modify the configuration, packaging, and deployment options for web applications.

In subsequent chapters many of the topics, such as building and deploying projects and the use of resource files, are examined in more detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.119.81