Chapter 5
Creating and Building Projects

Key Skills & Concepts

Image Work with Projects and Solutions

Image Set Properties in the Properties Window

Image Reference and Use Class Libraries

Image Compile and Run Projects

Image Use the Class Designer

Projects and solutions are VS’s way of helping you organize your code for both development and deployment. For development, you have a hierarchical structure that is flexible and allows you to organize your code in a way that makes sense for you and your team. For deployment, you can build different project types that will result in executable or library files (often referred to as assemblies) that run your program when executed.

While reading this chapter, you’ll learn how to use solutions and projects. You’ll learn how to find settings and options for customizing projects, how to reference assemblies, and different options for compiling code. As an extra bonus, you’ll learn how the Class Designer allows you to obtain a high-level visualization of your code and perform some design work. We’ll begin with learning about solutions and projects.

Constructing Solutions and Projects

With VS, you can build applications that range in size and sophistication. At the most basic level, you can start a console project that contains one or more files with code, which is very simple. At higher levels of complexity, you can build enterprise-scale applications consisting of many projects of various types, organized to support large teams of developers working in unison.

VS uses a hierarchical model to help you organize your code and gives you flexibility in how a project is set up. Some features, such as solutions and projects, are well defined, but you have the freedom to add folders that help customize the arrangement of files to meet your needs.

Two organizing principles of solution and project organization will always be true: you will work with only one solution at a time and that solution will always have one or more projects. For simplicity, I’ll use the term “project,” but that still means that we have a project inside of a solution. Different project types have unique settings and options, but we’ll start by creating a Console application, which will reduce unnecessary detail and help focus on the common features of all project types.

Creating a New Project

As a shortcut, press CTRL-SHIFT-N to open the New Project window, shown in Figure 5-1. CTRL-N will only open a single file, which you can’t compile, so don’t forget the SHIFT key. Of course, you can always use the menu to created a new project.

Chapter 2 describes the features of the New Project window. The process is the same any time you create a new project. VS remembers your last project type, which could be helpful if you are creating multiple projects of the same type. Make sure you select Console Application as your project type.

The way you create and name VB and C# projects are different in that all of the decisions for C# projects are made at one time, but VB divides creation into initial project creation and then saves additional information when you save the project for the first time.

C# projects allow you to configure Name, Location, Solution, and Solution Name as shown in Figure 5-1. In C#, the Name field is the name of the project you are creating, and the Solution Name field is the name of the solution. While typing the project name,

Image

Figure 5-1 The New Project window

VS will update the Solution Name with the same name. In a multiproject solution, this might not make sense. So, first type the project name and then you can provide a name for the solution that is more appropriate. In Figure 5-1, you can see that the project is named ProjectDemo and the solution is named SolutionDemo. VS allows you to put spaces in the names. A consequence of this is that the default namespace for a project will use the project name with spaces translated to underlines; something to be aware of if your coding conventions don’t allow underlines in identifier names.

If you have a very simple project and want all project files in the same folder, uncheck Create Directory For Solution. However, most applications you build will have multiple projects and leaving this box checked makes more sense because it maintains consistency between folder and solution organization. In any case, when an additional project is added to your solution, VS will always put the new project into a separate subfolder.

If you check Add To Source Control, VS will open a window for you to configure source control. Source control is a repository for you to check code into. This is especially useful for teams where each developer can check in his or her code for a common repository of source code for this solution when you create the solution. Click OK to create the solution.

TIP

If you accidentally start a project type that you didn’t intend, select File I Close Solution and then delete the solution folders from the file system. VS will often put OS locks on files, so it’s important to close the solution so that you will be able to delete files. The VS Recent Projects list will have an entry with the name of the solution you just deleted, but you can click that entry and VS will recognize that the solution no longer exists, prompting you to remove the entry from the list. After that, you can start over again and use the same solution/project name you intended, but with the right project type.

Starting a new Console project in VB, you only need to provide a Name parameter, which is the name of the project to create. Once the project is created, the first time you create the project, you’ll receive a window that asks you for Name, Solution Name, Location, Create Directory, and Add To Source Control options that work the same as described for the previous C# example. You’ve accomplished the same task, regardless of language, but in different ways.

Navigating the Solution Explorer

VS creates a new project in the Solution Explorer window, shown in Figure 5-2. While other VS windows provide specialized views into specialized parts of an application, the Solution Explorer window is where you can find all of the artifacts of an application.

One of the first features of the project shown in Figure 5-2 is the hierarchical relationships. You will have only one solution. VB doesn’t show the solution file by default, but you can

Image

Figure 5-2 The Solution Explorer window

change this by selecting Tools | Options | Projects And Solutions and checking the box for Always Show Solution.

You can add multiple projects to a solution, as well as folders for organizing the projects. Right-click the solution name in the Solution Explorer and select Add | New Project, and you can add more projects. Add | Existing Project allows you to add a project that already exists to your opened solution. The reason this option exists is that while VS solutions associate one or more projects together as a solution unit, any single project could optionally be associated with other solutions. In other words, a single project could be shared with other solutions.

Select Add | New Solution Folder to add a folder to a solution. You can add a hierarchy of folders to a solution for organizing projects. One thing to remember about solution folders is that unlike creating folders inside a project that become physical file system folders, solution folders are logical and don’t create a physical folder in your file system. If you want your file system layout to match the Solution Explorer layout with solution folders, you must create the file system folders yourself. To avoid confusion, remember that it is possible for the physical location of projects to differ from the Solution Explorer layout.

Besides organizing projects, solution folders are also useful for associating specific artifacts with your project. While solution folders are not tied to physical file system folders, they are included with source control providers, such as Visual Source Safe and Team System. One potential use of a solution folder is to include a copy of an external class library that you’ve built your project with. This way, whenever other members of the team check the solution out of source control, they all are working with the same files and versions. Solution folders can also be used for any type of file, including project documentation or anything else that you want to keep organized in a single place.

Depending on project type, VS hides various files associated with a project. The Solution Explorer toolbar has a Show All Files button that will show these hidden files. If you have the solution selected, all you’ll see is the Add A New Solution Folder button, so you’ll need to select a project before the Show All Files button will display. An example of a hidden file is the bin folder hierarchy that contains the output of your project when you compile.

Examining Property Settings

Each project has associated settings that you can configure. When you first create a project, these settings are configured for common values for that project type. However, you can modify these settings to meet your needs. Each project has a logical folder named Properties, shown previously in Figure 5-2, which will open a property setting window when you double-click the Properties (My Project in VB) folder in a project, shown in Figure 5-3.

There are multiple tabs, each with related properties grouped to the subject of each tab. Depending on project type, you might see additional tabs, but some of the tabs are common

Image

Figure 5-3 The Project Properties window

to all projects. The following sections describe each of the features of the Application settings tab.

Assembly Name

VS projects create either *.dll or *.exe assemblies. The assembly name provides the filename for this project and defaults to the name of your project. From Figure 5-3, you can see that Assembly Name is set to ProjectDemo. Since this is a Console application, the output would be a *.exe. It follows that the filename would be ProjectDemo.exe. Had the project type been a Class Library, the filename would have been ProjectDemo.dll.

Default Namespace

The Default namespace (Root namespace in VB) setting determines what the namespace will be defined automatically as whenever you add a new code file to your project. It’s initially set to the name of your project. If you want the namespace of new files to be different, set the namespace here.

Target Framework

VS has .NET Framework multitargeting support, where you can work with any version of .NET between v2.0 and v4.0. Select the .NET version you need in the Target Framework combo box. VB includes this option on the Compile tab when clicking the Advanced Compile Options button. Remember to set the VB project from .NET Framework 4.0 Client Profile to .NET Framework 4.0 because later we’ll be referencing a class library that is set to .NET Framework 4.0 and the target frameworks must be compatible for one assembly to reference another.

Since you can have multiple versions of .NET on the same machine as VS 2010, you can switch freely between different projects that use different .NET versions. This is particularly useful if you’re a consultant working on different projects with different versions or if you’re providing maintenance support on older versions of a product while doing active development work in a different project using .NET 4.0.

Output Type

An Output type (Application type in VB) is the type of assembly created when you build your project. The three types of output are Windows Application, Console Application, and Class Library. You already know how to create a Console application, which produces a *.exe assembly. Later in this chapter, you’ll learn how to create a Class Library project, which produces a *.dll assembly. In Chapter 8, you’ll learn how to create a Windows Application project, which is a *.exe.

TIP

If you have a WPF project, its Output Type is set to Windows Application. If you switched the Output Type of a WPF application to Console Application, you would see the Console window appear also. This might be useful for some intermediate debugging where you could emit Console.WriteLine messages. Of course, VS provides excellent debugging tools, which you’ll learn about in Chapter 6, including an Output window, but this is just another option if you ever wanted it.

Startup Object

You could add multiple Main methods to a Console application or a WPF application, but only one Main method can be active at a time. The Startup object allows you to specify which class contains the Main method you want to use as the entry point to your application. One of the reasons you might want to do this is to start your application in different configurations, which might facilitate testing by allowing you to go straight to a part of the program without too much navigation.

Icon and Manifest

By clicking the ellipses button on the right of the icon drop-down list, you can browse to an icon file, *.ico, that will appear as your application icon.

TIP

VS ships with system icons that you can use in your own applications. Navigate to C:Program FilesMicrosoft Visual Studio 10.0Common7VS2010ImageLibrary1033 and you’ll see a Zip file named VS2010ImageLibrary. Your path might be different if you chose to install VS2010 somewhere other than the default. Unzip this VS2010ImageLibrary and you’ll see a plethora of resources with images, audio, animations, and icons that are common to Microsoft operating systems and applications.

The manifest allows you to specify Microsoft Windows User Access Control (UAC) settings or to support a form of deployment called Click-Once, where a WPF application can be deployed from a Web page and run locally on your desktop machine. The manifest describes the application and deployment features of your Click-Once application. Since these manifests are automatically generated when you publish a Click-Once application, you normally won’t ever manually build manifest files yourself; this is considered an advanced practice and includes knowledge beyond what a beginner’s guide would include.

In VB, there is a UAC Settings button that allows you to directly modify the app .manifest file. This is an advanced technique that requires knowledge of the operating system UAC settings.

If you select the Resources option, you can include a Win32 resources file, which you can then access through code in your application. This is another advanced scenario beyond the scope of this book.

Assembly Information

Clicking Assembly Information shows the window in Figure 5-4. This information is included in the assembly metadata when you build your project. Most of the information in this window is self-explanatory. Since assemblies can comprise multiple files, you are allowed to vary the assembly (all files) and this file’s assembly version numbers.

With .NET, you can have two-way communications with Component Object Model (COM) applications. You can enable this by allowing your assembly to have a Globally Unique Identifier (GUID) so that COM can find it, and check the COM visible box.

Leave the Neutral Language as None, unless you want the default locality to be something other than en-US, which is the locale for US English.

To see what these settings look like, press F6 to build the application, and then navigate to the location in the file system where you created the project. The location on my machine for this demo is C:VS2010Chapter05SolutionDemoProjectDemoinDebug, but yours could be different if you created your project in a different location. Regardless, you’ll find the ProjectDemo.exe file in the binDebug folder. Right-click ProjectDemo.exe, select Properties, and click the Details tab of the ProjectDemo Properties window, shown in Figure 5-5.

Image

Figure 5-4 Assembly Information

Image

Figure 5-5 File Properties window

As you can see in Figure 5-5, the Assembly Information from the project properties is included with the file. This is convenient for you (or an end user) to be able to open the file and read pertinent information, especially version information, to know you’re working with the correct assembly, for debugging, or just to know what is on your system.

Referencing Assemblies

All projects normally reference external assemblies. For example, System.dll is a .NET Framework assembly that contains all of the primitive .NET types and is normally included in every project. Each project type has a specific set of assemblies that appear in the References list. The assemblies that appear in this list are either required because of the type of project you are building or are optional and contain libraries that are commonly used for that type of project. You are free to remove assembly references if you like, but be aware that removing a reference to an assembly required for that project type is likely to result in your code not being able to compile.

Assembly references are added to a project to tell the compiler where to find the types it is using in an application. When your compiler runs, it will know what types you have in your code and looks through the set of referenced assemblies to find that type. Adding an assembly reference doesn’t add all of the code from the referenced assembly to your code; it just tells the compiler where to look.

NOTE

There is often confusion around the relationship between assembly references and namespaces. A namespace using statement [Imports in VB) allows your code to be written without fully qualifying type references for types in an assembly. However, the assembly reference is just a way to tell the compiler in which specific external assembly to look to find those types: two different purposes. This confusion is exacerbated by the fact that you get the same error message from the compiler when you either are missing an assembly reference or don’t have a using (Imports for VB) directive in your code for a namespace that a type resides in. Just remember to ensure that you have an assembly reference first and then add a using (Imports) directive at the top of your file.

Adding a .NET Assembly Reference

You can add references to your project by right-clicking the project and clicking Add Reference. You’ll see the Add Reference window, shown in Figure 5-6. On the .NET tab of this window, you’ll see a list of assemblies from the Global Assembly Cache

Image

Figure 5-6 The Add Reference window

(GAC), which is a shared repository of assemblies. Microsoft and third parties will place assemblies in the GAC to make it easier to share them by any programs.

The COM tab shows all of the COM applications currently registered on your computer. For example, if you wanted to communicate with Excel, you would click the COM tab and add a reference to the version of Microsoft Office Excel that you are working with. Adding a reference to a COM object causes VS to automatically generate a new assembly, called an Interop assembly, that has stub methods that make it easy for you to perform operations on that COM object. You would need to reference the documentation for the COM object/application to determine what operations are possible, but this is a very powerful way to work with legacy applications and Microsoft Office applications that expose a COM interface.

CAUTION

If you’re adding an assembly reference for a VB project, remember to open My Projects on ProjectDemo, go to the Compile tab, click the Advanced Compile Options button, and ensure that the Target Framework is set to .NET Framework 4.0 (not .NET Framework 4.0 Client Profile). The reason is that the class library project is automatically set to .NET Framework 4.0 and the target framework for both the referencing and referenced assemblies must be the same.

The Recent tab has a list of references that you’ve recently added to a project, which is a convenience based on the probability that if you added a reference to one project in a solution, you might want to quickly add that same reference to others. The Browse tab of the Add Reference window allows you to search the file system for a *.dll file to add as a reference. Just remember that if you are referencing a *.dll for a project in the same solution, it would be better to use the Project tab, which manages dependencies and ensures that your project is updated if the referenced project changes. File references can’t know if the external *.dll changed because the external *.dll is outside of your solution. In most cases, if you’re referencing an external *.dll, you don’t have the code, so a project reference won’t be possible. The next section explains more about project references.

NOTE

The New Projects window, CTRL-N, contains Office project types that can help you get started building Microsoft Office applications.

Managing Assembly References

Occasionally, you might want to remove an assembly reference because it isn’t necessary or because you accidentally added the wrong reference. In C#, you would open the References folder, select the reference to remove, and press DELETE. In VB, you would

Image

Figure 5-7 The VB My Project References tab

open the Properties window by double-clicking My Project, click the References tab, select the reference to delete, and click Remove. Figure 5-7 shows the VB References tab.

VB includes additional functionality on the References tab. For example, you can click Add to add a reference. You also click Unused References to remove references for assemblies that are not being used in your code. Clicking Reference Paths allows you to specify a folder that VS will look in to find assemblies you want to reference.

C# has a separate tab on the Properties window for managing Reference Paths. When VS looks for referenced assemblies, it will search the current project directory, then in the folders identified in Reference Paths, and then in folders for the list of assemblies specified by the Add References window.

Referencing Your Own Class Libraries

There are various reasons for creating your own code libraries. For example, you might have reusable code or want to keep your code organized into separate assemblies. To do this, you would create Class Library projects, and then reference those class library projects from other code. First, let’s create a Class Library project and then create a reference to the Class Library project from a Console application.

Within the SolutionDemo solution, we’ll create a new project for a class library. Right-click SolutionDemo and select Add | New Project. This time, select Class Library instead of Console Application and name it ClassLibraryDemo. Clicking OK will add a new Class Library Project to your SolutionDemo Solution. You will now have two projects in your solution.

To use the code in the ClassLibrary project, right-click the ProjectDemo project and select Add Reference. This time, select the Project tab, which will contain all of the projects that belong to the same solution. Select the ClassLibraryDemo project and click OK. You’ll see the reference to ClassLibraryDemo appear in the References folder in the ProjectDemo project.

TIP

Resetting References for Renamed Projects. You can rename any project by right-clicking the project and selecting Rename. However, that doesn’t change the physical folder name. If you want to change the physical folder name, close the solution (select File I Close Solution) and then change the project folder name. When you re-open the solution, Solution Explorer won’t be able to load the project. This is because the folder name for the project in the solution file hasn’t changed. To fix this, select the project in Solution Explorer and open the properties window. In the properties window, select the file path property and either type the newly changed path or click the ellipses button to navigate to the *.csproj file. Navigate back to Solution Explorer, right-click the project that didn’t load, and select Reload Project.

Now that you have a reference to a class library, you’ll want to write code that uses the objects in the class library, which you’ll learn about next.

Using Code in Class Libraries

To use class library code, you need to ensure you have a reference to the class library. If using C#, you can add a using directive, and in VB you can add an Imports directive, which allows you to use the types in the class library without fully qualifying them.

After referencing the class library assembly and ensuring namespaces are managed properly, you can use class library classes and instantiate these externally referenced objects and access or invoke the members as if they were part of the code in your own assembly. The .NET CLR will take care of making sure that your calls to the class library object work transparently behind the scenes. The preceding section showed you how to create the reference from one project to another, allowing the compiler to find the other assembly. This section will explain how to write the code that specifies which objects in the class library to use.

Assuming that you were building an educational application, you might have a class library that helped you keep track of students. To facilitate this scenario, you can rename the Class1.cs or Class1.vb file in the ClassLibraryDemo project to Student.cs or Student.vb.

If you’re using C# when you do this, VS will ask if you want to change the class filename from Class1 to Student. VB will make the class name change automatically, without asking. This is a convenient way to keep your classes and filenames in sync. It is common to create only one class per file. Listing 5-1 shows the new student file after renaming and adding code to make it functional.

Listing 5-1 Class library code

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLibraryDemo
{
    public class Student
    {
       public List<int> GetStudentGrades(string studentName)
       {
           return new List<int> { 80, 100, 95 };
       }
    }
}

VB:

Public Class Student
    Public Function GetStudentGrades(ByVal studenName As String) As
List(Of Integer)
         Dim intList As New List(Of Integer)
         intList.Add(80)
         intList.Add(100)
         intList.Add(95)
         Return intList
    End Function
End Class

The important parts of Listing 5-1, for the current discussion, is that Student is a class inside of the ClassLibraryDemo namespace. You’ll need to remember the namespace so that you can obtain a reference to a Student instance from the calling code. Listing 5-2 shows how. Remember that the VB namespace is implicitly set to whatever is defined as the namespace setting on the My Project page, which defaults to the project name.

Listing 5-2 Application code calling class library code

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ClassLibraryDemo;

namespace ProjectDemo
{
     class Program
     {
           static void Main(string[] args)
           {
               string studentName = "Joe";
               Student myStudent = new Student();
               List<int> grades = myStudent.GetStudentGrades(studentName);

               Console.WriteLine("Grades for {0}:", studentName);
               foreach (int grade in grades)
               {
                     Console.WriteLine(" - " + grade);
               }
               Console.ReadKey();
           }
     }
}

VB:

Imports ClassLibraryDemoVB

Module Module1

     Sub Main()
          Dim grades As List(Of Integer)
          Dim studentName As String = "Joe"
          Dim myStudent As New Student

          grades = myStudent.GetStudentGrades(studentName)

          Console.WriteLine("Grades for {0}:", studentName)
          For Each grade In grades
                 Console.WriteLine(" - " & grade)
          Next

          Console.ReadKey()
     End Sub

End Module

One item to draw your attention to in Listing 5-2 is the using directive (Imports in VB), specifying that you can use the types in the ClassLibraryDemo namespace without fully qualifying them. After that, you can see how Listing 5-2 creates instances of Student and myStudent and calls GetStudentGrades.

TIP

The call to Console.ReadKey in Listing 5-2 causes program execution to stop until the user presses a key on their keyboard. If Console.ReadKey was not present, the program would finish the Main method, which would close the application before you had the chance to see the output.

Next, you’ll want to compile the code to see if the syntax is good and then run the program to see if it operates properly. The next section explains how compiling and running works with VS.

Compiling Applications

You’ll find several compilation options on the Build menu. Because there are so many options, it isn’t always intuitive which option you should use. The options are scoped to either the current project or the entire solution. The top portion of the menu applies to the entire solution, and the second section is context-sensitive, applying to the currently selected project. The following sections describe each set of options, including build, rebuild, and clean for both projects and solutions.

Building Solutions/Projects

Building typically means that you run the compiler to compile source code files. Sometimes the build includes more than compilation. For example, if you are writing ASP.NET applications, VS will generate code based on the Web controls on the page and then that generated code will be compiled with normal code. Therefore, the term build is more accurate than compile.

During a normal build, VS will only build the items in a project or solution that are out of date. More specifically, only projects that have changes and edits will be rebuilt, but projects that are untouched will be reused as is. A build is typically the fastest option during normal development because building only items that are out of date means that there are likely items that don’t need to be built. Be aware, though, that you’ll occasionally need to build everything to make sure you aren’t accidentally working with old code.

Rebuilding Solutions/Projects

A rebuild performs the same actions as a build, except that it forces the build of all items belonging to a project or solution. Reasons for a rebuild include ensuring new code you’ve written works with existing code, creating a fresh build for deployment, and ensuring important items are built when a normal build doesn’t work.

Many developers, including myself, like to pull the latest changes from source control into my solution every morning before starting work. This ensures that the current code in the solution will build with whatever was in source control. This keeps the code in your local solution from differing too much from what is in source control.

Before you deploy an application, you’ll want to perform a rebuild to ensure all of the code builds. Depending on your process, you will want to test the code that was just rebuilt, prior to deployment. The rebuild ensures that the application you are preparing for deployment is the most current.

Sometimes your normal build doesn’t work correctly or you’re seeing bugs that seem to be associated with code that you’ve already written. While VS is a great tool and manages dependencies between projects, there are still complex situations where everything doesn’t build correctly. At these times, you can try a rebuild, which forces the build on all items of a project or solution.

A rebuild takes more time to perform because all items in a project must be rebuilt. If you have a small project, you might not notice the differences. However, if you have a fairly large solution, with dozens of projects, a steady pattern of rebuilds throughout the day could cut into your productivity. A rebuild on a project is often not much more work than a build on the project, but there are probably edge cases where the difference in time would be noticeable. It is the rebuild on the solution that will most likely get your attention. That said, each version of VS has progressively improved the performance of the build process, so you should interpret the performance as a relation between build and rebuild, rather than as a statement about VS compared to any other tool.

Cleaning Solutions/Projects

A clean operation will delete project outputs, which include *.dll, *.exe, or other items produced by the build process. You would often perform a clean operation to guarantee that all outputs are fresh or to obtain a smaller copy of the project.

Normally, a full rebuild ensures that you have the most up-to-date outputs available. You could also perform a clean operation to ensure all outputs were removed and then perform a build to see which outputs were created. This might give you insight into whether the build on a solution was including all of the projects. In normal circumstances, VS manages all of your dependencies for you, as described in the next section. However, in advanced scenarios, some developers might occasionally change these dependencies. Cleaning is a tool to help you know whether a project is really being built. From a practical perspective, this is rare and you could inspect file dates to tell the same thing, but cleaning is another path you can take.

A more common use of clean is to remove outputs from the project to make it smaller. You might want to compress a project or solution and e-mail it to another person, requiring that you minimize the size of the attachment. While code files normally compress very well, *.dll and *.exe files can take up some file space, even when added to a compressed file. If you perform a clean before compressing the files, you will use much less file space.

Managing Dependencies and Build Order

A dependency describes to VS which other projects a given project depends on to operate properly. For the example in this chapter, the ProjectDemo project references ClassLibraryDemo and uses the code in ClassLibraryDemo. Therefore, ProjectDemo has a dependency on ClassLibraryDemo. VS adds this dependency automatically, which is good because when VS builds your solution, it will keep all projects up-to-date. VS manages a tree of dependencies. Whenever you perform a rebuild, VS looks at the dependency tree and builds all projects that don’t have dependencies. Then, VS builds all projects that depend on the last set of projects that were rebuilt. This process continues until the entire solution is rebuilt and all projects at the top of the tree reference updated versions of all referenced projects.

You can manually manage dependencies by right-clicking a project or the solution in Solution Explorer and selecting Project Dependencies. Figure 5-8 shows the Project Dependencies window.

In the Project Dependencies window, you can select (from the drop-down list) the project to set dependencies upon. There is a list of projects that you can set dependencies on. As shown in Figure 5-8, the ProjectDemo project has a dependency on ClassLibraryDemo. VS created this dependency automatically.

Project dependencies directly affect the build order of a project. If you recall from the previous discussion, projects that have dependencies upon them will be built before the depending projects. From the Project Dependencies window, shown in Figure 5-8, you can click the Build Order tab to manage the order of the build. You could also get to the Build Order tab by right-clicking a project or the solution in Solution Explorer and selecting Project Build Order. You can see the Build Order tab in Figure 5-9.

Image

Figure 5-8 Project Dependencies window

Image

Figure 5-9 The Project Build Order tab

CAUTION

Don’t alter project dependencies unless you really know what you are doing. The results could be severe in that it can take a long time to fix dependencies in a large project. The automatic dependency management provided by VS is very dependable, and you should rely upon it whenever possible.

Managing Compilation Settings

The project property pages include a tab for compiler settings. You set compiler settings for each individual project. Figure 5-10 shows the C# tab, which you can open by double-clicking the Properties folder on a project. Some of these settings are advanced topics that are out of the scope of this book. For example, this book doesn’t discuss COM Interop, unsafe code generation, or serialization assemblies. I’ll simply mention the setting with a quick explanation so that you’ll know it’s there if you ever run into one of these scenarios in the future.

The DEBUG and TRACE compilation constants enable you to use the Debug and Trace classes, respectively, that are members of the .NET Framework System.Diagnostics

Image

Figure 5-10 C# Compiler Options

namespace. You can also build code that depends on your own custom constants by adding your own constants to the Conditional Compilation Symbols box as a comma-separated list of strings.

C# allows you to write code that is classified as unsafe, meaning that you can use pointers and other features in an unsafe context. Unsafe code is still managed code (managed by the CLR). However, the CLR can’t verify that the code is safe because unsafe code can contain pointers. This is an advanced feature and the box is unchecked, ensuring that you must check it to opt in to enable this type of coding.

All warning messages are associated with a level, and the Warning level is set to 4 by default, which includes all compiler warnings. Setting this to a lower level would suppress the display of all warnings at that level or higher. You can also suppress specific warnings by adding them to a comma-separated list in the Suppress Warnings box. You really shouldn’t suppress warnings, as this setting could cover up an error that would be hard to detect otherwise.

When you build an application, your program will run even if warnings are present but will not run if the compiler encounters errors. Sometimes warnings are so important that you might want to treat them as errors, and the Treat Warnings As Errors section gives you flexibility in handling warning-as-error scenarios.

The output path of an application defaults to binDebug under the project folder for Debug builds and binRelease for release builds. You can change this location if you like.

Checking the XML Documentation file will cause XML Documentation comments to be extracted from your code into an XML file that you specify. Checking this box increases the time of the build process, so you won’t necessarily want to leave it on during Debug builds, when you are doing most of your coding. The XML documentation file can be input into third-party tools that automatically build technical documentation for you.

You would only check the Register For COM Interop box if you were building a .NET Assembly that was being called from a COM application.

If you’re doing XML serialization of types in an assembly, you can turn on the Generate Serialization Assembly to speed the serialization process.

C# has another group of settings on the Build Events tab. You can run code before or after the build for each project. You can set the conditions upon when the build occurs, which could be always, on a successful build, or only when an update occurs. The build events have a set of macros you can access that give you information on the current build process.

VB has options that are specific to the VB compiler on its Compile page, shown in Figure 5-11.

Image

Figure 5-11 The VB Compile Options page

Most of the VB and C# compiler options are similar, except for Option Explicit, Option Strict, Option Compare, and Option Infer. In VB, variable declaration before use can be turned off. When Option Explicit is on, you must declare any variables before use. You can also assign any type to another by default, but Option Strict, if turned on, will force you to use code that performs a conversion from a larger type to a smaller type, often referred to as a narrowing conversion.

Option Compare causes comparison of strings to be done in a binary fashion. However, when working with different languages, you’ll want to consider changing Option Compare to text so that the comparison will consider culture-specific issues affecting string comparisons. Option Infer will allow a variable to assume its type based on what is being assigned to the variable, rather than explicitly declaring the variable type. Here’s an example of interred type on a variable:

Dim studentName = "Joe"

In this example, the type of “Joe” is clearly a String. Since Option Infer is turned on, this syntax is valid and studentName becomes a String because that is the type of the value being assigned.

Navigating a Project with Class View

An alternate way to work with projects is via Class view, which allows you to view solutions and project artifacts through the logical layout of the code. In C#, you can open Class view by pressing CTRL-W, C or select Class View from the View menu. In VB you can open Class view by pressing CTRL-SHIFT, C or select View | Other Windows | Class View. Figure 5-12 shows the Class View window.

In Class view, you have a hierarchy of nodes that start at the project, include references and namespaces, and contain classes under those namespaces. Under each class you have Base Types, which contains a list of base classes derived from and implemented interfaces for that specific class. Notice how I selected the Student class in Figure 5-12, which shows the members of the class in the bottom pane.

As shown in the Class View toolbar, you can create new folders, use the arrows to navigate up or down the hierarchy, or choose options of what to display in the hierarchy. There is also a button with a glyph of objects that indicate how to create a class diagram, which is discussed in the next section.

Image

Figure 5-12 The Class View window

Using the Class Designer

When working with a project, it can sometimes be helpful to have a high-level view of the project contents, especially if someone else has created the project and you haven’t worked with that project before. This is where the Class Designer can help. In addition to code visualization, another capability of the Class Designer is to give you a basic tool to perform some design yourself. We’ll look at visualizing existing classes first.

Class Designer Visualization

Whenever you select a project in Solution Explorer, you’ll see the Class Designer button appear in the Solution Explorer toolbar. The Class Designer button also appears on the Class View window. Clicking View Class Diagram will produce a diagram of classes in your solution, shown in Figure 5-13.

As you can see in Figure 5-13, VS produces a new file, named ClassDiagram1.cd, with a visual representation of your code. You can see that the properties window is open, allowing you to view information about the selected Program class. Additionally, the

Image

Figure 5-13 Visualizing code with the Class Designer

Class Details window provides additional details on the members of the Program.cs class. Figure 5-13 is a minimal diagram of one class with a single method, Main, and you would have seen all of the classes in the current project if there were more. This could be a good way to help you learn about an existing base of code.

In addition to code visualization, you have the ability to perform some light design with the Class Designer, as discussed in the next section.

Class Designer Code Generation

The Class Designer allows you to generate code graphically. On the left-hand side of Figure 5-13, you’ll see a tab for the Toolbox. Hovering over that tab, you’ll see a group of images for code items, such as Class, Enum, Inheritance, and more. Figure 5-14 shows the results of using Toolbox items to enhance the existing Figure 5-14 diagram.

In Figure 5-14, you can see the Toolbox with options for what type of items you can add to a class diagram. Each of the Toolbox items matches some type of code that you would normally write. The class diagram itself has additional items, including an abstract

Image

Figure 5-14 Generating code with the Class Designer

class named Staff, a normal class named Teacher, an inheritance relationship where Teacher derives from Staff, and an association from Program to Staff.

To create a new object, drag-and-drop the object from the Toolbox to the Class Designer surface; you’ll see an input window similar to Figure 5-15.

The New Abstract Class window in Figure 5-15 is typical of most of the Class Designer objects you can add to a diagram where you fill in the initial data for naming the class and specifying the file the code will be added to. Not all Toolbox options work this way, though; associations and inheritance work by selecting the item in the Toolbox, selecting the object where the line begins in the Class Designer, and dragging the line to the object in the Class Designer being referenced.

The other two places you can modify data are in the Class Details and Properties windows. You can see how I added the GradePapers method in Class Details. You can add members to an object yourself by clicking the object in Class Designer, and then adding the member in Class Details. The GradePapers method also has a Summary comment for documentation and a parameter named papers with a type of List<string>.

The Properties window is context-sensitive, showing you what options are available for whatever you have selected in the Class Designer. In Figure 5-14, the Teacher class is selected in Class Designer and the Summary property in the Properties window was filled in with a comment. Listing 5-3 shows the code from the Teacher.cs (Teacher.vb in VB) file that was generated after all of these actions in the graphical designer.

Image

Figure 5-15 Adding a new object to the Class Designer

Listing 5-3 Code generated from the Class Designer

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProjectDemo
{
       /// <summary>
       /// Teaches Classes
       /// </summary>
       public class Teacher : Staff
       {
              /// <summary>
              /// Grade student papers
              /// </summary>
              /// <param name="papers">Papers to grade</param>
              public void GradePapers(List<string> papers)
              {
                  throw new System.NotImplementedException();
              }
       }
}

VB:

''' <summary>
''' Teaches Classes
''' </summary>
Public Class Teacher
    Inherits Staff

    ''' <summary>
    ''' Grade student papers
    ''' </summary>
    Public Sub GradePapers(ByVal papers As List(Of String))

    End Sub

End Class

As shown in Listing 5-3, code generated from the Class Designer includes default using directives and the namespace as specified in project properties. The class name, Teacher, is the same as the visual object in the class diagram, and the GradePapers method is the same as specified in the Class Details window. You can also see the comment on Teacher as specified in the Property window. All that’s left for you to do is replace the call to throw new System.NotImplementedException with your own code in C# or just add your code to GradePapers in VB.

Summary

You should now know how to create a solution and a project. You can set project properties and add new members to projects. Additionally, you are able to add class libraries to a project and reference those class libraries from other projects that use those libraries. If you prefer a more formal design process, VS offers the Class Designer, which you learned to use for both visualization and code generation. The next chapter builds upon the coding process with VS by showing you how to debug code.

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

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