APress Visual Studio Condensed

Page 1


For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them.


Contents at a Glance About the Author �������������������������������������������������������������������������������������������������������������� xvii About the Technical Reviewer ������������������������������������������������������������������������������������������� xix Acknowledgments ������������������������������������������������������������������������������������������������������������� xxi Introduction ��������������������������������������������������������������������������������������������������������������������� xxiii ■■Chapter 1: Introducing Visual Studio ���������������������������������������������������������������������������������1 ■■Chapter 2: Configuring Visual Studio ������������������������������������������������������������������������������25 ■■Chapter 3: Development Tools �����������������������������������������������������������������������������������������59 ■■Chapter 4: Debugging ������������������������������������������������������������������������������������������������������93 ■■Chapter 5: Code Improvement Tools ������������������������������������������������������������������������������115 ■■Chapter 6: Testing Your Applications ����������������������������������������������������������������������������137 ■■Chapter 7: Teamwork with Visual Studio ����������������������������������������������������������������������155 ■■Chapter 8: Framework-Specific Features ����������������������������������������������������������������������179 ■■Chapter 9: Extending Visual Studio �������������������������������������������������������������������������������207 Index ���������������������������������������������������������������������������������������������������������������������������������227

v


Introduction Visual Studio is a broad subject, but this book covers it in a concise way. In order to give you enough information to use Visual Studio effortlessly, this book covers a little bit of everything. Some features covered are limited to specific editions of Visual Studio; in those cases, the book marks the edition required with a banner at the beginning of the section. To avoid repetition, however, all features that are limited to the Express edition are specified, as are Premium and Ultimate edition features. For features available in several editions, only the lowest required edition is specified. For example, if a description is applicable to Premium and Ultimate editions, we will mark that feature as Premium. This book does not cover Visual studio features for specific platforms or technologies in depth. Chapter 8 is dedicated to platform-specific Visual Studio features, but it discusses each one only briefly. Also, because the focus here is on the development environment itself, there are few examples of code, all of them written in C#. Even if you are a Visual Basic or C++ developer, this should not affect you because the focus is on Visual Studio. This book contains information about how to use Visual Studio by explaining all its visual aspects and possible configurations. Then, it demonstrates Visual Studio’s capabilities for development and debugging. Several tools to improve your code are discussed, along with testing tools. You will learn about collaborative tools that Visual Studio offers with Team Foundation Server. Finally we take a peek at framework-specific features and how to extend Visual Studio.

xxiii


Chapter 1

Introducing Visual Studio Visual Studio (VS) has been the single Microsoft Integrated Development Environment (IDE) since its release in 1995. Previously, Microsoft Visual Basic, Visual C++ and Visual FoxPro were three different software formats. Between 1995 and 1998, Microsoft released three versions of Visual Studio. In particular, Visual Studio 6.0 was one of the most popular development tools of its time, for four years until Microsoft announced its new orientation with the .NET Framework in 2002. VS 6.0 is the first version that has more than one edition. Further versions rapidly appeared, with a version in 2003, followed by 2005 with .NET Framework 2.0. Three years later the 2008 version came out, then 2010, 2012, and finally 2013. The latest editions offer more tools and features to improve developer capabilities. In this chapter, you will learn the differences between all Visual Studio 2013 editions and get an overview of every visual component of this latest version of the Microsoft IDE.

Visual Studio Editions Visual Studio 2013 became available on October 17, 2013. It is available in five editions that fulfill different needs. •

The Express edition cannot have any extensions and does not offer any satellite tools like profiling, testing, or architecting, and it has limited project templates.

Professional is the entry-level version if you want more than just basic development. It can do unit testing but none of the other types of tests. You have no limitation on project templates.

Premium lets you read architecture and modeling graphic files.

To use all the architectural tools, you’ll need the Ultimate version.

For testers and QA, Visual Studio has a test edition that is very limited but allows for doing some test impacts and using the lab manager. This version is not discussed further in the following summary.

Different editions meet different needs, and I will explain the features in more depth throughout the book.

Visual Studio Express Edition The Visual Studio Express edition is the free version of Visual Studio. It comes in different flavors. One is for the Web, one for Windows, one for Windows Desktop, and one for phone development. The Express edition allows you to start developing with Microsoft .NET technology and has limited features compared to any paid version. However, Express projects can be opened with all Visual Studio editions, and Visual Studio Express can be upgraded to any other edition at any time. The difference between the Windows and Windows Desktop versions is that one is for Windows Store app development (supported by Windows 8 and later versions) and the other is for WPF, WinForm, and Win32 applications. The Web edition creates web applications, web APIs, or Azure applications.

1


Chapter 1 ■ Introducing Visual Studio

Visual Studio Express projects can be used for commercial purposes. One major drawback of the Express edition that you need to consider is that you cannot use any add-ins or extensions. Popular tools like ReSharper or Web Essentials cannot be installed. Nevertheless, the NuGet tool (part of Express since 2012) can be used, and we will talk about it in Chapter 3. A second detail to consider is that the type(s) of application you can create will be defined by the installed edition. For example, with the Visual Studio Web edition, you will not be able to create a Windows Phone application or a Windows WinForm application; Visual Studio will not offer the option in its Create menu to create a new project of a different type. A third feature that does not come with the Express edition but does with all other editions is the Exception Assistant tool. The Exception Assistant is a message box that appears when an unhandled exception occurs while debugging. It displays the type of exception, the stack trace, the inner exception, a help link for the error, an error message, and additional information to help you identify why the code is in an exception state. This scenario occurs in situations where you might not have considered an exception scenario and having additional information about it is precious. Visual Studio Express, since version 2010, does not provide this dialog box. Visual Studio Express has its own application ID. This means it can be installed in parallel with other Visual Studio editions. This is not the case with any other edition of Visual Studio. For example, if you have the Professional edition, you won’t be able to install the Premium edition side by side. However, you will be able to have Visual Studio Express Web edition in parallel with Visual Studio Express Desktop edition or Ultimate edition.

■■Note  You can install Visual Studio 2013 in parallel with Visual Studio 2012, 2010, 2005, and so on because each of these versions has a different application ID. Finally, keep in mind that this version is primarily intended for trying out the base IDE tools, or for the hobbyist developer. Visual Studio Express edition cannot use Microsoft Unit Testing Framework. It has limited project templates, and its integration with MSDN is limited.

Visual Studio Professional Edition Microsoft Visual Studio Professional Edition is the entry point of the full Visual Studio IDE. With this edition and above, it is possible to create every type of application within the same IDE. This mean you can create Windows WinForms, Web Form applications, ASP.NET MVC, Windows services, WCF services, phone applications, Windows 8 applications, and so on. This edition is perfect for the developer who wants to code applications without needing too many features. Basic features like project templates, debugging tools, page inspector, static code analysis, and Windows 8/phone simulator are all available. Almost all IDE features are available except the CodeLens and the Code Clone feature. Visual Studio has a lot of architecture and modeling tools available. Visual Studio Professional does have some of them. It has the ability to show code dependencies with dependency graphs. It can also create a code map (in read-only format). Visual Studio Professional’s feature limitations start with the testing tools that we will discuss later in Chapter 6. The Professional edition allows only unit testing, while other versions allow for more advanced testing. Its online service also has limitations. It has almost every feature that the Visual Studio Online Edition’s Basic and Pro versions have, but not as many as the Advanced version. For example, it cannot handle agile portfolios or work with team rooms. But almost all other features are available, including the use of work items, sprint planning, repositories like TFS or Git, and Team Explorer, which can be used within Visual Studio or with a plug-in for Explorer. However, it cannot use the team review features. Most of the missing features should not be a showstopper for most developers, and usually this is the edition most developers should be using. It costs a fraction of the price of the Premium and Ultimate editions, and it still offers many tools.

2


Chapter 1 ■ Introducing Visual Studio

Visual Studio Premium Edition Visual Studio Premium edition sits between the Professional edition and the Ultimate edition. It has everything the Professional edition has with additional features. This version is for the advanced developer or for the architect of your team. This is the first edition to have Code Metrics. This is an essential tool to improve your application quality. It also has the Code Coverage tool, Microsoft Fakes for unit testing, and UI testing tools. It is also the first edition to have the Code Clone feature but still doesn’t have the CodeLens tool. For architecture and modeling, the Premium edition adds the architecture validation feature and has UML compliance diagrams such as the activity diagram, use case, sequence, and component. However, the UML diagrams are in read-only format, while all others can be read/write. This is a step better than the Professional edition for code mapping and the dependency graph. The team foundation is enhanced for the Premium version and has everything the Ultimate version offers. It is possible to manage development tasks and features like agile portfolios, team rooms, work item charting, release and backlog management, sprint planning, Kanban or agile task boards, TFS or Git source control, work item tracking, and build automation.

Visual Studio Ultimate Edition Visual Studio Ultimate edition is the most complete of all Visual Studio editions. It is the version in which everything is possible, all features are available, and no restrictions apply. Everything is read/write, and it has additional features that we have not yet covered. This version is often used by the team lead or the head architect. It is the first edition to have IntelliTrace for debugging, which is also available in production. It is also the only version that allows .NET memory dump analysis and coding map debugger interaction. Since 2013, CodeLens is also a new feature available only in this version. For code architecture and modeling, Ultimate provides the Architecture Explorer and the architecture and layer diagrams. These two features are only available for the Ultimate version in write mode. Premium can read files generated by Ultimate but no other edition. The Ultimate edition has one feature that no other Visual Studio version has, which is a cloud-based web load and performance test. No version of Visual Studio Online has this feature or any other Visual Studio version. This requires having an Azure account, and it is a feature that we do not use often.

■■Note Throughout this book, I will indicate which edition at a minimum is required for the feature discussed. If nothing is specified, you can assume it is available in all editions beginning with the least: the Express edition.

Visual Studio Online A brand-new addition in 2013 is Visual Studio Online. It is a light version of Visual Studio that was formerly named Team Foundation Services. It is important to know that Visual Studio Online does not replace the more traditional editions of Visual Studio. It allows having a source control with Team Foundation Services (TFS) but also offers work items tracking, agile planning, and build and load testing services. So far, unlike Visual Studio itself, Online does not let you write code for every project type. Nevertheless, Visual Studio Online is the first edition to offer a coding environment for the cloud (if only for Microsoft Azure). It is very lightweight at this moment. The name of the online Visual Studio code editor is Monaco. The online edition allows for the creation of the desktop application as a web application or Azure application. Visual Studio Online is available in three subscription plans: Basic, Professional, and Advanced. Online Basic is free until you need more than five developers in the project. If you need more than five users, a fee by user is charged. Online Basic works with Visual Studio Express Edition for Web, Windows, or Windows Desktop. Online Professional is distinct from the others, with a limit of ten developers. It also comes with a monthly subscription to the Visual Studio

3


Chapter 1 ■ Introducing Visual Studio

Professional IDE, which is a major plus. The Advanced plan is aimed at a larger project with several teams. It provides a real-time update on all your teams and allows you to be more efficient with the communication and management of all your developers. It is integrated with Visual Studio and also with Eclipse and Xcode. Unlike Basic and Professional, the Advanced plan allows an unlimited number of developers. The benefit of choosing an online plan is that you can simply manage your team without having to configure TFS and Visual Studio yourself. As you will see soon, it is possible to work online with a traditional version of Visual Studio. In fact, all other editions of Visual Studio share the online part of the online plan. The main difference is the payment; it is monthly for the online plans and a onetime payment for the full edition. However, all Microsoft Visual Studio versions allow you to try them free of charge. Table 1-1 compares the features of the three Visual Studio Online plans. Table 1-1.  Comparison of Visual Studio Online Plans

Features\Division

Advanced

Professional

Basic

Maximum number of users with this plan on an account

Unlimited

10

Unlimited

Unlimited team projects and private, hosted code repos using TFVC or Git

X

X

X

Project planning and bug tracking tools, including Kanban boards and team velocity forecasts

X

X

X

Integration with popular development tools, including Visual Studio, Eclipse, and Xcode

X

X

X

Work in one IDE to create solutions for the web, desktop, cloud, server, and phone

-

X

-

Support for Office 365 business apps

-

X

-

Track complex projects with hierarchical portfolio backlogs

X

-

-

Visualize project data with work item chart authoring

X

-

-

Send feedback requests to users and stakeholders

X

-

-

Manage and run tests and test plans

-

-

-

Host team projects on-premises as well as in the cloud

-

-

-

■■Note  For more details about prices and the differences between online editions, see Visual Studio’s website at http://www.visualstudio.com/products/visual-studio-online-overview-vs.

Guided Tour of the Visual Studio UI Visual Studio has been enhanced a lot since its creation. The software is composed of several portions that are worth exploring. This section explains most of the useful parts of the IDE.

4


Chapter 1 ■ Introducing Visual Studio

The General UI Before going deeper into Visual Studio’s 2013 features, let’s do a quick overview of its user interface (UI).

■■Note  Because the Ultimate edition includes every Visual Studio feature, it will be used for screen shots throughout this book. First, the Visual Studio menu is at the top of the screen. It offers different possible actions grouped by theme. For example, the main menu has File, Edit, View, Project, Build, Debug, Team, Tools, Test, Architecture, and Analyze tabs that all contain submenus. Second, toolbars are located under the menus. You can configure toolbars by adding tools or removing buttons and bars as you wish. Toolbars must always be located under the menu and over the main code editor. This means that you can move toolbars to specific locations, but you cannot move them just anywhere. The third part of the UI is the code editor, located between the toolbar and the footer. The footer, shown in Figure 1-1, provides information about the state of the compilation and the position of the caret.

Figure 1-1.  Footer information Figure 1-1 shows that the current state is Ready, which tells you that it is ready for the next project to be compiled in this example. The second indicator displays a progress bar and appears only when compiling or publishing. Following that, the icon that looks like a box indicates what type of progress is occurring. Figure 1-1 has the icon for compilation. Next to this icon is information about the caret position. It indicates that it is located on line 49, column 18, which is also character 18. Finally, on the far right is the keyboard mode, which is currently Insert (the alternative would be Override).

■■Note  You can double-click the line, column, or character in the footer to open the Go To Line dialog or press the shortcut, Ctrl+G. Visual Studio offers an easy way to communicate feedback to Microsoft. At the top right of the screen, a small shootout icon is available. Click it to send feedback with an attached screenshot of the current state of your Visual Studio. Label (1) in Figure 1-2 highlights the feedback feature.

5


Chapter 1 ■ Introducing Visual Studio

Figure 1-2.  Feedback and notifications The top menu also contains an icon in the shape of a flag (2). This one is for available notifications. If you click the flag, the notification panel opens. If the notification flag is black, a new notification is available. If the flag is white, no notification is available. Finally, the top right contains a Quick Launch textbox. If you start typing, a context panel appears with related information. Quick Launch provides a search within all code file names, build configurations, tools, architecture, and modeling files. It also allows you to jump to every configuration possible inside Visual Studio, and open documents and even NuGet packages. Figure 1-3 shows its results.

6


Chapter 1 ■ Introducing Visual Studio

Figure 1-3.  Quick Launch results

The Start Page Visual Studio consists of several panels and toolbars. When Visual Studio opens, the first panel displayed is the Start page, shown in Figure 1-4.

7


Chapter 1 ■ Introducing Visual Studio

Figure 1-4.  Visual Studio Start page The Start page contains various types of information. In Figure 1-4, labels (1) and (2) point out the two portions of the Start page that developers use the most. The Start link at (1) lets you create a new project, open an existing one on a hard drive, or open an existing project from a source control. These functions are also available in the File menu (Figure 1-5).

8


Chapter 1 ■ Introducing Visual Studio

Figure 1-5.  To start working in Visual Studio, choose New Project, Open Project, or Open from Source Control The Recent link at (2) offers a history of the recent solutions that you have open. Often, developers work on the same solution for a while. Opening one of these solutions is a great shortcut to get up and running quickly when you need to open Visual Studio. The links at (3), (4), and (5) in Figure 1-4 are always at the right side of the Start page. This part is dynamic and updated by Microsoft. At (3) you’ll find links to websites for information about new features and enhancements of the edition you are working on. In the screen shot, it is news concerning the Visual Studio Ultimate edition. At (4), What’s New on Microsoft Platforms, are links to Microsoft platforms. This information is rarely used compared to the Product Videos at (5). This displays a short tutorial video about Visual Studio tips and features. Under the Video section, Visual Studio also has an Announcements section, which reports an all-new version of Visual Studio and discusses what is coming out soon. The Start page is a panel like most of Visual Studio’s screens. All panels have the same common features: One feature is that they can be closed. To close a panel, the mouse needs to hover over the panel header or the panel needs to be the one that is active. In both scenarios, an X icon appears. In Figure 1-6, the Start Page tab is shown because it is open on the screen, but you can see that it is also activated because the focus is on it. This is not the case for the Errors In Solution panel to the right of the Start Page panel. This panel is open but not activated, and hovering with the mouse has no effect. To close a panel, select the X icon.

Figure 1-6.  Click the X to close a panel

9


Chapter 1 ■ Introducing Visual Studio

Pinning Panels To activate a panel, just click on the caption. Two icons appear. One is the close icon, as we just saw, and the other is a pin icon (Figure 1-7). The pin icon is a second common feature that allows you to make a panel sticky on the screen. Otherwise, the default behavior is that once a panel loses its focus, it collapses to give more space. If you want to keep the panel open, click once on its pin icon.

Figure 1-7.  Two different states of the pin icon Figure 1-7 shows at the left a C-Sharp file named Configuration.cs that is open but not pinned. This one stays open because it is a code file. Having a code panel pinned has no effect except that all pinned code files are grouped together. However, at the right of Figure 1-7, the Solution Explorer is pinned. This panel stays open even if the focus is on the left panel. Usefully, you can navigate quickly with the Solution Explorer while having the code editor open. Having a code file pinned will let you close all of the pinned or unpinned panels, depending on which option you choose. To access this option, right-click any code file and a context menu will appear, as shown in Figure 1-8.

Figure 1-8.  Choose the Close All But Pinned option to view only a single panel

10


Chapter 1 ■ Introducing Visual Studio

Docking Panels Panels can be docked. Visual Studio is a big container in which panels can be moved around and docked. A panel is docked when it is in one of six possible positions: left, right, top, bottom, center, or its own group outside Visual Studio. To move a panel, click its caption and then drag it into one of the six locations highlighted in Figure 1-9.

Figure 1-9.  Docking positions Once you have clicked the title of a panel and have started to move your cursor, keeping it pressed on the panel, you will see a docking indicator like those labeled in Figure 1-9. Clicking at (1) will dock the panel at the top of the screen. If you release the mouse at this position, the panel will be placed over the three panels open (Errors in Solution, Configuration.cs, and AccountController.cs). If you drop it at position(2), the current panel will be grouped with the Toolbox panel. By default, the panel will be open but once the focus is lost, the panel will be under the Toolbox caption. It is the same for the bottom position, (3), and the position at the right (4).

11


Chapter 1 ■ Introducing Visual Studio

The placeholder at (5) is unique because it allows for nine different positions. The center one is the most used. In the example in Figure 1-9, the center position would put the panel with the three others on the main panel (Errors in Solution, Configuration.cs, and AccountController.cs). Those placeholders that are at each end create a new column of panels. For example, the one at the far right of (5) would create a unique panel group to the right of the existing one, which already contains three open panels (Solution Explorer, Team Explorer, and Server Explorer). On the other hand, an inner placeholder at (5) places the panel at the position desired within the center panel. The inner one is rarely used except when you want to have two code files open side by side. The last docking position is shown at (6) but could be anywhere outside Visual Studio. Often, developers with more than one screen want to have a toolbox, Solution Explorer, or other panels on their second screen. This allows more space for the code and lets you have more panels open and pinned.

■■Note Usually developers have the Solution Explorer and Unit Test pinned on their screen.

Navigation Visual Studio incorporates many features to help you work efficiently while developing. One main aspect where Visual Studio 2013 shines is navigating between files. This is important because developers must change task files hundreds of times every day. This section describes navigation tools that are available directly on the Visual Studio user interface. They are the Solution Explorer, the Search Solution Explorer, and the Quick Launch. Other features for navigation exist but are related to code directly and will be discussed later in the book. The Solution Explorer is a panel (Figure 1-10) that has been available since almost the first version of Visual Studio. Searching within the panel now allows filtering. This is an important feature for a large solution. To access the Solution Explorer, choose View ➤ Solution Explorer.+

Figure 1-10.  Solution Explorer panel The Solution Explorer has its own toolbar that contains several icons:

12

Left and right arrow icons: Allow you to move between previous searches.

House icon: Toggles the navigation between a search and the initial state, which is to display every file and project.

Clock icon: Allows a fast way to see only those files that have been modified since the last commit to the source control.


Chapter 1 ■ Introducing Visual Studio

Double arrows icon: Allows synchronizing the current open file with the Solution Explorer. This means that if you have a file open and you click this icon, the file name will be selected in the Solution Explorer, allowing you to navigate back to the file structures from a file that is open. This is a very useful command when you are navigating with other mechanisms and you want to come back to the Solution Explorer.

Round arrows icon: Refreshes the file with the source control.

Multiple sheets icon: Allows collapsing every project and folder. After you’ve been working for some time, solutions can become messy, so it’s useful to be able to collapse everything for a cleaner view of the solution.

Double files icon: Allows displaying files in the Solution Explorer even if they are not part of the solution. This lets you easily add files by right-clicking them, and you can add them to solutions without using Add Existing Item.

Less and greater icon: Switches the file into the code editor. This is only useful when a file can be opened in either a designer mode or a code editor mode. For example, that is the case for the WinForm application.

Wrench icon: Allows switching to the Property Panel for the active file. When the Property Panel opens, the properties displayed may be for the file, control, or HTML tag you have selected and not the file itself. This button automatically displays the properties of the file.

Toggle icon: Accesses the Preview Tab feature that has the file open automatically when a file is clicked in the Solution Explorer. When a file is opened with the Preview Tab without being edited, it is closed automatically when the focus moves to another file.

The Solution Explorer has under its toolbar a textbox for the Search Solution Explorer feature (Figure 1-11). This tool performs a search within all files inside the Solution Explorer. The shortcut is Ctrl+;. You can search within the file contents and by file name. You can customize these options by clicking the arrow next to the search text box.

Figure 1-11.  Solution Explorer search The Quick Launch tool was briefly discussed earlier, but it allows for navigating, too. It is available at the top of the Visual Studio UI, or by pressing Ctrl+Q. You can navigate to the most recently used file by adding @mru followed by the keyword desired. You can also navigate to something inside a menu by adding a prefix to your search with @menu. The prefix to navigate directly to an option is @opt, to NuGet it is @nuget, and to search open documents it is @doc.

13


Chapter 1 ■ Introducing Visual Studio

Properties Visual Studio’s Properties pane allows you to change a property depending on which element is active on the screen. The shortcut key is F4. If you select a file, the Properties pane will show the file properties. If you select a C-Sharp file, nothing should be displayed. However, if you select a file with a .cshtml extension, it gives you possible HTML attributes depending on where your cursor is located. If you select a resource file, properties for resource files are displayed, and so on.

Command Window The Command window has been present for many years in Visual Studio and it allows you to execute commands directly in the IDE. To access the Command window, press Ctrl+Alt+A. You can also access it by choosing Views ➤ Other Windows ➤ Command Window. For example, if you want to build your entire solution, just type Build.BuildSolution and the solution is compiled. Since Visual Studio 2010, the Command Window has provided IntelliSense, which helps you explore possible commands and eliminate the need to type everything. When debugging, IntelliSense can evaluate an expression if you use the question mark followed by a space and the name of the expression; for example, ? variable1. It is possible to use the up and down arrow keys to navigate through the history of commands. You can also open a file by starting a command with the keyword of followed by a space and the file name. For more information, see the “IntelliSense” section later in this chapter. If you want to know the Visual Studio command aliases, like what the question mark does, you can enter alias into the Command window, and the full list of aliases and their related commands will be displayed.

Immediate Window The Immediate window evaluates expressions when using the question mark, just like with the Command window. This time, only typing the variable name is enough. To access the Immediate window, press Ctrl+Alt+I or choose Debug ➤ Windows ➤ Immediate Window. The Immediate window is useful only at debug time and shows a subset of what the Command window can provide. It is a panel that you can pin when debugging and hide when you are developing.

Error List The Error List panel is where every error, warning, and information message is listed (Figure 1-12).

Figure 1-12.  Error List panel

14


Chapter 1 ■ Introducing Visual Studio

The funnel icon on this panel allows you to filter errors, warnings, and messages by project, document, or only open documents. Then, in the resulting set, it is possible to filter only errors or warnings or messages by choosing the type you want to filter. It is also possible to search through the list. The list is updated automatically for most errors, but some additional information can be discovered only at compilation time. This is one of the most useful panels and should be always open.

The Object Browser The Object Browser (Figure 1-13) gives you information about the DLL of your project, DLLs referenced by your project, and any DLL or COM object on your computer. To access the Object Browser, choose View ➤ Object Browser or press Ctrl+Alt+J. By default, the preset shows only your solution, which lists all your projects and all the referenced DLLs.

Figure 1-13.  Object Browser At (1) is the list of all libraries listed in the current solution, known as the Object Panel. It currently shows the Browse list for My Solution. The Entity Framework library is open for the System.Data.Entity namespace. The Database class is also open and its content is seen at the right. At (2) is the Member Panel. When a method is selected, the Description Panel (3) is open with a definition of the method. The Object Browser is useful for learning more about libraries but is used less and less now that it’s possible to search on the Internet for richer information. The Internet contains examples of use, which the Object Browser does not. It is also less used because some other tools allow you to dig into the class of the variable. Even if the class is from a library outside your solution, the Object Browser can jump into the file definition or even be able to decompile the code. In both cases, however, you can have a good idea of the signature of classes without having to use the Object Browser.

15


Chapter 1 ■ Introducing Visual Studio

Code vs. Debug View Visual Studio’s User Interface (UI) has two different modes: Code and Debug. It is important to be aware of this because you may be confused when Visual Studio is changing modes. When you open panels and docks at the location you desire, Visual Studio can save these placements depending on whether you are coding or debugging. This allows you to have different panels open depending on what you are doing. For example, you may not want to see the Code Stack open when developing but want this one open and pinned to be activated all the time when debugging.

Smart Tag Visual Studio offers real time information about your code with smart tags. This feature first alerts you where it can make suggestions about your code by flagging those items with a red underline (Figure 1-14).

Figure 1-14.  Red underline highlights where a Smart tag will appear When you put your cursor over the word with this indicator, the smart tag appears, showing multiple possible actions (Figure 1-15). You can also open this list of possible actions by pressing Ctrl+.(period).

Figure 1-15.  Smart tag with two suggestions

16


Chapter 1 ■ Introducing Visual Studio

IntelliSense IntelliSense is a Microsoft Visual Studio code completion feature. You can type just a few keystrokes and press Tab or Enter, and the complete word will be written for you. IntelliSense groups some other features that we will discuss here, like List Members, Parameter Info, Quick Info, and Complete Word. IntelliSense has been around since 1996 and has been improved to be more intelligent. It uses your current code but also draws on other libraries to figure out what variables, methods, or namespaces are available. Since the release of .NET, IntelliSense has triggered when the developer types; no shortcut is needed. IntelliSense uses a feature called List Members (Figure 1-16). This displays every member of an object when the object is followed by a dot.

Figure 1-16.  The IntelliSense List Member display At label (1) in Figure 1-16 is the dot, the trigger that tells IntelliSense to use the List Members feature. It opens the list of possible options shown at (2). Furthermore, if a comment has been written, it is displayed, as shown in the Quick Info popup at (3), which we will discuss shortly. Another feature that kicks in once you choose the method of an object is Parameter Info (Figure 1-17). It gives information about every type of parameter and displays the comment written for the parameter.

Figure 1-17.  The IntelliSense Parameter Info display

17


Chapter 1 ■ Introducing Visual Studio

It is possible to trigger this feature by using the shortcut Ctrl+Shift+Spacebar or by using the Parameter Info button on the editor toolbar. If a method is overloaded, you can use the up and down arrow keys to navigate through the whole list of overloaded methods. The Quick Info displays documentation about different methods (Figure 1-18). You can trigger it by using the menu or by using the shortcut Ctrl+I. A popup is shown with the return type of the method, parameters, and the comment written for the method. You can see Quick Info when you have the List Member open and also when you hover over an existing method.

Figure 1-18.  The IntelliSense Quick Info display Another addition to IntelliSense is the Complete Word feature, which completes the word you are typing if Visual Studio can figure out without a doubt which variable or method has been written. The shortcut is Ctrl+Spacebar. In Visual Studio 2013, IntelliSense has been improved by allowing Pascal Case to filter a long Method List. It allows you to search by entering only the first letter of each word in a method name. For example, Figure 1-19 shows a list of several methods that start with the same name.

Figure 1-19.  The IntelliSense Long Member List display Instead of searching through the list, it is now possible to type TFCD, for TemplateForComponentD (Figure 1-20).

18


Chapter 1 ■ Introducing Visual Studio

Figure 1-20.  The IntelliSense Pascal Case feature Visual Studio 2013 IntelliSense can also now search for not only the first word written but also inside the method name (Figure 1-21). That is, you can search for method names that contain a string as well as those that start with it. For example, if you type Me and your class has a method named Method1 and another named ThisIsAlsoAMethod, both will appear, which was not the case in earlier editions.

Figure 1-21.  IntelliSense with a Pascal Case filter now allows searches anywhere within a method name

Code Snippet Code Snippet allows you to have code written for you quickly after typing a few keywords. Code Snippet also contains templates with placeholders that are required to be filled.

■■Note  You can find all preinstalled snippets in your Visual Studio folder at C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC#\Snippets\1033\. This folder contains subfolders for different types of projects.

19


Chapter 1 ■ Introducing Visual Studio

For example, by default, Visual Studio has a Code Snippet named class. If you type cl, IntelliSense shows the class snippet. If you press the Tab key twice, a new class is generated. The first time you press Tab, the letters “cl” expand to the word “class” (Figure 1-22).

Figure 1-22.  Code Snippet with IntelliSense The second time you press Tab, the Code Snippet is launched and a new class is generated with a default name, which is highlighted to allow you to customize the name (Figure 1-23).

Figure 1-23.  Code snippet expanded with default class name It is also possible to trigger a Code Snippet of the type Surround by selecting some code and typing Ctrl+K + Ctrl+S. For example, if you select a few lines of code and use the shortcut for Code Snippet surround, you can select the IF template to have the code surrounded by braces (Figure 1-24).

20


Chapter 1 ■ Introducing Visual Studio

Figure 1-24.  Surround code snippet You can define your own snippet by adding your snippet to the Visual Studio Snippets folder, and you can edit an existing snippet with Notepad. However, a better way is to use the code editor (Tools ➤ Code Snippets Editor) to add your custom Code Snippet folder to Visual Studio. This way, you can copy and paste your folder anywhere you work or share it with your team. The creation of a code snippet is covered later in this book.

Find and Replace The Quick Find feature allows you to search a string by using the shortcut Ctrl+F (Figure 1-25). You can also access it by choosing Edit ➤ Find and Replace ➤ Quick Find. It opens a small search window at the top right of the editor. By default, it searches only in the current document but this can be changed to all open documents, the current project, or for the entire solution. In all cases, the keyword searched is highlighted and you can navigate through all that has been previously searched by pressing F3.

21


Chapter 1 ■ Introducing Visual Studio

Figure 1-25.  Quick Find Visual Studio also has the traditional Find and Replace panel that you can access by pressing Ctrl+Shift+F or by choosing Edit ➤ Find and Replace ➤ Find and Replace (Figure 1-26). This panel has two tabs, one for Find and one for Replace.

22


Chapter 1 â– Introducing Visual Studio

Figure 1-26.  Find and Replace dialog This panel opens another panel called Find Result 1 that contains the result. For every result, an overview of the line is displayed, with the line number and the file path.

Summary This chapter introduced Visual Studio by explaining the differences between every Visual Studio edition, including the difference between an online version and a full edition. Then you saw an overview of the user interface, from the Start page to the most-used panels and visual features that every developer must know.

23


Chapter 2

Configuring Visual Studio Configurations are an important way to customize Visual Studio to your specific needs. Creating tools that work for everybody is not possible. Instead, Visual Studio allows you to modify many options, so you can have an experience that is tailored to you, and still have access to all the power of Visual Studio. This chapter introduces some of the most useful configuration settings that you are likely to want to change in order to get the most out of Visual Studio on a day-to-day basis. They include customizing menus and toolbars, Visual Studio options, Import and Export settings, and Project properties.

Customizing Menus and Toolbars Visual Studio allows you to add, remove, or reorder items on any menu, as well as commands within toolbars. It is also possible to create toolbars. To customize either menus or toolbars, go to Tools ➤ Customize. This opens a dialog window labeled Customize.

Menu The Customize dialog contains two tabs. The first is Toolbars, which we’ll discuss in a moment. The second tab is labeled Commands. This tab allows you to select three different elements to customize. The first is named Menu Bar. It lets you choose which menu to customize. To create a new menu, click Add New Menu. If you want to create a menu at the root, which is always visible on the UI, like the File, Edit, and View menus, you need to be sure that in the Menu bar, the item selected in the drop-down is Menu Bar. You can see the dialog in Figure 2-1.

25


Chapter 2 ■ Configuring Visual Studio

Figure 2-1.  Adding a new menu in Visual Studio You can rename the menu caption by clicking Modify Selection and writing in your custom name. You can see this button in Figure 2-2. If you put an ampersand (&) in front of one letter of your custom name, that letter automatically becomes the shortcut assigned. To invoke it, press Alt + the letter chosen.

26


Chapter 2 ■ Configuring Visual Studio

Figure 2-2.  Renaming a menu To add a command to the new menu, select that menu from the drop-down and click Add Command. In the same way, it is possible to add a menu under an existing menu, as shown in Figure 2-3. To add a submenu, click Add New Menu instead of Add Command.

Figure 2-3.  Adding a submenu to a new menu After adding some commands to a menu or a submenu, your next step may be to group all commands to clean up your menu. To do this, select any commands except the first one and select Modify Selection. This is the same option used to rename a command. At the bottom of the popup panel, select Begin a Group, as shown in Figure 2-4. Adding a group creates a separation line, which marks the end of one group and the beginning of a new one.

27


Chapter 2 ■ Configuring Visual Studio

Figure 2-4.  Creating a menu group

Toolbars You customize toolbars in almost the same way as menus. You can access the options by choosing Tools ➤ Customize ➤ Toolbars, but also by right-clicking any toolbar and selecting Customize. To create a new toolbar, click New in the Toolbars tab shown in Figure 2-5, enter a suitable name, and click OK.

Figure 2-5.  Creating a new toolbar From here, adding commands can take two different paths that will converge into a single one. To add commands, you can remain in the Customize panel and select the Commands tab. This is the same approach as previously discussed for menus. The second path is to right-click any toolbar and select Customize. In both cases you should now be at the Customize panel. You can select the radio button Toolbar and select the toolbar you want to edit. Figure 2-6 shows that we’ve chosen to customize the toolbar named Apress Toolbar.

28


Chapter 2 ■ Configuring Visual Studio

Figure 2-6.  Customizing toolbar commands For toolbars, the default display behavior is Default Style, which shows only the icon. You can optionally choose to include a caption by selecting Image and Text instead; however, it may be preferable to omit the caption and use only the associated icon. Doing so saves space and is more consistent with Visual Studio’s own toolbars, which use only icons. To change this setting, click Modify Selection, and the same pop-up for editing the caption appears.

Visual Studio Options Visual Studio lets you configure everything to make the development experience as smooth as possible. This section explains the most useful options and how to customize them. Most options are located in Tools ➤ Options.

Environment Environment configuration options control general aspects of Visual Studio like the user interface, keyboard, document, languages, and so on. It has the following panels: •

General

Add-in Security

AutoRecover

Documents

Extensions and Updates

Find and Replace

Fonts and Color

Import and Exports Settings

International Settings

Keyboard

Quick Launch

Startup

29


Chapter 2 ■ Configuring Visual Studio

Synchronized Settings

Tabs and Windows

Task List

Web Browser

General You can configure the theme in the General panel. With Visual Studio 2013, you have the choice of three themes: Blue, Dark, and Light. You can also choose how many recent files are displayed in the Window menu when you choose File ➤ Recent Files. The Window menu is accessed from the top bar of Visual Studio. The recent files are in the File menu under Recent Files. There are three checkbox options shown in Figure 2-7. Clearing Show Status Bar hides the status bar (which displays the Visual Studio state, line, columns, and similar information), to provide a little more space. The second checkbox is Close button affects active tool window only. By default when a panel is docked with other panels, only the one that has been closed by the X is closed. If you clear this checkbox, the whole group is closed. The last checkbox, Auto Hide affects active tool window only, controls the behavior of unpinned panels, which auto-hide when not active. By default this option is unchecked, which means that the whole group is hidden when the focus is lost. However, you can check the box if you prefer to have only the active window set to auto-hide.

Figure 2-7.  The Environment ➤ General option

30


Chapter 2 ■ Configuring Visual Studio

Manage File Associations opens a Windows property that hooks file extensions to applications. It is a shortcut from Visual Studio to Windows. It allows binding or unbinding file extensions with Visual Studio applications. You can achieve the same result in Windows by going to Control Panel ➤ All Control Panel Items ➤ Default Programs ➤ Set Default Programs ➤ Set Program Associations.

■■Note It is recommended that you keep .sln and .csproj/.vbproj associated with Visual Studio, because you will use them often to open existing projects from Windows Explorer.

Add-in Security Add-in Security is a simple configuration panel that allows you to specify the directory from which Visual Studio is permitted to load add-ins. You can also specify here whether to allow online add-ins, an option that is not active by default. Visual Studio 2013 deprecates add-ins in favor of VSPackage extensions.

AutoRecover AutoRecover automatically saves your open documents. Visual Studio uses this in the case of a problem that unexpectedly closes the software. The AutoRecover panel offers two options: you can set the number of minutes between each save, and the number of days that Visual Studio keeps files in backup.

■■Note Automatic backup files are located in the directory %UserProfile%\My Documents\Visual Studio 2013\ Backup Files\<ProjectName>\, where <ProjectName> is the project name of your application.

Documents Configuration options for controlling document behavior are grouped under the Documents submenu, illustrated in Figure 2-8.

Figure 2-8.  Document options

31


Chapter 2 ■ Configuring Visual Studio

Figure 2-8 shows which options are selected by default. •

Detect when file is changed outside the environment: This tells Visual Studio to detect if files have been modified outside the IDE. If that is the case, a popup window notifies the developer and asks if the file inside Visual Studio needs to be updated. If you want to have the file automatically loaded without this prompt, check the Auto-load changes, if saved option.

Allow editing of read-only files; warn when attempt to save: By default, Visual Studio allows you to edit read-only files; it is only when the file is saved that the Save As dialog will be displayed.

Open file using directory of currently active document: Visual Studio also opens files using the current active directory instead of the last used directory. It is useful to leave this option checked because using the last used directory can open any directory that you have open outside Visual Studio. For example, if you’re working on c:\code\yourproject\ and then open Windows Explorer to e:\games\xyz, the next time you open a file in Visual Studio it will open this latest directory instead of the one that your project is in, and that is usually not desirable behavior.

Check for consistent line endings on load is useful only if you are using multiple operating systems. Windows and Linux do not use the same ending characters; one uses CR/LF, and the other uses only LF. By default this option is checked, and it does not hurt to keep it this way. If it is checked, Visual Studio displays a dialog asking whether to normalize every file in the project.

Display warning when global undo will modify edited files: Visual Studio has refactoring tools that can modify several files when executed. By default, if a change modifies multiple files and an undo is about to remove the change across all these files, Visual Studio warns the user about it. You can disable this warning by unchecking this default option.

Two more document options are not enabled by default: Show miscellaneous files in Solution Explorer: Miscellaneous files are files that are not directly associated with any projects but can be used by developers. You can create and edit these files with Visual Studio but usually do not want them in your solution. These files might include files that contain SQL or that you downloaded from the Internet for reference but will not be part of the final solution. By default, these files are not displayed in the Solution Explorer. For example, if you drag and drop a file that is not added to your project from Windows Explorer into Visual Studio, a folder named Miscellaneous Files appears in the Solution Explorer. Figure 2-9 shows this example.

Figure 2-9.  The Miscellaneous Files folder in Visual Studio Solution Explorer

32


Chapter 2 ■ Configuring Visual Studio

Save documents as Unicode when data cannot be saved as CodePage: By default, Visual Studio sets the encoding of all new files to that used by the template used to create a given file, which should be UTF-*. If you check this option, however, new files will be saved in Unicode.

Extensions and Updates, Find and Replace, Fonts and Color These three next Environment panels offer few options. Extensions and Updates allows you to manage Visual Studio Gallery extensions. The Find and Replace dialog lets you choose informational and warning messages. By default, Visual Studio displays a message when the search reaches the starting point or when a replacement is done in a file that is not open. The last option in Find and Replace uses the text selected in the code editor as default text. Otherwise, if nothing is selected, the search term used is the last one searched by the user. Finally, the Fonts and Color options customize visual settings. Developers can set their favorite fonts, size, and color for almost every text in Visual Studio.

Import and Export Settings Visual Studio creates a CurrentSettings.vssettings file the first time you start it; settings are automatically saved in this file when Visual Studio is closed. Use the Import and Export Settings panel to work with this file: •

Automatically save my settings to this file: This option allows you to change where the settings file is saved. Settings recorded include all Visual Studio options and also Windows environmental details such as where panels are docked and pinned.

Use team settings file: Visual Studio allows a development team to share a settings file. When the Use team settings file option is activated, it allows Visual Studio to update its settings file with a team file. Any team member can change the team settings because Visual Studio keeps this very simple and allows you to use a .vssettings file on a network drive. To limit the ability of team members to change the file, you just have to set its write property to a specific team member.

■■Note  By default, settings are saved in the developer documents: %USERPROFILE%\Documents\Visual Studio 2013\Settings.

International Settings Visual Studio comes in a single language. However, it is possible to change the language by downloading a language pack. Languages are free to download at Microsoft websites. Once you’ve downloaded a pack, the International Settings panel lets you select from all installed languages. Language packs are about 1 MB.

Keyboard Visual Studio is equipped with default editing shortcuts. Every action in every menu can have a shortcut key combination assigned, and you can modify any default shortcut combination to one you prefer. The Keyboard panel in the Environment options (Figure 2-10) lets you choose any command and assign it a shortcut. It allows double combinations like Ctrl+K followed by Ctrl+C, which is the default for commenting a selection.

33


Chapter 2 ■ Configuring Visual Studio

Figure 2-10.  Creating a keyboard shortcut Finding the command name for your shortcut can be cumbersome at first. A trick is to use the Press Shortcut Keys text box (3) to see a current action (4). For example, Ctrl+F is the shortcut for searching a word in a document. Nevertheless, if you search for “search” (1), you will not find the command in the result panel (2). When you enter the shortcut in the textbox, Visual Studio discovers that it is assigned to Edit.Find. From there you can change the shortcut if you desire.

Quick Launch Chapter 1 introduced the Quick Launch feature; the Quick Launch panel gives you the following options:

34

Enable Quick Launch: You can disable Quick Launch in Visual Studio.

Show search results from previous search: Show previous searches in Quick Launch when the current Quick Launch is used.

Enable the following providers: You can individually disable any of the five providers: •

Most Recently Used

Menus

Options

Open Documents

NuGet Packages


Chapter 2 ■ Configuring Visual Studio

Startup The startup page can be configured in the Startup panel. The startup page is by default the page loaded when Visual Studio starts. This behavior can be modified. Three options are possible: •

The default startup page displays actions you can take: •

Create New Project

Open Existing Project

Open from source control

Automatically Open Last Loaded Solution.

Open Visual Studio Open Project Dialog or Open Visual Studio New Project dialog.

It is possible to modify the startup page to your own preference. A startup page is a WPF page. For a home page, you can use any HTML file you want. This is useful if you want to display messages to your developers. The Startup panel includes a combo box labelled At Startup that allows you to select which startup page to use. Consequently, to have multiple options, you need to install additional startup pages, either using the Extensions feature via the .VSIX file or by copying the startup page into the %USERPROFILE% \My Documents\Visual Studio 2013\StartPages folder. The startup page can be dynamic, and the Startup panel’s Download Content Every setting allows you to set the interval in minutes for clients on your network to download updated versions; you could thus greet team members with a “message of the day.”

Synchronized Settings Beginning with Visual Studio 2013, it is possible to sign in with a Microsoft account. This extends possible features like synchronizing settings between computers with the cloud, which means you can have your settings configured to all your computers within a few seconds. This solves many of the problems that can occur when changing computers or working on multiple computers. Developers want control over what is synchronized, so Visual Studio provides the Synchronized Settings panel to choose which settings to synchronize. For example, you may want to synchronize only your shortcuts.

■■Note The account used for synchronization does not need to be the same as for your TFS account.

Tabs and Windows The Tabs and Windows panel is divided into four sections: •

Tab Well

Pinned Tabs

Preview Tab

Tool Windows

35


Chapter 2 ■ Configuring Visual Studio

Tab Well division offers the following options controlling tabs: •

Insert new tabs to the right of existing tabs: By default, every new tab opens at the left of existing tabs. You can modify this behavior to open new tabs to the right.

Floating tab wells always stay on top: It is possible to dock floating documents on a separate monitor. If this option is unchecked in such a setup, a floating window will not appear over other windows when Visual Studio gets the focus back. When this option is checked, if another application appears over a Visual Studio floating window, that window will instead appear over the application when Visual Studio is activated again. The same option appears on the Tool Options panel.

The second division is named Pinned Tabs. It is possible to have two rows of tabs, as shown in Figure 2-11: one for pinned tabs and one for unpinned tabs.

Figure 2-11.  Two rows for tabs It is also possible to hide the pin button when the mouse goes over an unpinned tab. If “Show pin tab button” is checked, pinning a tab requires you to right-click and choose Pin Tab. Finally, Visual Studio can remember the state of the pin even if the document is closed. If “Maintain pin status” is checked, if you close a pinned tab and open the document later, the tab will remain pinned. The third division, Preview Tab, controls a new feature, added in Visual Studio 2012. It allows you to preview a file in a separate tab. This preview tab (Figure 2-12) opens files in a different container than the Tab Well. The preview area displays only one file, which stays open until something is modified in the file. When a modification occurs, the file is transferred into the Tab Well. If no modification is done on the opened document but another file is opened in the preview, then the first one is removed. This feature allows you to have a quick preview of a file without overwhelming your Tab Well with files. The “Allow new files to be opened” option lets you disable this feature but also select when the preview tab can be used. By default, the preview tab works when a file is selected in the Solution Explorer, or using the Find Result or Navigate To options.

Figure 2-12.  The preview tab

36


Chapter 2 ■ Configuring Visual Studio

Figure 2-12 shows at (1) a document in the Tab Well, at (2) the preview tab, and at (3) a button to promote the preview tab contents to the Tab Well. Finally, the fourth tab is Tool Windows. By default, tool tabs that are open but not active and not pinned are hidden but not their tab caption. Beginning in Visual Studio 2012, checking the “Show auto-hidden windows” option displays these tabs by hovering over the tab instead of requiring you to click, which is the default behavior. Figure 2-13 shows a hidden toolbar.

Figure 2-13.  A hidden toolbar that can be opened by hovering

Task List In the Task List panel, you have two Task List Options: •

Confirm Deletion of Tasks controls whether a confirmation dialog appears when deleting a task.

Hide Full File Paths controls whether the full absolute file path is displayed for each task item.

It is also possible to modify, delete, and add keywords for tasks in this panel. When the option screen is open, you click the token and then choose Modify or Delete. Figure 2-14 shows that tokens in the token list are interpreted by Visual Studio and added to the Task List.

37


Chapter 2 ■ Configuring Visual Studio

Figure 2-14.  A custom task token

Web Browser The last panel of the Environment options controls the Visual Studio internal Web Browser. Here you can change the home page URL and the search page. By default, this browser opens the MSDN Getting Started page, but you can change it to Bing.com or StackOverflow.com if you prefer.

Projects and Solutions The Projects and Solutions panel displays the same options as choosing Project or Solution in the Tools ➤ Options menu. The General area lets you set up different paths; you can set locations for templates and new projects and you can set the location of user project templates. Other configuration options for a project include disabling display of the error list when errors occur and tracking the active item with the Solution Explorer. This feature, when activated, automatically selects the active file in the Solution Explorer. Another option is about build configurations. If you do not want options to create all possible build configurations, including Debug, Release, x84, and x64, you can uncheck Show Advanced Build Configurations. The Solution Explorer displays the solution at the top of the project tree. If you want to hide the solution and instead view all of the projects directly, you can uncheck Always Show Solution, and the tree view will not show the solution node. However, this option has no benefit when your solution has more than one project. You also lose all context menu shortcuts to the solution. Since 2005, by default, Visual Studio automatically saves all projects when they are created. However, developers creating quick projects for testing might not want to have the project folder filled up with temporary projects. If the option Save New Projects When Created is unchecked, projects will not be saved automatically when created.

38


Chapter 2 ■ Configuring Visual Studio

Visual Studio warns users when they save projects in an untrusted location. This can be disabled, using Warn user when the project location is not trusted. Untrusted locations are any projects located on a Universal Naming Convention (UNC) path. This option may have been unchecked by the warning message. To enable this option again, you must go back to the Project and Solution options. Visual Studio raises the output window when a build starts. This default behavior can be turned off by unchecking Show Output window when build starts. Another automatic behavior is that Visual Studio displays a prompt message like that shown in Figure 2-15 when a file is renamed in the Solution Explorer, confirming that all references should be renamed. If you accept, the class name is renamed by the file name, and every reference to the old class name is renamed, too. By unchecking Prompt for symbolic renaming when renaming files, you can make this behavior automatic, removing the message and having all references renamed when a file is renamed.

Figure 2-15.  File renaming with the prompt for symbolic renaming The Projects and Solutions tab contains a second panel for Build and Run configurations. Its first option, maximum number of parallel project builds, concerns the number of parallel project builds. It is possible to set the number of processors that MSBuild will use when building. The number cannot be more than the number of CPUs in the computer. From this panel, it is possible to change some dialogs that prompt when Visual Studio starts a build or run, and you can change the verbosity for both the build output and the log file when MSBuild builds. The next panel is for a Visual Basic (VB) project. It specifies default values for the following: •

Option Explicit

Option Strict

Option Compare

Option Infer

In the Visual C++ (VC++) Project Settings you can set the search path, build logging, and build timing. You can create a log file when building and show additional information about task timing in the output window. In this screen, you can set the extensions to be hidden and configure the included VC++ file explorer. The Solution Explorer mode can be set to show only project files or every file. For Web Projects, your options are whether or not to build a project to run with the IIS Express 64-bit edition and whether or not to display a warning before running web applications when there are errors in the error list.

39


Chapter 2 ■ Configuring Visual Studio

Source Control The configuration of the Source Control pane changes dynamically depending on which source control plug-in you select in its first tab, Plug-in Selection. If you choose None or Microsoft Git Provider, no other tabs are available. If you choose Visual Studio Team Foundation Server, two tabs are available, to configure Source Control Environment settings and Team Foundation server settings. Figure 2-16 shows the Environment settings.

Figure 2-16.  Options for Source Control when Team Foundation is chosen as a plug-in In Figure 2-16 the source control environment is set to Team Foundation. Choosing this environment unchecks the four checkboxes. Another option is Independent Developer, which checks all four checkboxes. The last option is Custom, which allows you to change anything the way you prefer. Custom is automatically selected if you change anything in this panel. The Get everything when a solution or project is opened checkbox causes Visual Studio to call Team Foundation Server (TFS) with a GET operation. It retrieves every file that has changed since the last Get Latest Version command. Keep in mind that TFS deletes any checked-in files from your disk that have been deleted from the server. Files that have been renamed or moved on the server will be also renamed or moved to your disk. This mean that if you are not ready to synchronize when you open your solution and want to determine the best time to do it, uncheck that feature. Alternatively, if you like getting everything from the server when your solution is opened, then you should choose Check in everything when checking in a solution or project; it will save everything to TFS when the solution or project closes. When this feature is enabled, a check-in operation is executed to TFS. If Display silent check out command in menus is selected, Visual Studio Application Lifecycle Management (ALM) displays the Check Out for Edit Now command on the context menu if you right-click a file in the Solution Explorer. This avoids the Check Out dialog box. If it is selected, when you perform a check-in operation, Visual Studio

40


Chapter 2 ■ Configuring Visual Studio

keeps the files checked out. That is, the latest version of each working item is committed to Team Foundation version control, but you won’t have to check out the file to edit it again. The only way to release the check-out is to manually select Undo Changes. The last block of options is about checked-in files. Saving and Editing control Visual Studio’s behavior when saving or editing a file. By default, if either action is executed, the file is checked out by Visual Studio. But for either you can instruct Visual Studio to prompt whether to check out or do nothing. The setting Allow checked-in items to be edited allows you to modify files that are checked in (not checked out). This option is not required if you automatically check out a file when you edit it. Nevertheless, if you do not want to check out a file to edit it, you can set the editing to do nothing and check this option to be able to modify files. Of course, this requires you to check in and check out a file once you are ready to send your changes to TFS Source Control. The Visual Studio TFS tab has proxy configuration options that let you set a proxy server name and port. Additional actions like getting the last version of a file when checking it out can be configured through this tab. Deleted files are by default not shown in the Source Controller Explorer, but by choosing Show deleted items in Source Control Explorer, if desired you can show them. Having this option checked can create a large code base that may make your Source Controller Explorer hard to read. The last three checkboxes are checked by default: •

Solution Explorer Refresh automatically refreshes the source control status.

Prompt before check-in from Pending Changes window displays a prompt window before check-in from the Pending Changes window.

Automatically resolve conflicts when they are generated means that if TFS cannot automerge, then an entry for each conflict appears in the conflict list.

Text Editor Text Editor is the panel that developers spend the most time using. It is possible to configure most of the settings for all programming languages but also precisely for each specific language Visual Studio supports. Before going deeper into settings shared between languages, let us explore seven configuration options that are not language related: •

Drag and Drop Text Editing

Highlight Delimiter

Track Changes

All Languages

Settings

Scroll Bars

Tabs

Drag and Drop Text Editing should always be checked. It lets you select pieces of code and drag them anywhere in the file. This is useful to move code and it is also the default behavior in a lot of software. The second checkbox is Highlight Delimiter, for characters like parentheses or curly brackets. This should also always be checked. It helps you see where delimiters start and end. Figure 2-17 shows brackets with their background color changed.

41


Chapter 2 ■ Configuring Visual Studio

Figure 2-17.  Highlighted delimiters The Track Changes setting lets Visual Studio mark the left margin and the scroll bar with color markers for code modification, as illustrated in Figure 2-18. If the color is white, it means that nothing has changed while the file has been open. If the color is yellow, code has been modified. The color turns to green once the code has been saved.

Figure 2-18.  Track Changes in the code editor The next three configuration options control the display of the selection margin, which we see with Track Changes in Figure 2-18. It is possible to show or hide the margin selection and the indicator margin if Track Changes is enabled. Finally, Visual Studio can highlight the current line. The Text Editor configuration contains an All Languages subtree as well as subtrees for each supported language. For each subtree, you’ll see shared configuration options as well as those specific to the language. Figure 2-19 shows the C# subtree with the first node open. At (1) are the General settings and at (2) the C# settings.

42


Chapter 2 ■ Configuring Visual Studio

Figure 2-19.  Options for Text Editor The All Languages subpanel has the General, Scroll Bars, and Tabs settings in common with almost every language. These are the three settings panels that will be covered here. First note that Statement Completion means IntelliSense. Checking Auto list members triggers IntelliSense. The Settings options include the following: •

Enable Virtual Space should usually never be checked. It allows you to click anywhere in a file and start to type. This is an option you can enable if you are accustomed to coding with the ability to click anywhere in a file to type. Over the last 15 years, it has become more common for IDEs to treat the code window like typing in a document; you can only put your cursor after a character and not anywhere in the white space within a document.

Word Wrap allows you to wrap a line of code to a second line when it goes beyond the width of the screen. You can enable a visual image to indicate when a line is wrapped.

Line numbers are shown in the Visual Studio status bar, but if you check Line Numbers, they will always be visible to the left of the code editor.

Enable single-click URL navigation: You can choose whether or not to display URLs in comments with a clickable link.

Navigation Bar: For navigation within a file, the navigation bar can be visible or not. By default, it is visible and it adds under the Tab Well two combo boxes, which list all classes in the current file and all members and class variables.

43


Chapter 2 ■ Configuring Visual Studio

Automatic brace completion adds the ending character of any brace. For example, if you open a parenthesis, the closing parenthesis appears automatically.

Finally, it is possible to select and copy whitespace, which would paste nothing. If you want to prevent copying nothing, uncheck the option Apply Cut or Copy commands to blank lines when there is no selection. Otherwise, it will copy and paste an empty line. It is worth mentioning that if you have this option enabled and have nothing selected in the code, the current line will be copied. If you uncheck this option, copying an empty line would result in pasting the last clipboard contents (not the empty line).

Debugging The Debugging options control how Visual Studio behaves when attached to a process for debugging. The Debugging pane divides its setting into five panels: •

General Settings

Edit and Continue

Just-in Time

Output Window

Symbols

The principal settings used most often are under General Settings, Edit and Continue, and Symbols. First on the General Settings panel, if you are working with a multiprocess application, you may want to decide whether to break every process when one breaks. To do so, use the Break all processes when one process breaks option. By default everything is stopped, but you may want to continue with other processes. The option Enable Breakpoint Filters allows you to add a conditional breakpoint. I’ll explain conditional break points in Chapter 4, but before you can use the feature, this option needs to be checked. One major feature that is not available in Visual Studio Express is the Exception Assistant, a popup window that appears whenever a run-time exception occurs. In Express, the exception popup contains only the message error without any other information. But when you are using any other Visual Studio edition and enable the Exception Assistant option, you get an enhanced dialog showing the exception object, a description, troubleshooting tips, and online help. One of the most useful options is the Actions link. By clicking this link, you can get detailed information including inner exceptions, a stack trace, the source of the error, and so on. Another very important feature that you may want to adjust from time to time is Enable Just My Code. This option makes it less likely that your code will break, because you’ll only hit (and trigger debugging for) code that you have written. Sometimes, it is useful to step through any code, but sometimes it is more efficient to concentrate on your code only. Somewhat similar is the setting Enable source stepping into .NET. In some cases, going deeper into the .NET framework for debugging might be a useful option, but at other times it is not. Checking this option will automatically uncheck Enable Just My Code. This option uses the last panel debugging setting about symbols. Even if you have not yet configured this screen, Visual Studio will prompt you that you need to configure symbol locations. The reason is to be able to get the debugging symbol from Microsoft. Visual Studio allows you to reduce the level of depth you can reach by stepping over properties. Check Step over properties and operators if you do not want to go inside your getters and setters while debugging. This is desired in the case that your properties do not contain any logic. However, if you have code in your properties, you may want to continue to include them while debugging. Two features that should always be enabled are Require source files to exactly match the original version and Suppress JIT optimization on module load. The first setting instructs Visual Studio to compare the debugging code file to the running file. If they are not the same, a dialog will inform you that the code displayed is not the version

44


Chapter 2 ■ Configuring Visual Studio

being executed. Suppress JIT optimization on module load makes your debugging code slower because it is not optimized but provides a richer debugging experience. In fact, if you have optimized code and have the debugger debugging only your code, all optimized code will be considered not to be yours. The only time you should not have this feature checked is for very rare bugs that occur only when the code is optimized. Debugging has a second tab named Edit and Continue that allows you to edit and continue debugging. This feature works only on builds that are set to debug. It cannot be used with IntelliTrace; you must use one or the other. Also, to be able to use Edit and Continue with ASP.NET you must enable the option inside the web project property. Keep in mind that this feature will not work with Linq queries or dynamic variables. The last panel is Symbols. It lets you set a location for symbol (.pdb) files, such as the Microsoft source file. From this screen, you can set up where to cache your symbols. You can have them in a single directory that is shared for all your solutions. Figure 2-20 shows an example of what can be downloaded if nothing is in the cache.

Figure 2-20.  Symbols downloaded for a small ASP.NET MVC solution By default, a single location is set, Microsoft Symbol Servers. Often, adding http://referencesource. microsoft.com/symbols solves any missing symbol problem.

■■Caution Downloading symbols can take time when you don’t have them already cached.

IntelliTrace Configuration

IntelliTrace is discussed as a feature in Chapter 4. However, you configure it with Visual Studio Options, and I’ll explain that process here. First of all, it is possible to enable or disable IntelliTrace. This is important because IntelliTrace is resource-intensive, and it may not be a good idea to have it always running. When debugging, IntelliTrace can collect information from events or from events and call information. The IntelliTrace panel is the place to select which of the two types is active. It is possible to tweak Advanced IntelliTrace features like the Maximum Disk Space allowed per session of recording. File recording location can also be set in this settings panel. It is the place to allow the IntelliTrace panel to show the navigation gutter, to enable TFS symbol lookup and to prompt to enable source server support. In most situations, every one of these options should be checked.

45


Chapter 2 ■ Configuring Visual Studio

Whatever the IntelliTrace mode, you can choose which events to capture. Be aware that you can expand the IntelliTrace Events category for more accurate selection, as shown in Figure 2-21.

Figure 2-21.  Click the arrowheads to expand events To control the amount of information registered by IntelliTrace, you can specify which code module to get information from and which to ignore. It is possible to use the * character as a wildcard character. Only file names are compared to string patterns provided, not assembly names or file paths.

Performance Tools

On the Performance Tools panel, different options are available for every performance/profiling tool. The first one in the General category is Show Time Values as Clock Ticks or Milliseconds. Once the sampling is done, the Performance summary view appears in the main Visual Studio window; it is possible to change the number of functions shown. It is a good idea to keep the Automatically Serialize Symbol Information option checked. Serializing symbols merges them into a single .vsp file. Later, the .vsp file can be opened without having any references to the original traced files (.pdb, .dll, or .exe). Running a profiler takes a lot of resources, and Visual Studio allows you to select only your code for profiling. The Just My Code checkbox allows you to sample only your code base. Consider using this option if your code does not have contain “Microsoft” in the copyright string or if the module name is the same as that of the module generated by building the project in the current solution. It is possible to show one level of non-user call functions and also one level of non-user caller functions.

46


Chapter 2 ■ Configuring Visual Studio

Performance Tools has predefined rules that can be disabled and enabled. Using the Rules panel, you can redefine the action for a given rule between Error, Warning, Information, and disabled. As Figure 2-22 shows, the grid of rules includes an ID that provides a shortcut reference to a given rule as well as a Title column. Checkboxes, labeled (1), allow enabling or disabling a rule. However, it is also possible to disable a rule by changing its action directly in the drop-down menu (2), where you can select any other type of action.

Figure 2-22.  Performance Tools rules

Database Tools Visual Studio comes with some database tools. It is possible to see views and tables in a designer. One option is Warn when changing schema. Another option, Issue the SET statements that ensure commits succeed, should remain checked. The second group of options is about scripts and stored procedures. A DML Marker setting allows you to select and edit blocks of SQL with the designer instead of only allowing the modification in the SQL panel. This feature should also always be enabled because it gives more functionality and lets you avoid switching to another panel for editing SQL. When dropping a SQL file to a database, a reference executes the file automatically. If you want to be warned before executing any dropped SQL file, you can enable Warn when executing a script or query when dropping it on a reference. This option should be removed only if you attempt to do an intensive period of trusted SQL file manipulation. Otherwise, it is safer to have a prompt window warn you before executing any script whose contents you may or may not know. In the Data Connections screen you can set two options. The first is the Number of Rows displayed by a SQL query; by default, no limit is set. The second is the default SQL Server Instance name. Beginning in Visual Studio 2013, the default value is (LocalDB)\v11.0. If you are using SQL Server Express, you can change the instance name. The third panel contains a single configuration, Pluralization of names, which allows automatic pluralization of English names of objects.

47


Chapter 2 ■ Configuring Visual Studio

The fourth panel controls the behavior of the Query and View Designer screen. The Query and View Designers panel is the place to set a time-out for long queries; 30 seconds is the default value. Some visual settings are available, including default panels to be shown in the Query and View Designer. You can also choose a Default Query Type: •

Select

Delete

Insert

Make Table

Update

Select is the default option. The fifth and last panel, Table and Database Designers, controls the Table and Database Designer. Like the Query and View Designer, it allows you to define a time-out in seconds. From the designer it is possible to generate a change script that contains SQL statements. This can be used later to build all types of code outside Visual Studio. If you are using this feature often, you can have the script generated automatically. The three next options are about warning messages. You can be warned if null primary keys are defined, if a difference is detected, and about affected tables. Differences can be detected if you are working on the same table in multiple designers or if the table has been changed outside Visual Studio. The Affected Tables dialog displays a listing of all tables that will be changed by the running script. Other options include the default view for the designer and the default Column Type and other Column Attributes, as shown in Figure 2-23.

Figure 2-23.  Table and Database Designer default column attributes

48


Chapter 2 ■ Configuring Visual Studio

HTML Designer The HTML Designer tab is only for ASP.NET Web Forms. It is not available for ASP.NET MVC files or static HTML files. Figure 2-24 shows (1) the HTML Designer option selected. The display at (2) shows how to know if the designer is activated. We can see that this one is activated because an .aspx file is open. You can specify which view will be displayed when a file is opened, using the Start Pages In setting. Source View shows only ASP.NET and HTML markup, and Design View shows the code rendered.

Figure 2-24.  HTML Designer option and designer The next HTML Designer options are checkboxes. Assign unique IDs to new tables is about the assignment of unique identifiers to pasted tables. If unchecked, the pasted table will continue to have the same ID as the copied one. Auto Keyboard Switching controls whether the keyboard automatically switches to the language where the cursor is. If you’re only using one language (as when you’re doing all development in English), it does not matter whether you have this checkbox checked. Split Views Vertically is about the Split button, which you can see at (2)in Figure 2-24, between the Design and Source buttons. It allows you to use the designer with the design mode and the source mode available at the same time, splitting the screen vertically instead of horizontally. This option is useful if you are using a widescreen monitor. HTML Designer’s options are divided into several subpanels. Two are for the generation of CSS (CSS and CSS Styling), which can be set for different HTML elements either inline or by classes. Another subpanel is Ruler and Grid, where Visual Studio lets you define a unit, spacing, color, and style for every HTML element. Finally, View is the panel where all the HTML Designer colors are defined.

49


Chapter 2 ■ Configuring Visual Studio

Package Manager The NuGet Package Manager extension lets you browse for cached packages and clear them. The location for cached packages is %UserProfile%\AppData\Local\NuGet\Cache. The General tab of options for the Package Manager lets you specify whether to allow NuGet to download missing packages. It also lets you specify whether Visual Studio must do that when building code. It is very important to check Allow NuGet to download missing packages because many open source projects do not have the package itself in the public repository but just the definition of the package required. This approach allows the posting developer to have a smaller repository footprint and to have users download the package directly from NuGet. However, to have only the definition of package, the solution must have been set to have NuGet Package Restore enabled. Chapter 3 will explain the use of NuGet. What is important to understand here is that we can instruct Visual Studio to download missing packages automatically. The Package Sources panel is shown in Figure 2-25. Here you instruct NuGet where to find packages to download. You can have multiple package sources. You can provide a URL or a folder path on your hard drive or a shared folder. The flexibility that Visual Studio and NuGet offer makes it simple to create a personal repository. This is an efficient way to test a custom package without having to deploy it. Shared folders can be an excellent way to share private packages across a business.

Figure 2-25.  NuGet Package Sources options At the top of Figure 2-25 are four buttons (1) that represent the possible actions you can take. You can add a repository path (+),delete the selected repository (X), or move it up or down. There is also a list of available package sources (2). You can uncheck any package source that you want to disable temporarily without having to remove the package from the list.

50


Chapter 2 ■ Configuring Visual Studio

At (3) is the Machine Wide Package Sources list, which comes from the ProgramData folder and can be configured as shown in Figure 2-26. Third parties can add NuGet configuration files under this directory to register a custom package source for their products.

Figure 2-26.  Machine-wide configuration

■■Note It is important to know that when you select a directory, NuGet Manager will recursively go inside folders and get every .nupkg.

Import and Export Settings The Tools menu has an action called Import and Export Settings. The Import and Export Settings Wizard offers three possible actions to the user, as shown in Figure 2-27: •

Export Selected Environmental Settings

Import Selected Environmental Settings

Reset All Settings

51


Chapter 2 ■ Configuring Visual Studio

Figure 2-27.  Import and Export Settings options Export Selected Environmental Settings exports the current settings. This option navigates you through a list of options that let you choose which settings to back up. All the options covered in this chapter can be exported. The result of exporting is a .vssettings file that contains XML with all differences between the default values and the customs ones. Import Selected Environmental Settings is the reverse process. It takes the .vssettings and sets Visual Studio settings from the configuration file. This process is called importation. Finally, the third option allows you to Reset All Settings.

Project Properties Every project has properties. Depending on the project type, properties can change, as shown in Figure 2-28. This allows you to have specific properties set by project instead of across Visual Studio. Project properties can be viewed by right-clicking a project or by going to the Project menu and selecting Properties.

52


Chapter 2 ■ Configuring Visual Studio

Figure 2-28.  Different panels for different project types Some panels are similar, as they all have Application/Library, Build, Build Events, Debug/Web Resources, Settings, Signing and Code Analysis subpanels. This section will focus mainly on these shared settings.

Application/Library The Application or Library panel is common to every project type. Every project needs to know what its assembly name will be once compiled. Most of the time, the assembly name should be the name of the project. In fact, that is the default for the assembly name. The project name is also the Default Namespace name, another property that can be defined in this screen. The next common property is the Target Framework. It lets you specify what framework the compiler must use. The target framework is a list of all installed frameworks on the developer’s computer. As shown in Figure 2-29, it is possible to choose any .NET framework from 2.0 to 4.5.1.

53


Chapter 2 ■ Configuring Visual Studio

Figure 2-29.  Application settings in the Project properties Finally, it is possible to select the Output Type and assembly information. The choices are •

Class Library

Console Application

Windows Application

Class Library is for all project types except WPF applications, Win Form applications, or Console applications. WPF and Win Form projects are Windows Applications, while Console is a Console Application. The assembly information comprises all information that is written in the .dll property. It is possible to write a title, a description, a company name and information concerning copyright and version. The lower part of the Application/Library panel contains a Resources division. The application’s icon can be set as with a manifest file. Manifest files are mandatory for almost all project types except class libraries, web projects, and unit test projects, none of which can have a custom manifest. A manifest file is an XML-formatted description of the application that can be embedded into the binary. This enables applications to be executed side by side after they are deployed. Manifest files were used in the past to give the Windows XP look and feel to application controls. Since Windows Vista, manifest files can be used to specify elevated permissions required for User Access Control (UAC).

Build Use the Build panel to specify a build configuration. It can be set to Debug or Release or to custom builds. It is possible to target 32-bit or 64-bit applications with the platform target. Another configuration that is often set is the output path and XML documentation. You can set where the build files will be created. Also, if you want to have XML documentation, it is possible to enable this feature in this screen.

■■Note  X86 is for 32-bit applications, and X64 is for 64-bit applications.

Build Events The Build Events panel lets you set commands to be executed before and after the build starts. Build events are a technique that you might use to clean directories, move files, or start third-party tools. For example, you could create web page help from XML documentation generated; this could be a post-build event that takes the XML-generated file and passes it to software that generates HTML.

54


Chapter 2 ■ Configuring Visual Studio

Debug/Web The Debug/Web panel controls the action performed when an application starts. Visual Studio allows you to start the project itself or to start an external program or URL. It is possible to set command line arguments and to specify the working directory of the environment. With any application type except a web application, you can specify a remote machine. The Use Remote Machine text box lets you specify by name the computer you want to debug.

■■Note The remote computer needs to run the Remote Debugging Monitor to allow Visual Studio to start the remote debugging. Under the remote machine name, checkboxes allow you to enable native code debugging, to enable SQL Server debugging, and to enable the Visual Studio hosting process. Debugging native code is not available for the Express edition. The Enable SQL Server option allows you to debug SQL procedure code within Visual Studio. The Hosting Process setting improves the debugger performance and enables additional features. For example, suppose a console application sends diagnostics to the Visual Studio Output panel. Figure 2-30 shows vshost.exe in the Process Manager, which indicates that Visual Studio runs the application in a hosting process. Having a hosting process allows you to use the Immediate panel without having to run the application.

Figure 2-30.  Hosting processes

Resources The Resources tab lets you open the Resources.resx file, located under the project’s Properties. It lets you write strings but also provide an image, icon, or text file for the project. Figure 2-31 shows the two ways to access the Resources.resx file.

55


Chapter 2 ■ Configuring Visual Studio

Figure 2-31.  The Resources tab and Resources.resx file share the same data

Signing Options you can configure in the Signing panel depend on the project; some fields are disabled in some project types. The WPF and Win Form types have ClickOnce Manifest enabled, which allows you to check the signing of the manifest. This option is disabled for class library, web application, unit test, or portable class projects. It is required if ClickOnce technology is used for deployment. It assigns a key to the software that can come from the Store or a .pfx file, or you can create an “on-the-fly” certificate file for testing purposes. The purpose of signing ClickOnce is to verify that any future updates come from the original publisher. Under the Sign ClickOnce Manifest section is the Sign Assembly section. This section is available for any type of project and allows you to attach a certificate (.pfx file) to an assembly. As with ClickOnce, the goal is to ensure authenticity—in this case, not that of the publisher but of the .dll file. This is required if you want to put the .dll in the global assembly cache (GAC).

56


Chapter 2 ■ Configuring Visual Studio

Code Analysis

Visual Studio Professional, Premium, and Ultimate versions can run code analysis when a project is built. In the Code Analysis panel you can choose a Rule Set to be run and also whether to Enable Code Analysis on Build. By default, it is not enabled. Warnings and errors are shown in Visual Studio’s Error List. Figure 2-32 shows at position (1) whether code analysis is running on the build. Clicking at (2) opens the rules. From here, it is possible to check and uncheck any rule in the set. It is possible to change the action associated with a rule. By default, most rules are set to Warning, but it is possible to block a build by setting the action to Error. Nevertheless, several sets are already built. From the drop-down, it is possible to choose a set and to configure it.

Figure 2-32.  Code analysis enabled with a rule set open

57


Chapter 2 ■ Configuring Visual Studio

Summary This chapter has covered most of the options that can be configured in Visual Studio 2013. You have seen environment options that touch every global feature, along with project and solution options that are targeted more to the type of work, and you’ve seen how to back up every setting and load them later. In short, you’ve seen that you can modify Visual Studio to be not only a tool to work with, but a tool that works for you.

58


Chapter 3

Development Tools This chapter contains information about Visual Studio 2013 from the perspective of development. I’ll discuss the code editor, also known as the editor window, for several languages, and I’ll show how to navigate Visual Studio. This chapter will help to improve productivity in your day-to-day work. Briefly, you will see how the documentation works when you develop your application and how Visual Studio allows you to publish your code. Finally, you will learn about NuGet, which is now the principal way to handle references.

The Editor Window The editor window is the screen that developers work with most of the time while coding. This window adapts its contents to reflect the project types and file types you’re working on. The Visual Studio editor window is convenient to have as a code editor when it is time to edit code, but it is also powerful enough to provide a visual editor for the designer in some situations. The code editor lets you write code; whereas the visual editor lets you move visual controls but is not available for every file type. The editor window has many familiar features, like IntelliSense for C#, JavaScript, and CSS, but it also includes new features in 2013 like Code Lens and Peek Definition. This section discusses all these features, as well as Go To, the Razor, the Database Panel, the Report Designer, and the WPF editor. You’ll also learn how resource files work.

C# IntelliSense Visual Studio has the capability to enhance your code editing through IntelliSense. As you saw while setting up the configuration in Chapter 1, Visual Studio procures dynamic information while you’re typing. For example, by default, it lists all members of a class when a dot is typed after a variable name. This IntelliSense member list feature can be trigged manually by pressing Ctrl+J or by choosing Edit ➤ IntelliSense ➤ List Member. In the code editor, once IntelliSense has displayed a list of possible values, you select a value by pressing Tab or the Space bar. As discussed in Chapter 1, the combination of the member list and the parameter info creates a huge benefit for C# over most other Visual Studio code editors. It allows the developer to get information that is available somewhere else, such as another class, using only a few keystrokes and without leaving the editor. Likewise, the list of parameters for every method is available. Even if the method is overloaded, Visual Studio detects which one you are using. In addition, Visual Studio autocompletes any variable, command, or function name. After you type a few letters in the editor, Visual Studio can detect the whole word and suggest you complete it by pressing Enter. If Visual Studio does not provide any suggestions, you can use the Ctrl+Space shortcut to ask Visual Studio manually for a suggestion.

59


Chapter 3 ■ Development Tools

JavaScript IntelliSense Before Visual Studio 2012, all IntelliSense features were available for C# and Visual Basic. Since version 2012, Visual Studio has extended its powerful IntelliSense to JavaScript. The JavaScript implementation of IntelliSense provides list members and auto-completion, like the C# version. This is also true for third-party JavaScript; Visual Studio reads all JavaScript that your solution contains and figures out basic elements like variables and functions. Figure 3-1 shows information with IntelliSense about JQuery. The experience is enhanced with JQuery because Visual Studio has a file called jquery-{version}.intellisense.js, supplied with the jquery{version}.js file. It contains all the definitions needed to allow Visual Studio to provide it. This file is contained in the web project but is never used in any ASP.NET View. It resides in the project only for the purpose of giving Visual Studio information about JQuery to IntelliSense.

Figure 3-1.  The third-party JavaScript library can have IntelliSense An external definition file is not required for your own JavaScript files, because you can comment directly inside your code. Figure 3-1 displays the list of functions available for the selected HTML element with information displayed as comments on the right. To activate the documentation feature in your own code, you must add comments with the same C# syntax. The triple slash (///) identifies the comment to Visual Studio so that it can be displayed in IntelliSense. However, in the figure the comment is not over the signature of the method but within the function. This is the only difference in the commenting method compared to C#.

■■Note  If you do not want to clutter your JavaScript file, you can do like JQuery and provide an IntelliSense file that has all functions documented without code in it. Figure 3-2 shows an example of the syntax with the triple slash (///). As with C#, a summary tag, a parameter name tag, and a return type can be inserted. When these types of comments are not provided, Visual Studio shows only the member name without any other information. This is the case for libraries like BootStrapper, for which only members are shown in the member list, without details.

60


Chapter 3 ■ Development Tools

Figure 3-2.  IntelliSense with a JavaScript function It is also possible to have comments for variables that reside in the JavaScript closure. The use of the triple slash (///) is required and must be followed by an attribute field name. Figure 3-3 is an example that documents the variables v1 and v2.

Figure 3-3.  JavaScript IntelliSense with a variable

61


Chapter 3 ■ Development Tools

CSS IntelliSense The CSS editor window also has been improved. It is now possible to have IntelliSense in ASP.NET MVC views. The list of available classes appears when you type some letters. Figure 3-4 shows IntelliSense with Bootstrap classes when the three letters col have been typed.

Figure 3-4.  Visual Studio showing a third-party CSS class Not only has CSS editing been improved in ASP.NET MVC views, but also in CSS files. The code editor for CSS is richer with support for CSS 3. When you type a few keystrokes within a CSS class, IntelliSense pops up with a standard tag. Figure 3-5 is an example of typing only back and seeing all CSS valid tags that start with these letters.

Figure 3-5.  CSS IntelliSense

62


Chapter 3 ■ Development Tools

Code Lens

Visual Studio 2013 Ultimate Edition adds indicators over every method, a feature known as Code Lens. It adds information about the health of the method by showing the number of unit tests that pass (1)compared to those that fail, and also showing what happens inside the source control. Code Lens is divided into three functionalities. The first is to show all references used by the method. In Figure 3-6, (2) shows references. Code Lens is available for classes, properties, and methods.

Figure 3-6.  Code Lens showing references and test status Figure 3-7 shows the result of clicking a References link. Every reference is grouped by files. Clicking any line will navigate to the source that calls the class.

Figure 3-7.  References open

63


Chapter 3 ■ Development Tools

At (1) in Figure 3-6 is a passing test. This is the second functionality of Code Lens; you can also open it in the same way that a reference opens when you click it. This time, unit tests are shown with the time elapsed and the result (pass or fail). The third functionality is available only when using Team Foundation Server (TFS) 2013, and it shows the name of the last person who commit. Like the two previous Lens indicators, this one can be clicked to see the history of the file. This new feature does not slow down the main process of Visual Studio; it runs asynchronously.

Peek Definition

Peek Definition is a small window that opens under the chosen code that displays the code that is called by the method. The Peek Definition window can be open when your cursor is over a method or properties. Pressing Alt+F12 or right-clicking and choosing Peek Definition opens the Peek Definition tool. Figure 3-8 shows a definition of a function. You can see that the window shows the relevant part of the file in question. The top-right part of the Peek Definition displays the file name, with icons for two possible actions. You can open the peek into a full file in the code editor or close the Peek Definition. You can also close the peek using the Esc key.

Figure 3-8.  Peek Definition opens for a method named TemplateForComponentA In addition, you can edit the code within the Peek Definition window, allowing you to make quick modifications without losing your concentration. You can go deeper into a definition, by choosing Peek Definition when you are already within the Peek Definition at the top of the hierarchy. The top Peek Definition will display a dot within the title that represents the depth of the Peek Definition.

64


Chapter 3 ■ Development Tools

Go To Features The editor window has two Go To features: Go To Definition and Go To View. The Go To Definition feature is available anywhere within C# code. To use it, click a method, right-click, and then choose Go to Definition. The shortcut for this is F12. For the Go to Definition, move to the source of the code that you are selecting. For example, if your cursor is on a constructor of a class, Visual Studio will open the class and set the focus on the constructor. Go To View is only available with the ASP.NET MVC controller class. If you right-click the return statement View of any controller, you can select Go to View. This opens the .cshtml file that represents the view returned by the controller. A shortcut is to press Ctrl+M, Ctrl+G.

Razor Razor is the most popular view engine for an ASP.NET MVC project. When you create a new controller, no views are created by default. Visual Studio helps you create a Razor view by right-clicking anywhere in the controller action and choosing Add View in the context menu, as shown in Figure 3-9.

Figure 3-9.  Choosing Add View for a controller In the resulting window, shown in Figure 3-10, you can choose a view name and a template from a list of possible predefined templates. For example, you can choose an Edit template that will create all editable controls depending on the Model class selected from this wizard. At (1) you can enter a view name. This will create in the View folder a file name with the extension .cshtml. At (2) is a drop-down that lets you choose a template. Finally, at (3) is an all-model class list that is available in your solution. If you have created a brand-new model class, you must compile the project before you can see the class in the drop-down.

65


Chapter 3 ■ Development Tools

Figure 3-10.  Using Add View to create a Razor view The Add View window automatically creates the model object link. It binds every property of the model into HTML input in the Razor. Figure 3-11 shows the result of adding a Razor view from the controller action.

Figure 3-11.  A view generated by Visual Studio

66


Chapter 3 ■ Development Tools

At (1) is the file that has been generated. The name is the one specified in the Add View window. At (2) is the type of the model, also from the previous window. Finally, (3) shows two properties contained in the model. Visual Studio has automatically created the inputs and validation controls for every property. From here, it is possible to customize the view. A new feature in the Razor editor of Visual Studio 2013 is the list of attributes, which are grouped by prefixes. Visual Studio shows only the prefix and, when one is selected, expands all possible values. Figure 3-12 shows the ng- prefix that collapses all ng-… attributes. This powerful feature removes many irrelevant possible values.

Figure 3-12.  A collapsed attribute

The Database Panel Visual Studio has a panel for setting up a connection to a database used in your project development. To open this panel, select Tools ➤ Connect to Database. This lets you choose the data source and server name. You must identify the type of authentication that will be required. You can choose between Windows Authentication and SQL Server Authentication. The last step of this panel is to connect to a database on the selected server. Once you’ve configured a connection and choose Server Explorer, its panel opens with all data connections available. This means that if you have previously configured a connection, you do not need to configure everything again. Figure 3-13 shows the Server Explorer as it opens with a connection to the database named WorkoutPlanner. The server is a localdb, which means that you do not have to connect to a full SQL Server database.

67


Chapter 3 ■ Development Tools

Figure 3-13.  The Server Explorer has tables, views, stored procedures, and so on Visual Studio has a designer for every element (table, view, stored procedure) that a database can have. For example, Figure 3-14 shows the Table Designer. You can open it by double-clicking the table in the Server Explorer.

Figure 3-14.  Visual Studio table definition designer At (1) is a grid containing all the columns of the table. It is possible to add, remove, and modify any name or data type, and to mark whether a column can be null. At (2) is a panel listing all table properties, including primary keys, foreign keys, constraints, and triggers. The last panel (3), is the SQL code editor that generates the table. Modifying the data from any panel updates all others on the panel.

68


Chapter 3 ■ Development Tools

It is also possible to right-click a table and select Show Table Data. By default, 1,000 rows can be shown. This view displays data but also allows for the editing of data directly within Visual Studio. Figure 3-15 displays four rows of a table. You can see the context menu open from a single table. It allows you to add a new table or trigger, open an editor for a new query or a table definition (see Figure 3-14), and finally, display the table data.

Figure 3-15.  Visual Studio database editor shows the table data The top bar lets you refresh the data and the number of rows to display. The icons Script and Script to File both give you SQL statements to insert data. The first opens the SQL editor, and the second outputs the SQL to a file.

Report Designer The Visual Studio Report Designer provides a user interface to generate reports. To create a new report, create a new project and select the type Application Report. Figure 3-16 shows the first step of the configuration wizard. Reports can have different data source types.

Figure 3-16.  Data source configuration for a report in Visual Studio The next step is to create a data set. Visual Studio takes you through several steps to do this. The Data Source Wizard has a user interface for dataset properties, and a unique user interface for arranging fields; you can also choose a report style. All steps become available only if you choose the Application Report or if you decide to add an item to an existing solution with the Report Wizard item. After some time, you may want to create a new report without using the wizard. For this, add a new item and select Report. The Add New Item window is shown in Figure 3-17.

69


Chapter 3 ■ Development Tools

Figure 3-17.  Visual Studio items for a report Selecting the Report item creates an .rdlc file. Double clicking an .rdlc file instructs Visual Studio to open the Report Designer, which consists of the report data panel. Figure 3-17 shows the report data at the left. At the right is the designer. Items from the left side can be dragged to the right side. At (1) in Figure 3-18 are the built-in fields. These fields are general items that are dynamically generated at runtime. They can include the page number, the languages that the report is open to, the total amount of pages, or similar information.

Figure 3-18.  Report data and Report Designer

70


Chapter 3 ■ Development Tools

Below the fields are the parameters (2). Parameters allow for supplying information that can be used by a data set. Images can also be added in the report data. The other report data section (3) contains every data source. A report can have several data sources used in a data set (4). Additional items can be dragged to the designer from (5) the toolbox panel. This allows using labels or other visual components. Visual Studio Report Designer has some limitations. First of all, it is not possible to change the Data Set query other than specifying fields of a single table. If you want to use a view or multiple tables with joins, then you are out of luck. If you want to create this type of report, it is best to use Microsoft SQL Server Report Builder. This can be downloaded for free on the Microsoft website. Figure 3-19 on the left (1) shows the Visual Studio properties window for a dataset. On the right (2) are the Report Builder dataset properties. The comparison is obvious.

Figure 3-19.  Left, Visual Studio Report Designer data set properties; right,Report Builder properties The Report Builder allows you to choose between three query types. The first is Text, which is not an option in Visual Studio. The second choice is Table, which is the only option available in Visual Studio. The third is to call a Stored Procedure directly. However, Visual Studio 2012 and earlier could open a report created by Business Intelligence if the Business Intelligence templates were installed. Visual Studio 2013 can open Business Intelligence reports by downloading the SQL Server Data Tool at www.microsoft.com/en-us/download/details.aspx?id=42313.

The WPF Editor Visual Studio 2013 has a special editor for a Windows Presentation Foundation (WPF) project. In fact, the WPF editor is the same as in Visual Studio 2012 but with some enhancements. First, data binding is improved with a better IntelliSense. Performance is improved with an IntelliSense that works faster with the XAML Designer. Before 2013, the editor would constantly freeze after typing only a few keystrokes. Additionally, the WPF XAML editor uses the data context to provide a list of members that are coherent for the context. This works in both the resolved-data context and the design-time–data context. So far, all of the enhancements mentioned involve IntelliSense, but the WPF editor has other new improvements as well.

71


Chapter 3 ■ Development Tools

Visual Studio 2013 also provides better navigability with the Go To Definition action. You can choose this tool in the WPF editor by using the context menu, or simply use the shortcut key F12. Using this feature when the focus is in a resource in XAML navigates to the definition of the resource. You can also use this feature on a binding expression. Activating this feature on a binding navigates to the property that is bound to the XAML in the model class. IntelliSense is available for the resource. Working with a resource is easier because moving between files to complete a reference is not required. Visual Studio looks up resources in the project and shows all entries in the list of members. Another new feature with Visual Studio 2013 and XAML is the ability to use code snippets. While this feature is available with several other languages in Visual Studio, it is new for XAML. Code snippets are available in two types, Insert Snippet and Surround With. To have code snippets triggered, right-click anywhere in the XAML editor and choose one of the options in the context menu. Figure 3-20 marks with two arrows the snippet actions. Default shortcuts for both code snippets are Ctrl+K, Ctrl+X or Ctrl+K, Ctrl+S.

Figure 3-20.  The XAML code snippet Choosing Insert Snippet adds XAML code at the current location depending on the snippet chosen. Choosing Surround With adds XAML code before and after the current code selected. The WPF editor enhances XML comments. XAML uses XML syntax, and this causes problems with nested comments. When you use the comment button or the shortcut to comment on XAML code, the editor is now intelligent enough to encapsulate the code with XML comments. Figure 3-21 (1) shows a single comment block. If you re-select the grid element from the start to the end and use the comment action, the code is transformed with multiple comment blocks and is still valid XML. The resulting code is shown at (2).

72


Chapter 3 ■ Development Tools

Figure 3-21.  XAML commenting code that already contains comments The WPF editor and IntelliSense also provide autocomplete support when you type in a few characters, like any other IntelliSense. With XAML IntelliSense, however, you don’t need to provide all the letters. For example, if you want to select from a list the word AutoToolTipPlacement, you could limit the typing to Auto. IntelliSense provides everything that starts with these letters. Additionally, you could also write AutoToPla. This is called Fuzzy Matching. Thus, it is possible to provide only the capital letter of a name. For example, ATTP selects AutoToolTipPlacement. This is called CamelCase matching. The example is shown in Figure 3-22.

Figure 3-22.  IntelliSense with a smart keystroke combination Finally, IntelliSense searches for a string within all strings. This means that to get AutoToolTipPlacement, you could write ToolTip, and it will get every possible value that contains ToolTip. As you can see, Visual Studio 2013 and the WPF editor enable you to efficiently select specific existing elements.

73


Chapter 3 ■ Development Tools

Furthermore, the XAML Designer now works with tags in a way that formerly only the HTML editor did. This feature automatically modifies the ending tag characters when the starting tag is altered and vice versa. For example, if you have a <StackPanel> starting tag, you can edit it by pressing the Backspace key to make it <StackPa>; then the ending tags will become </StackPa>. The tag features are now synchronized. This provides a huge benefit; you can edit one instance and have everything adjusted automatically, and you won’t forget any corresponding tags. Visual Studio 2013 cleans up tags that are not useful by removing an ending tag. For example, if you have <AutoToolTipPlacement></AutoToolTipPlacement> and you go into the start element and add a backslash to close the tag, it will automatically erase the ending tag. This will produce <AutoToolTipPlacement/>.

Resource Files Resource files have not changed in a few years. They are shared between all .NET projects. The goal of a resource file is to set the translation of words in different languages. To create a resource file, choose Visual C# ➤ General ➤ Resource File. If you are using VB.NET, this new file type is under General ➤ Resource File. These Resource Files end with the .resx extension. The .NET framework uses the System.Threading namespace to get the current thread UI culture and to resolve which resource files to adopt. To do the mapping, you need to name each resource file with its target language. If a file does not have any language reference, it is a global resource file. For example, you can create a House.resx as a default fallback for any language not defined. Then, you can add House.fr.resx for French culture, which defines only the relevant resources. The .NET framework is smart enough to use the default file if the specific resource is not found. For greater precision, you can even specify the country. Microsoft .NET searches from the most specific to the most general. Figure 3-23 shows the priority cascade. First, .NET searches for the House.en-US.resx file within the House resource with a language and country. Then, if it finds nothing, it searches for only language, House.en.resx. In the example, the culture is set to English. No resource has EN for a language, so the search falls back to House.resx.

Figure 3-23.  Resource priorities Resource files are not used only for strings. Visual Studio has a drop-down menu that contains Strings, Images, Icons, Audio, Files, and Other. Figure 3-24 illustrates (1) this drop down. The default value is Strings. It is the resource type that is most used in every project. This same figure shows that when images are added in the resource file, they are automatically added to a Resources folder. Images can be of type .bmp, .png, .jpeg, .tif. or .gif.

74


Chapter 3 ■ Development Tools

Figure 3-24.  Images in resources Like strings, all resources use the same mechanism for the language and country. This lets you have audio files in the desired language. Images could have text, a flag, or any specific mark corresponding to a specific culture. To use the resource file in any code file, you need to change the access modifier. To modify this property, you must open the default resource file. This is the one without a culture set in the file name. Visual Studio gives you two ways to change this property. First, you can open the resource file and select Public or Internal as Access Modifier. The drop-down with these options is located at the top of the resource file, as shown in Figure 3-25.

Figure 3-25.  Visual Studio access modifier The second way to change the default resource is to select the file in the Solution Explorer and open the Properties panel (F4). Figure 3-26 shows the Properties panel open for the default resource. The Custom Tool is set to PublicResXFileCodeGenerator, which creates a .Designer.cs file under the resource file. This creates a file with a public static property that uses the ResourceManager class to get resources for you.

75


Chapter 3 ■ Development Tools

Figure 3-26.  Visual Studio properties and custom tool

Navigability Navigability is essential for moving efficiently between all your classes, files, or class methods. To improve your productivity, this section explains how to navigate inside your solution easily.

Solution Explorer Class Navigation The Solution Explorer has new navigation capabilities for classes. It allows searching by the options Base Type, Derived Type, and Is Used By, all of which are new in Visual Studio 2013. All of these options are located in the Solution Explorer panel. To activate any of them, you need to right-click a class. Classes have a .cs file extension for C# and .vb for Visual Basic. You can expand a class file by clicking the disclosure triangle at its left. Once a file is expanded, all of its classes are listed. Often, only one class is shown, since it is logical to have one class per file. Figure 3-27 illustrates a single file named Workout.cs (1). At (2) is a single class in the file and at (3) the three features for class navigability.

Figure 3-27.  Navigability of classes

76


Chapter 3 ■ Development Tools

The first new navigability feature is the use of base types. When you click Base Types, the Solution Explorer moves the selected class to the top. Listed under the class are all classes that inherit from it. Figure 3-28 shows the result of choosing Base Types. The first line shows the name of the class, identifying it as a Base Type. Under this class, you have two elements. One is the inherited class, called BaseModel in the example. The other is an interface called IUserOwnable. From this result panel, you can go deeper by right-clicking again and choosing one of the three search features: Base Types, Derived Type, or Is Used By.

Figure 3-28.  Result of the Base Type The second feature, Derived By, is the antithesis of Base Type. That is, if you execute this action on a base class, you will get all the classes that inherit from it. For example, executing this command on Figure 3-28’s BaseModel displays all classes that inherit the trait from BaseModel. Of course, the Workout class is in the list, but so is every other class that inherits from it. The third feature, Is Used By, should be the feature that returns the most entries. Every time a class is declared and used in a parameter, or every time it is used in a generic declaration, it will be shown in the results. Figure 3-29 shows an example of a list of results. Each entry shows the name of the file, the line number, and the column, along with the line of related code. This feature is more exhaustive in its results.

Figure 3-29.  The Is Used By display in the Solution Explorer

77


Chapter 3 ■ Development Tools

Navigating Methods in Solution Explorer The Solution Explorer has new navigation capabilities for methods. You can search by what calls are made for a specific method, who called the method, and whom it is used by. These three functionalities are new in Visual Studio 2013. All of these are accessed in the Solution Explorer when right-clicking any of the properties or methods as shown in Figure 3-30.

Figure 3-30.  Navigating methods in the Solution Explorer The Calls option provides every other method that the method uses. Figure 3-31 shows every call in the method and its listing in the Solution Explorer.

Figure 3-31.  Call results provide a lot of references

78


Chapter 3 ■ Development Tools

Is Called By is the reverse of the Calls method. Instead of showing every method that it calls, it shows every time the selected method is used. Is Called By lists every place the property or method is called. It lists not the line but the method that calls the selected method. Is Used By shows every time that the class is used, listing all lines that use the method.

Navigate To Navigate To is a very old feature that has been in existence since the earliest version of Visual Studio. Nevertheless, a huge improvement has been made in Visual Studio 2013. Instead of popping up a dialog as in Visual Studio 2010 and 2012, Visual Studio 2013 has an unobtrusive way to display a textbox at the top right of the code editor. This feature can be reached by choosing Edit ➤ Navigate To, or by pressing Ctrl+, (Ctrl + comma). Once you have typed in a few letters, the textbox shows a list underneath it. By default, the first element is selected. When you press Enter, the selected file opens. When you press the Esc key, the Navigate To list closes. The search uses special characters to enhance research. For example, you can use the space to create an and between two words. Like writing mes and ord, this gives results for MessageOrder because it contains the strings “mes” and “ord.” The character @ can be used to search only class names instead of searching everything, including file names and file paths. Use capital letters to create a camel search for a path, file, and class name. For example, searching for MOB can result in a ModelObjectBinding class. Navigate To has three options, which are available at the top-right of the code editor when the feature is activated. Figure 3-32 shows (1) its option menu with three checkboxes. Search Within External Items is available only for C++ projects. The search includes external items like an external dependency folder into the possible results. The option Use Preview Tab opens the selected element of the list in the preview tab. If you use the up and down arrows after typing a few letters, you will be able to highlight results. When this option is checked, the file will also open in the preview tab. Finally, Show Details displays the file path of the selected element. This presents additional information but at the cost of taking more space. Depending on the file, path, and project type, the line number can be displayed.

Figure 3-32.  Options for Navigate To

79


Chapter 3 ■ Development Tools

Quick Find and Find in Files Visual Studio provides two ways to search strings. Both are in Edit ➤ Find and Replace. The Quick Find shortcut is Ctrl+F, and the Find in File is Ctrl+Shift+F. The difference between the two methods is that a quick find searches the open document by default. It also highlights every string found in the document. Finally, the search is shown at the top right of the code editor in a nonblocking way, which allows you to continue editing your code without forcing you to close the search. (It closes if you click the X or press the Esc key.) If you change the document, the search remains active only for the file for which the quick find has been activated. This does not mean you can have multiple quick finds open. If a quick find is open in a document, you can go to another document and come back, and this one remains open. However, if you go into another document, do a quick find, and come back, the first quick find will be closed. In Figure 3-33, (1) shows highlighted code and (2) the option bar. The first icon, Aa, specifies the case. If clicked, it makes the search case-sensitive. The Ab icon searches for the whole word; for example, by entering time the word DateTime is highlighted. This is not the case if the match case command is selected. The third icon, a box plus asterisk, enables regex in the search box. Finally, the drop-down arrow specifies where to search. By default, it is the current document.

Figure 3-33.  Quick Find The Find in Files option is different because it opens up a dialog box that lets you search by sending results to another panel. It is good practice to use Quick Find for current documents and Find in Files for the whole solution. This creates two ways to search with shortcuts. Since Find in Files searches the whole solution, it can be run in the background and once the search is done, displays the Find Results panel. Figure 3-34 shows at the right Find and Replace and at the left Find Results.

Figure 3-34.  Find Results of the Find in Files

80


Chapter 3 ■ Development Tools

Find and Replace also has some options. Every option available for Quick Find is also available for Find and Replace. Matching cases, matching whole words, and using regular expressions are all unchecked by default. The Result option gives you the possibility to show results in the Find Result 1 or Find Result 2 panel. There is also an option to show only the file name without the line number.

Bookmark The Bookmark feature is not new in Visual Studio 2013 but is often forgotten. Bookmarks allow you to mark a specific part of the code, like a bookmark that you set to mark a specific page in a book. The bookmark allows you to rapidly come back to a specific line in your code. You can have multiple bookmarks in a solution. Figure 3-35 shows (1) the bookmark tool, which has four command buttons. The first one adds a bookmark. This creates an icon in the left margin as seen at (2). The second and third button in the toolbar let you navigate through the previous or the next bookmark. Finally, the last button deletes all bookmarks. To delete a single bookmark, you need to select the line that is bookmarked and click the first button.

Figure 3-35.  The Bookmark toolbar and a bookmark

Search Solution Explorer Searching the Solution Explorer is a feature introduced in Visual Studio 2012. It is located at the top of the Solution Explorer. You can also use Ctrl+; to grab the focus of the top textbox of the Solution Explorer. If you type a string and press Enter, the Solution Explorer is filtered by your input. It searches within the filename, the file extension, folder name, references, and even class and method names. The last two (classes and methods) are called logical elements, while the others are physical elements. Figure 3-36 shows all four ViewModel classes in the single file AccountModels.cs. If you do not want results to contain this kind of logical information, then you need to uncheck Search Within File Contents, as in Figure 3-37.

81


Chapter 3 ■ Development Tools

Figure 3-36.  Solution Explorer Search

Figure 3-37.  Options for Solution Explorer Search The option Search Within External Items enables searching in the external dependencies folder. This is for C++ projects only. To come back to the full Solution Explorer, click the X at the left of the option arrow, press the Esc key, or select the house icon over the text box. This feature works with the preview tab, which opens the file temporarily. Selecting a logical item like a class or a method has the same effect; the preview tab opens at the line where the class or where the method starts.

The Pending Changes Filter The Pending Changes filter is another feature that has been available since Visual Studio 2012. The filter modifies the Solution Explorer panel by showing only files with pending changes since the last commit with TFS. To use the Pending Changes filter, you need to be working with TFS. The icon to activate the Pending Changes filter is in the Solution Explorer window and is represented by a clock, as illustrated in Figure 3-38.

82


Chapter 3 ■ Development Tools

Figure 3-38.  The Pending Changes Filter icon

The Enhanced Scrollbar The Enhanced Scrollbar is new in Visual Studio 2013. It incorporates two substantial features. The first enhancement adds color annotation in the scrollbar. Figure 3-39 shows the enhanced scrollbar. •

(1) An orange annotation signals every quick search result of the file.

(2) A black annotation identifies a bookmark entry.

(3) A blue horizontal line marks the current line (the cursor line).

(4) A red annotation represents an error in the file.

(5) The left side of the scrollbar is yellow because the code has changed since the last time the file was opened. It is green when a file opens.

(6) A dark brown annotation shows the breaking point.

Figure 3-39.  Scrollbar color annotation

83


Chapter 3 ■ Development Tools

In the Text Editor options you can decide to not show annotations to the scrollbar by choosing All Languages ➤ Scroll Bars. The second feature is a map mode for the editor's vertical scrollbar. To enable the enhanced scrollbar mode, right-click the scrollbar and choose Scroll Bar Options. From here, it is possible to choose the map mode. The default, small scrollbar is the Bar Mode option. The alternative is the new Map Mode option, which can be wide, medium, narrow, or completely off. It is also possible to have a preview tooltip, and to do this you need to hover your cursor over the scrollbar for few seconds as shown in Figure 3-40. At (1) is the scrollbar with the map mode activated. The display at (2) appears after you hover for a second over the scrollbar. The map scrollbar lets you navigate quickly to a specific part of a file. If there are numerous methods in a class, this preview lets you select the code in the scrollbar to navigate through the file to the desired place. The preview gives you a quick look at code without moving from your position.

Figure 3-40.  Scrollbar map mode

Documentation Visual Studio allows you to document your code in different ways. Depending on the file type, comments can be added in different forms. Documentation changes depending on the language. This section discusses the different documentation options in C#, Visual Basic, Razor, XAML, and Visual C++.

C# In C#, there are three ways to comment (Figure 3-41). The first is with a double slash. It comments on a single line from the double slash to the end of the line only. The second way to comment is with a slash star (/*). This comment type can extend over multiple lines. To indicate the end of a comment, use star slash (*/). The last way to comment is to use three slashes (///). When you type three slashes, Visual Studio automatically writes XML tags including the summary tag, the parameter tag, and the return tag. You can write additional tags by pressing Enter and letting IntelliSense show you the available options.

84


Chapter 3 ■ Development Tools

Figure 3-41.  C# offers three ways to comment

Visual Basic Visual Basic does not offer as many ways to comment as C#. VB allows single-line commenting, using the apostrophe (') as a marker. The only way to have multiple-line comments is to select multiple lines and then either click the Comment button in the toolbar or choose Edit ➤ Advanced ➤ Comment Selection. This will add the apostrophe to every selected line. The second way to comment is to type three apostrophes over a method. Visual Studio will generate the XML documentation with <summary> and <remarks> tags. If parameters or the return value are available, these will also be added. Figure 3-42 shows the two types of available comments in VB.

Figure 3-42.  VB.NET comments

Razor Razor allows only one way to comment. Comments start with the @* marker and end with *@. This notation is adequate for multiple as well as single lines. You can also include HTML comments in a Razor file, but they will appear in the generated HTML. To do this, use <!-- as the beginning tag and --> as the ending tag. Figure 3-43 illustrates the two types of comments, Razor and HTML.

85


Chapter 3 ■ Development Tools

Figure 3-43.  Razor comments

XAML XAML is based on XML, and its commenting style is also based on XML. To comment with XAML, use the <!-- and --> tags; this method lets you comment on several lines. Visual Studio 2013 has improved commenting in XAML by allowing you to select code that is already commented and use the Comment tool. When you click the Comment button, this will add the ending comment tag as discussed in the WPF section of this chapter.

Visual C++ C++ uses the same pattern for commenting as C#. In fact, C# took its inspiration from C++. The only difference is that IntelliSense does not generate the triple slashes (///) automatically as in C#. Figure 3-44 gives an example.

Figure 3-44.  Visual C++ comments Alternatively, C++ allows you to use // to comment a single line or /* as in C# to comment multiple lines.

Deploying Your Code Once your code is completed, it is time to deploy, or publish, it. Visual Studio can help you deploy on different media for different types of applications. Visual Studio is equipped to publish with FTP, as a file, or with web publishing (Web Deploy) for web applications. It can also deploy a setup file for an executable or use Click Once technology. Visual Studio also publishes Windows 8 applications using a specialized package. In this section you will see how to deploy a Windows 8 application with Visual Studio; you’ll see how to install it without having to fully deploy it with Windows.

86


Chapter 3 ■ Development Tools

Web Deploy Web Deploy is also known as MSDeploy or Microsoft Deploy. Its role is to simplify the deployment of web applications to IIS. Web Deploy can be installed by using the Web Platform Installer. Because this book is about Visual Studio, we will not go into any further detail about Web Deploy. Most Web Deploy publishing is done with the msdeploy.exe software, directly with IIS, or with One Click Web Deployment, covered in the next section. Keep in mind that if you are using Web Deploy with an IIS server that is not located on your local machine, you may have to set up the Web Deployment Agent Service (MSDepSVC) on a remote machine. Administrative rights are also required on the remote machine.

One Click Web Deployment One Click Web Deployment is also known as the One Click tool, or simply the Publish tool. You can find this option in the context menu of any web project you have, if you open it in the Solution Explorer. Once you have right-clicked the web project and selected Publish, a wizard will appear. You can also choose Build ➤ Publish Web Application to access the wizard. One Click is available for Visual Studio 2012 and 2013. Visual Studio 2013 Express edition also has a feature called One Click Deployment, which lets you deploy directly to a host provider by choosing either Web Deploy or Web Deploy Package. You can also choose FTP or File System as deployment options. Wherever you plan to deploy, the wizard has three steps. The first step is to create a profile. Profiles contain settings about where to publish. If you are using an external host provider or Windows Azure, you can download from them a .publishsettings file for the profile. In the second step, use the combo box to choose a publish method. Figure 3-45 shows all fields for the Web Deploy publish method. Most of the wizard options require you to be the administrator. If you are not, you will not be able to publish. Be sure to close Visual Studio and open it again as an administrator.

Figure 3-45.  Step 2 of the Publish wizard

87


Chapter 3 ■ Development Tools

In the third step you configure the settings for the build and the connection string. If you are using Entity Framework, an option to execute Code First Migration is available. Beware that this requires you to have a single implementation of the DbMigrationsConfiguration class. Otherwise, Migration will not be executed. If you are not using the Entity Framework Migration tool or want to use SQL, you can specify a SQL script to be run.

Click Once Click Once easily publishes Windows Presentation Foundation (WPF), Windows Form, and console applications. It works online and offline and can be self-updating. This method can publish on a website, in a network share, or to any external device like a USB stick. Click Once can communicate with a server to find out if a newer version of the application is ready. If the network is down, it can still run the application but will not update it. If the network is available, it can check for a new version and update if required when a newer version is available. The owner of the application controls updates. Updates can be mandatory or optional. To access Click Once publishing, right-click a WPF, console, or Windows Form project and choose Publish. It is also available by choosing Build ➤ Publish. A wizard with several steps will appear. In the first step, as illustrated in Figure 3-46, you specify where to publish the application. Most of the time, you will publish to an IIS server.

Figure 3-46.  The first Click Once wizard step The second step establishes the type of installation. Even if you specify a web site in the first step, it does not mean that the user will install the software from a web site. The third step allows you to define the web path for the application to search for an update. This should be a URL to the IIS server that contains the Click Once application. However, this path is not required.

Win8 Application Deployment If you create a Win8 application, you can deploy it on the store or only on your computer. To deploy on the store, you need a developer license. Once you have that license, go to the main menu and choose Project ➤ Store ➤ Create App Packages.

88


Chapter 3 ■ Development Tools

■■Note  You can acquire a developer license by choosing Project ➤ Store ➤ Acquire Developer License. This opens a wizard; it will first ask you if you want to publish on Windows Store or locally on your hard drive. Then, if you have selected to publish locally, you can select the output location on your hard drive, as shown in Figure 3-47. Other options include setting the version. It is also the Select and Configure Packages panel that lets you specify whether to generate an app bundle. This option can be useful to reduce the size of the package; it should be chosen if your application has a lot of images or external resources. By default, the option is If Needed. Visual Studio will create the app packaging if it sees that you have defined the language assets, images, or Direct X resource.

Figure 3-47.  Step 2 of the Win 8 Publish wizard Finally, you can set the build configuration used by Visual Studio when creating the package. It is possible to include a debugging file (.pdb) to attach later on with Visual Studio. These debugging files will be located in the .appxsym file generated by the publisher.

89


Chapter 3 ■ Development Tools

NuGet NuGet lets you easily reference external libraries. It allows the downloading of public libraries, and it also lets you create private NuGet repositories to store and download private libraries. NuGet allows you to update libraries easily as needed. This section explains NuGet’s console and its graphical user interface. The most useful and simple screen in NuGet is the Manager; to open it, choose Project ➤ Manage NuGet Packages or right-click the References nodes under Projects in the Solution Explorer. As a side note, all libraries in NuGet are associated with a single project. If you want to use a library in multiple projects, you have to use NuGet for each of them. Figure 3-48 illustrates the NuGet Manager: •

(1) points to all the libraries NuGet has installed for the selected project.(2) is a list of NuGet repositories. NuGet.org is the public repository where you will most often download libraries. It is possible to add a private repository.

(3) is a list of libraries that can be updated. NuGet connects to the repository where libraries have been downloaded to check if newer versions are available.

(4) is the list of all libraries. This can be filtered using the search box in the top-right.

The display at (5) identifies who created the library and what the current version is, and it gives a description of what the package is doing.

Figure 3-48.  NuGet packages

90


Chapter 3 ■ Development Tools

Figure 3-49 shows that the library FlagConsole is installed. It is present in the list of References of a project and available in the Installed Package of NuGet. At the right of the library is an Uninstall button. This is the correct way to remove an installed library, because it removes the physical DLL and cleans up both the project file and also any other configurations previously written in the configuration file of the project.

Figure 3-49.  Uninstalling the NuGet package It is also possible to control DLLs for all your projects by opening the NuGet package for solutions. This is located in Tools ➤ Library Package Manager ➤ Manage NuGet Packages for Solution. The manager looks the same as the one for a project, but this time it is installed on multiple projects. Visual Studio offers a Package Manager Console. It is available in Tools ➤ Library Package Manager. You can get all packages by typing Get-Package -ListAvailable. The resulting list will be huge, and instead of having thousands and thousands of lines of packages, it is best to filter the output. To do so, add the Filter parameter; for example, Get-Package -ListAvailable -Filter JqueryUI. Figure 3-50 shows the Package Manager Console.

Figure 3-50.  NuGet Package Manager console At the top of the console, (1) is a drop-down that lets you choose the package repository. By default, it is the public library at NuGet.org. You can add repositories to the list by clicking the button at the right of drop-down (1). The top bar also lets you choose which project to apply the command to, by using the drop-down at (2). Finally, the command prompt starts with PM> (3), and it lets you type a command. Output will be shown under the command line.

91


Chapter 3 ■ Development Tools

So far, we’ve only worked with package listings in NuGet. However, using the command line you can also install, uninstall, or update packages. The command Install-Package <package name> will let you install the package. The uninstall command is Uninstall-Package <package name>. To update a package, first type Update-Package -Updates to get a list of all packages that can be updated. Then you can update by using the same command, UpdatePackage followed by the package name. Finally, Visual Studio and NuGet have a Restore option, which allows for the automatic downloading of any missing package when compiling. This is a powerful tool because any open source package or code that does not need to have references in a source control can save space by omitting them. NuGet has package files that specify which version to use, and when Visual Studio is building, it reads the package file to know what NuGet package to use. If packages are missing, it uses NuGet to download them and continues to build. To enable package restore, right-click the solution and choose “Enable NuGet Package restore”. You can also choose Tools ➤ Options ➤ Package and check Allow NuGet to download missing packages during build.

Summary This chapter has covered the editor window and all the features that will be essential for optimizing your development. You have seen how IntelliSense can be used and its variations among different languages supported. We then explored Visual Studio navigation. You learned how to navigate with the Solution Explorer, but also how to optimize getting information with a different way of searching. Developing involves many people reading the code, and comments are the way to document your code for yourself and others. You have seen that Visual Studio provides different ways to comment depending on the language. We also looked at Visual Studio’s has integrated publishing tools. From web deployment to Win 8 publishing, every project can be deployed. Finally, you have seen that Visual Studio integrates NuGet, which references and updates the external package without having to leave Visual Studio.

92


Chapter 4

Debugging Coding is a considerable part of the development process, and debugging is closely related to this operation. Visual Studio offers a powerful way to resolve logical errors within the development environment. No installation is required and no additional third-party software; all the debugging is included out-of-the-box for you. This chapter discusses how to efficiently use breakpoints, a debugging window, advanced debugging, tracing, and managed memory analysis in Visual Studio.

Breakpoints Breakpoints are indicators in Visual Studio that tell the compiler to stop executing its process. Using them enables you to examine variable values and to explore the stack trace. Breakpoints are available in Visual Basic, C#, and C++, and for every Visual Studio edition. This section covers all the related options, including conditional breakpoints, filtering, counts, and the Edit and Continue feature.

An Overview of Breakpoints In general, breakpoints are the functionality most often used in Visual Studio for debugging. It is possible to set a breakpoint anywhere in your code. To set a breakpoint, you can use the shortcut F9. You can also choose Debug from the menu and choose Toggle Breakpoint. A third way to insert a breakpoint is to right-click the line of code where you want to add the breakpoint, select Breakpoint, and then choose Insert Breakpoint. One of the most common ways to add a breakpoint is to click in the left margin next to the line you want to debug. To confirm that you have really set a breakpoint, the line turns red. In addition, the left margin is marked with a red dot. Finally, the scrollbar has a red mark that indicates where in the file the breakpoint is located. Figure 4-1 illustrates at (1) the Toggle Breakpoint command and at (2) the New Breakpoint item. We will discuss the New Breakpoint feature shortly. At (3) is the Delete All Breakpoints option. This permanently deletes all assigned breakpoints. It is quite useful when your debugging session is over. Instead of searching in every file to toggle back the breakpoint, using this feature resets everything. Disable All Breakpoints (4) acts like deleting but allows you to reactivate the breakpoint later. Sometimes, removing breakpoints temporarily without removing them indefinitely is the best approach. You might use this option if you are in a debug session and you want to continue executing the whole code. You can use Disable All Breakpoints, which will put all breakpoints into disable mode. This can be done for specific breakpoints, too. The shortcut is Ctrl+F9, or you can right-click any breakpoint and select Disable Breakpoint from the context menu. This feature is not available in the Express edition.

93


Chapter 4 ■ Debugging

Figure 4-1.  A Visual Studio breakpoint and related menu options The New Breakpoint feature (2) allows you to set a new breakpoint somewhere in the project just by writing the function name; this is why it is also called Break At Function. For example, if you write Index and your project has more than one method with that name, Visual Studio will prompt you with a list of possible breakpoints to choose from. In Figure 4-2, the New Breakpoint dialog box is open with the list of possible functions for the name Index.

Figure 4-2.  The New Breakpoint dialog box

94


Chapter 4 ■ Debugging

This function is not available in Visual Studio Express. However, it is available for Visual Basic, C#, and C++, and for setting breakpoints from the call stack. When debugging, you can right-click on a line of the call stack and add a breakpoint. Later in this chapter, we will discuss the call stack in more detail. Nevertheless, even if Express editions are limited in breakpoints, these two functionalities—new breakpoints and call stacks—are not really used much. Breakpoints have their own panel, where you can see the list of breakpoints for the solution. Open the panel by choosing Debug ➤ Windows ➤ Breakpoints. The Breakpoints panel lets you delete, disable, or change the location of breakpoints in a single place.

Conditional Breakpoints, Breakpoint Filters, and Hit Counts

Conditional breakpoints, breakpoint filters, and hit counts are features that are available in Visual Studio Professional, Premium, and Ultimate editions. They can be accessed by right-clicking on a breakpoint in the left sidebar to open the breakpoint context menu (Figure 4-3) or if you have the Breakpoints panel open.

Figure 4-3.  Context menu for a breakpoint Conditional breakpoints can be enabled by selecting Condition from the breakpoint context menu. When you do this, a new dialog box opens and allows you to write a statement. Figure 4-4 shows that you have two options. When the Is true option is selected (1), then the breakpoint is enabled when the condition in the box is true; otherwise, it stays disabled. For these cases, the condition must evaluate to a Boolean (for example, "yourVariable > 10"). You can also use the Has Changed option, which enables the breakpoint only if the condition has changed. In these cases, the condition must be a variable name only.

95


Chapter 4 ■ Debugging

Figure 4-4.  The Breakpoint Condition window Once a condition is set to a breakpoint and the breakpoint is set, a plus sign is added to the red dot in the left margin. Among the three functions, this is the one that is most used. The next function is the Hit Count option in the breakpoint context menu. By default, a breakpoint is triggered every time that line of code is run or hit, but you can specify to break the code only after a certain number of hits. For example, you can specify to break the code only after the line has been hit ten times. Additional options are available. It is possible to break if the hit count is more than one (the code line has been hit multiple times) or if the hit is greater than or equal to a specified limit. As with a conditional breakpoint, once a hit count is set to a line, it has a plus sign within the red dot in the left margin. The final function to mention is the breakpoint filter, which you access by selecting Filter from the context menu. It lets you specify which computer, process, or thread can use the breakpoint. This can be useful in a scenario where you want to debug a website remotely and you want only your calls to be hit by a breakpoint.

Edit and Continue Edit and Continue allows you to alter code during its execution when the code is in a break. This feature has been included with Visual Studio since 2005. It is a time-saver because you can edit the code without stopping it and having to compile it again. You can enable Edit and Continue before executing the code by opening Tools ➤ Options ➤ Debugging ➤ Edit and Continue, as shown in Figure 4-5.

Figure 4-5.  The Edit and Continue option Since .NET Framework 4.5.1, Visual Studio has supported Edit and Continue for 64-bit projects. ASP.NET developers who want to enable Edit and Continue must open the website project properties and select the Web tab. At the bottom of this setting panel are all the debugging options. One is a checkbox that enables Edit and Continue. It has been checked by default since Visual Studio 2013.

96


Chapter 4 ■ Debugging

Still, Edit and Continue has the following limitations: •

It allows you to change code within a method but not outside it. For example, adding a new method to a class is not supported, but changing the assignment of a variable inside a method is.

It cannot be used in changing a signature of an existing method.

Change using a statement or references is not supported.

Modifying methods with a yield statement or modifying a lambda expression is prohibited.

Edit and Continue is available for Visual Basic, C#, and C++, but not for F#.

Attaching to a Process Attaching to a process means that Visual Studio hooks a process to get debugging information. It opens a communication channel between the development environment and the desired process to debug. By default with an ASP.NET project, Visual Studio starts IIS Express. The ASP.NET project knows how to attach Visual Studio to IIS Express in order to enable you to debug. Attaching Visual Studio to a process allows you to have the same capability as the default behavior that attaches Visual Studio to IIS Express. This can be useful if instead of using IIS Express you use IIS. You can attach to the w3wp.exe process and have the same capabilities as the default IISExpress/Visual Studio combination.

■■Note  ASP.NET projects use a private web server called Cassini. Since Visual Studio 2013, Cassini does not exist and IIS Express is the default server. It has more configurations and is more similar to the real IIS server. Attaching to a process requires you to have the debugging information, which is often referenced as a .pdb file. To start using Attach to Process, choose Debug ➤ Attach to Process. A list of all available processes appears. You can also see processes that are not running under your Microsoft Windows account. Once you have selected the process, which can be IIS as well as any executable, such as a Win form or a WPF application, Visual Studio is linked and the debugging can start. It is possible to debug remote processes. To proceed, you need to download the Remote Tools for Visual Studio on the remote computer. Visual Studio needs to be run as an administrator and the firewall should be turned off, or a special rule for MSVSMON.EXE (which is the remote tool installed on the computer to debug) should be added. Finally, in Visual Studio you have to change the Qualifier to the machine name to debug with the port used by the tool. This information is located in the tool on the debug machine.

Debugging Windows During debugging, it is important to know what is happening. Debugging has a lot of windows/panels where you can find variables, values, and different states of the application. This section explains eight panels that can be used to help you debug your application: •

Output

Immediate

Watch

QuickWatch

97


Chapter 4 ■ Debugging

Autos

Locals

Breakpoints

Memory

The Output Window The Output window is one of the most often-used debugging features. It can display information about builds, build order, debugging, source control, and more because depending on the tool installed in Visual Studio, this window can extend its capability. It is possible to open this window by selecting View ➤ Output or by using the shortcut Ctrl+Alt+O. The Output window is not limited to receiving messages from Visual Studio and its add-ins. In fact, you can use this Output panel to output information from your website. Instead of logging into a file if you are debugging, you can redirect the output to the Output window. A Visual Basic developer may remember the Debug.Print command that was available in VB6. Visual Studio 2013 uses the System.Diagnostics framework, which provides the Debug.Write and Debug.WriteLine methods to monitor with the Output window. In Figure 4-6, (1) shows the result of using Debug.WriteLine.

Figure 4-6.  The Debug.Write and Debug.Assert methods In addition to the Debug.Write methods, Debug.Assert logs to the Output window only when a specific condition is false. The Debug.Assert method declares a message but also pops up a dialog box with three options (2), as shown in Figure 4-6. You can see that from a single line of code, the Output window displays a message but also has a dialog box with Abort, Retry, and Ignore options. Abort stops the application that is causing Visual Studio to stop debugging. Retry jumps Visual Studio into a dynamic breakpoint, and from this action, you can step-into your code. The Ignore command simply acts as if nothing has been triggered, and the code continues. If you want to write a line conditionally without working through the dialog, you can use Debug.WriteLineIf, which takes a Boolean condition and a message as parameters. If the Boolean is true, the message is written to the Output window.

■■Note  System.Diagnostic also has the Trace class, which has the same Debug logging method. Debug code is not ported when compiling in Release mode, whereas Trace is.

98


Chapter 4 ■ Debugging

The Immediate Window The Immediate window is a panel that can be opened by choosing Debug ➤ Window ➤ Immediate, or by using the shortcut Ctrl+Alt+I. Its role is to accept commands and display the results. It can evaluate expressions, execute commands, and trace values. To display values, you can type the command >Debug.Print VariableName or >? VariableName. It is also possible to evaluate expressions. The greater-than sign is optional in the Immediate window before every command. You can set variable values or create variables on the fly by writing the name of the variable followed by the equal sign and the desired value. Ending the command with a semicolon is required in that case. One powerful feature that was incorporated into the Immediate window is Visual Studio IntelliSense. Static methods can be executed right away in the Immediate window. Methods from classes need to be instanced into an object before being used.

The Watch Window The Watch window is the most often-used debugging window available in Visual Studio. It is only available when a debugging session is running. To open it, choose Debug ➤ Windows ➤ Watch. Visual Studio offers four watch windows that let you organize your debugging session. The shortcut is Ctrl+Alt+W+1 (or 2/3/4) for the Watch 1 (/2/3/4) window. When debugging, it is possible to right-click any variable and click Add Watch. This adds the variable to a list of variables whose value Visual Studio will keep track of until the scope of the variable ends. Watch variables can be added directly into the Watch panel. In the last line of the watch variable list, you can enter a variable name, expression, and methods, and see the result refresh when a part of one of these changes. Figure 4-7 shows some variables that have been put into the Watch 1 panel. The last two lines of the grid are expressions. The first expression does not even contain a variable, while the last line does arithmetic operations with variables and a number.

Figure 4-7.  The Watch window A third way to add information into the Watch panel is to drag and drop variables directly into the Watch window. As you can with variables and expressions, you can set the result of a condition in the Watch window. For example, writing x == y in the Watch window outputs true or false. This is useful when debugging because if variables change, the expression changes. Other special variables, called pseudo-variables, can be watched. For example, adding $ReturnValue shows the value returned from a function, $exception gives the catch exception value, $user is information about the user that executes the process, and so on.

99


Chapter 4 ■ Debugging

The QuickWatch Window QuickWatch examines variables and expressions on the fly. Instead of setting variables or expressions in a list like the Watch window, QuickWatch is there for a very quick examination of values. To use QuickWatch, right-click the variable or select the expression and then right-click and select QuickWatch, or press Shift+F9. From here, a dialog window opens and lets you see the selected item’s value. It is possible to add a variable from the QuickWatch to the Watch window. Figure 4-8 shows that the expressions can be entered or altered from a selection of the code. Changing the expression means it needs to be reevaluated. To do that, click the Reevaluate button or press Enter. The Add Watch button takes the expression and inserts it into the Watch window.

Figure 4-8.  QuickWatch window You can fire up QuickWatch from the Immediate window, too. The command is >Debug.QuickWatch. Without any parameters, this QuickWatch window opens empty, but if an expression is passed in a parameter, then it is evaluated in the QuickWatch window. As in the Watch window, you can expand the watched object to see its inner properties. The major advantage of the QuickWatch window over the Watch list is that you do not have to clear anything. Once the QuickWatch window is closed, everything is cleared. The other advantage is that the window can be rapidly resized, which is a must for classes with a lot of properties. You will often need to resize the window while debugging a generic list.

The Autos and Locals Windows The Autos and Locals windows display values by themselves. The Locals window displays the value of every object in the current scope. If you are inside a method, the variables shown in this panel are from this method only. Figure 4-9 shows that the Main method has four variables declared and initialized. The Locals window shows these four variables plus the one that is the parameter.

100


Chapter 4 ■ Debugging

Figure 4-9.  The Locals window The advantage of the Locals window is that it does not need any manipulation from you. It is automatically populated. If you are debugging and moving across several methods, the Locals window is populated for every method. Like the Watch window, if you are stepping through a method and a value changes, the window is updated automatically. In contrast, the Autos window shows the current statement and the previous statement values. Values can be variable values, return statement values, or values used in parameters. The result is a shorter list than in the Locals window, which Visual Studio populates automatically without any manipulation from the developer. Nevertheless, if you are developing using good standards, your methods should not be so huge that the Locals window becomes unusable. Still, the Autos window shows the return statement from a method call, which the Locals window does not. Figure 4-10 shows the difference between the Locals and Autos windows. The Autos’ first three lines are returned values from the previous statement. As you can see, the result variable is calculated from three functions. The Autos window shows every function’s return value, while the Locals window shows only the value of defined variables.

Figure 4-10.  The Autos and Locals windows

101


Chapter 4 ■ Debugging

The Breakpoints Window Every breakpoint that is set in the solution is collected in the Breakpoints window/debugging panel. The Breakpoints window is available at all times, not just while debugging like the other windows we have previously discussed. You’ll see a list that shows the location of the breakpoint, the label associated with the breakpoint (if one has been set), the condition (by default there is no condition), and the hit count. Figure 4-11 shows some of these scenarios. The first breakpoint is set to ApressController.cs at line 15 and character 13. Double-clicking this line moves the Visual Studio code editor to this file. You can also see that this breakpoint has a hit count condition set to hit only when the count reaches 10.

Figure 4-11.  The Breakpoints window The last line of the breakpoint was unchecked directly from the panel but could have been disabled directly from the code editor by right-clicking the breakpoint and selecting Disable Breakpoint. If you want to enable or disable the option from the Breakpoints window, just check or uncheck the box beside the breakpoint desired. This window has other available actions, including adding a new breakpoint. However, that’s not very convenient; it is easier to simply go into the code editor and add the breakpoint. Another action you can perform here is to delete selected breakpoints. A trick to delete multiple breakpoints is to hold down the Ctrl key when clicking the breakpoint. If you want to delete all breakpoints from the Breakpoints window, you can press Ctrl+A, which will select every entry, and then press Delete or the second button with a red X. The Breakpoints window has a Search text box, and you can write a string filter breakpoint using a file name. When the breakpoint list is filtered, it is possible to click the third and fourth buttons, which delete the list of filtered breakpoints or disable/enable it. This is an efficient way to disable all breakpoints, as in ASP.NET MVC Controller, for example. Finally, double-clicking a breakpoint line makes Visual Studio jump to the file and the line where the breakpoint is set.

The Memory Window The Memory window shows the big picture of the memory used by a project. Unlike previous debugging windows, this one does not show the value of variables or expressions but shows the value of memory. The Memory window is for the advanced user. It shows your memory footprint and allows you to modify the memory directly. Figure 4-12 shows address values. Everything is set to hexadecimal.

102


Chapter 4 ■ Debugging

Figure 4-12.  The Memory window To access the Memory window, choose Debug ➤ Windows ➤ Memory. It is only available when debugging. This panel is used almost exclusively by C++ developers.

Advanced Debugging Debugging can be harder in a multithreaded environment or if it uses several processes. This is why Visual Studio offers several tools to help you while debugging; these include the Threads window, the Parallel Stacks window, the Modules window, the Process window, and the Page Inspector tool.

The Threads Window The Threads window is a grid that lists all threads in the running application. By default it shows all threads, but the window allows for the filtering of threads as well. You can flag threads to bookmark those you want to watch closely. The grid has a column for the unique identifier of the thread, a managed ID, a category (interface thread, rpc handler, worker thread), the name of the thread, the location, the priority, and the name of the process that executes the thread. The Affinity mask is hidden by default and is used to mark which processor the thread is assigned. Additionally, it has a suspended count that shows if a thread can be run or not. The thread window is in Debug ➤ Windows ➤ Threads. Figure 4-13 shows an example of the main thread of a console application when two threads are created. This creates two entries next to the main thread. The location column displays where the code thread is running. You can see that they are both located at ThreadFunction(), which is the method that the thread is executing.

Figure 4-13.  The Threads window

103


Chapter 4 ■ Debugging

Double-clicking a thread makes the source code editor move to the position where the thread is located. If you have the Call Stack window open, you can see the stack of the current thread.

The Parallel Stacks Window Visual Studio offers a visual designer for debugging parallel execution such as threading. It is under Debug ➤ Windows ➤ Parallel Stacks. Figure 4-14 shows Thread 3 holding three other threads. The Parallel Stacks window allows you to freeze some threads, to move to the source code, or to display threads in tasks. Once you see the tasks in the parallel stacks, you can see the status of each one. It is possible to see blocked, deadlocked, active, and scheduled tasks.

Figure 4-14.  The Parallel Stacks window If you open the Task panel at Debug ➤ Windows ➤ Task, it shows you a matrix of all tasks with the start time, the duration of the location, and the task, as shown in Figure 4-15.

Figure 4-15.  The Tasks panel

104


Chapter 4 ■ Debugging

The Modules Window The Modules window is displayed by choosing Debug ➤ Windows ➤ Modules. It shows all DLL and EXE files used by the process of the running program. Information like the path of the file is shown. This can be useful if you are debugging and you are not sure that Visual Studio is using the correct file. It is also useful to see if the debugging file, known as the symbol file, has been loaded and for which DLL. If the symbol file is not loaded for a DLL, Visual Studio might not be able to debug it. You can also view the Version and Loading Order. Figure 4-16 shows that it is also possible to filter a list to simplify the search.

Figure 4-16.  The Modules window

The Process Window

The Process window is not available in the Express edition, but it shows all processes attached to Visual Studio. If you have launched a process from Visual Studio, that process is also shown in the list. It is possible from this list to detach a process or terminate a process. It is not a window that is used much since most of the time we attach only one process at a time. Nevertheless, in a scenario where multiple services, websites, or console applications need to be run together, it can be useful.

The Page Inspector The Page Inspector is for website applications. It provides a browser diagnostic tool that links HTML elements to the C# code. To start the Page Inspector tool, you first need to change the default browser to the Page Inspector instead of Internet Explorer. This can be done with the standard toolbar, as shown in Figure 4-17.

105


Chapter 4 ■ Debugging

Figure 4-17.  The Page Inspector toolbar From here, instead of the website launching in a browser, it starts inside the Visual Studio Page Inspector's inner browser. This special browser lets developers inspect elements in the browser windows. In Figure 4-18, the left side is the Page Inspector. The Home button is being inspected, which shows in the bottom-left panel that the HTML is generated by the Razor code. The Razor code is also automatically open in the code editor window. It is possible to modify the Razor and to see the modification of the Page Inspector. CSS styles can also be changed and refreshed in the Page Inspector.

Figure 4-18.  The Page Inspector

106


Chapter 4 ■ Debugging

Tracing During debugging, not only are the variable values important, but also each one’s location in the call stack. This section shows you four ways to work with the stack: the Call Stack panel, Code Map, IntelliTrace, and Tracepoint.

Call Stack The Call Stack is one of the most used debugging panels after the Watch/Locals windows. Its role is to display the path of the code from the starting point of the application. It allows you to double-click any line of the stack to move backward. Figure 4-19 shows what the call stack looks like after the user has double-clicked on an earlier step in the stack. You can see that a curvy arrow appears in the Call Stack window, and the same arrow appears in the left margin of the code editor. This is the mark in the code editor where the call was made.

Figure 4-19.  The Call Stack window In the example, the Counter method has been called, and you can clearly see that the main method was the caller. This is shown in the Call Stack panel and also in the code editor. One powerful feature is the ability to see all the values of each variable in the called method. The Visual Studio Ultimate edition allows you to display every variable's information for the entire stack. This feature is ideal for tracing because it not only shows the execution path from the start to the breakpoint but also displays the value throughout this process. However, it is not very well represented visually.

107


Chapter 4 ■ Debugging

Code Map

As an alternative to the Call Stack, the Code Map feature is available in the Visual Studio Ultimate edition. The Code Map is synchronized with the Call Stack while debugging. For example, in Figure 4-20, a breakpoint was set inside a method from a thread function. Several threads have started this function. The Call Stack shows ThreadStart_ Context and ThreadFunction, but the Code Map shows more. It displays the main thread as the Counter method and the thread is stopped by the breakpoint in ThreadFunction. Code Map allows commenting and can display information including method calls, definitions, and all references to methods. Once you stop debugging and start a new session, your comments and information are cleared as well.

Figure 4-20.  Code Map

108


Chapter 4 ■ Debugging

IntelliTrace

IntelliTrace is available only with the Visual Studio Ultimate edition. It records all coding steps when Visual Studio is debugging. It is turned on by default but can be turned off by choosing Tools ➤ Options ➤ IntelliTrace. IntelliTrace comes with two modes: One is driven only by events, and the other is enhanced with calls. IntelliTrace mode can be set in the Options tab under the General tab of IntelliTrace. In both cases, the goal of IntelliTrace is to run a sequence of actions on your software and display a history of what happens. You can see this feature as a list of steps that have been taken. This is similar to Adobe Photoshop or Microsoft Word, which each have a stack of actions that have been completed. You can open IntelliTrace when Visual Studio is in debug mode. If the panel is not open, you can choose Debug ➤ Windows and then click the IntelliTrace Event to activate the panel. Let’s examine IntelliTrace by looking at a simple example. In a console application, a few threads are launched and a method is called. Figure 4-21 shows the IntelliTrace Events view side by side with the IntelliTrace Calls view.

Figure 4-21.  IntelliTrace Events view compared to Calls view

109


Chapter 4 ■ Debugging

Because our example is a console application, it is not really event-driven. This means that you cannot see which button was clicked or which events have been called. Nevertheless, if we had put in some breakpoints, IntelliTrace would have added an event for each one in the panel, and it would be possible to jump back into the state that it was in during the application at this time. On the other hand, the Calls view has plenty of entries. Of course, the drawback is that your machine collects a lot more information and your application may run slower. This feature should not be activated all the time. IntelliTrace collects calls to all methods. It is like the stack trace window but not just for the direct path from the start. Instead, it is for all calls and all paths from the start. Figure 4-21 shows that the main method of the console application first calls a method called FunctionAdd and then the Start 2 thread. It then changes the current culture, then the HouseName method writes something to the console, and so on. It is possible to click a past event and have Visual Studio move back to the state it was in at that time. The Locals window shows the variable’s value. But it is also possible to dig deeper. The left margin of the code editor has new controls, which allow you to navigate to the previous margin and then make a call and go inside the method, as shown in Figure 4-22.

Figure 4-22.  IntelliTrace navigation buttons When stepping through a function, the Locals window updates its variables. Parameters, variables, and return values are shown. Figure 4-23 shows the next step of the previous example. It is the result of stepping through the Counter function.

Figure 4-23.  IntelliTrace Step In function As you can see, the IntelliTrace panel shows the function entry and exit calls, and because I have stepped through to the end of the method, the Locals window at the bottom of the screen shows the return value as the parameter value.

110


Chapter 4 ■ Debugging

Tracepoint

Tracepoint is not available for the Express edition but it is for the Professional, Premium, and Ultimate editions. Tracepoint is a breakpoint with an action. Instead of breaking when the code reaches a certain point, the tracepoint executes an action. There are two ways to create tracepoints. You can right-click the line of code where you want to set the tracepoint, select Breakpoint, and then Insert Tracepoint. The second way is to convert an existing breakpoint into a tracepoint. Converting occurs if you right-click the breakpoint’s red dot and select When hit. In both ways, when a tracepoint is set, a dialog window opens. Figure 4-24 shows this dialog. First, you can set what to do when the tracepoint is set. Printing a message will write the message in the Output Panel. This is convenient if you want to print data without altering the code and without having to break the code. This is useful in situations where loops are present.

Figure 4-24.  Tracepoint dialog window You are not limited to printing messages. You can also specify a macro name to have its action be executed.

111


Chapter 4 ■ Debugging

Memory Analysis with Profiling Memory problems, such as memory leaks or inefficient memory use, are hard to debug. Applications can create memory exceptions or have performance issues. It is possible to analyze information and make changes with .NET Memory Dump Analysis. This feature is only available in the Visual Studio 2013 Ultimate edition, and the process must run on .NET 4.5 or later. To start collecting memory, open Debug ➤ Performance and Diagnostics. This opens a Visual Studio wizard that lets you choose the analysis target and the tool to use. Select the Performance Wizard tool. It is possible to choose to profile the CPU as well as the memory. This is a great way to collect information for problems with your software. This tool is CPU-intensive; so beware of this before starting a profiling session. The result gives the hot path that is the call tree of the highest inclusive samples. This is the path with the most data collected. A profiling session also lists the functions that are doing the most work. These two lists are a good entry point to figure out performance problems. Figure 4-25 shows these two lists: Hot Path and Functions Doing Most Individual Work for the whole debugging session. It is possible to select only a part of the sampling to concentrate on a specific task.

Figure 4-25.  A profiling report

112


Chapter 4 â– Debugging

Once you have an analysis and have done some modification on the code, you can rerun a performance profile by right-clicking an existing session and selecting the Launch with Profiling option. This will create a new data file that can be compared. Finally, if you select a function from the hot path or from a list of functions, you can go deeper into the analysis. It is possible to see the calling function and the called function. This is an efficient way to see which piece of code can call the problematic function.

Summary This chapter introduced the debugging side of Visual Studio. You have seen how to use a breakpoint to get information from variables and how to do so from Visual Studio using an external process. We did a roundup of all the debugging windows so you can respond more efficiently to what happens during an execution. You have also seen how to debug with more advanced techniques, including how to debug a thread and parallel executions. Finally, you have seen how to perform tracing and profiling with Visual Studio.

113


Chapter 5

Code Improvement Tools Code always needs to be improved, not only for maintainability, but also for performance and testability. This chapter explains how to improve your code with Visual Studio tools. This chapter takes a closer look at the Code Map feature, which as you saw in Chapter 4 creates a visual reference of the code. You’ll also learn about features like finding code duplicates with the clone tool, and how to use Visual Studio’s architectural tools to perfect your code. The last part of this chapter shows how to evaluate the quality of your code with the Code Metric tool and Visual Studio’s code analyzers.

Code Map In the previous chapter we briefly discussed Code Map, but here you will learn how to use the tool. The Visual Studio Code Map feature is designed to help developers visualize relationships in code. Code Map becomes useful during development and debugging. During development, it helps you to understand the relationship between classes so you can improve the code. During a debugging session, it helps you visualize the stack. The Code Map feature is only available for Visual Studio 2013 Ultimate edition. Nevertheless, Visual Studio Premium and Professional do have limited capability here, as they can open Code Map files and make limited edits to navigation.

Using Code Map for Methods Code Map can be enabled by right-clicking any method and choosing Show on Code Map. This command opens a panel to the right of the code editor. A single rectangle with the name of the method should appear. From here, you can right-click the node and display all references. Figure 5-1 shows the references of the constructor of the class FilteredDbSet. It is used by the SetOwnable method.

Figure 5-1.  The result of choosing Show All References in Code Map It is also possible to add code in the Code Map by dragging and dropping files from the Solution Explorer into the Code Map.

115


Chapter 5 ■ Code Improvement Tools

Double-clicking the SetOwnable node opens the code editor to the file that contains this method, and this process of double-clicking can be repeated on SetOwnable. As shown in Figure 5-2, the Code Map can become huge very fast depending on the number of references. Nevertheless, the Code Map has a menu that allows automatic redraws with different visual views.

Figure 5-2.  Code Map for a method with many references So far, to know what class owns the method in the Code Map, we have to double-click the node and see the file opened in the code editor. It is also possible to show the method within its class in the Code Map. Right-click the method and select Show Containing Type. The resulting container opens around the method with the name of the class. Figure 5-3 shows that SetOwnable is still calling FilteredDbSet.

116


Chapter 5 ■ Code Improvement Tools

Figure 5-3.  The result of choosing Show Containing Type in Code Map You can also display the methods that a method calls, but beware of the result of this action. This feature adds a lot of nodes in the Code Map even if your method has only a few lines. To be able to work with a Code Map, the editor has some helpful features like zooming in and out with the mouse wheel and options you can select from the combo located in the command bar. The command bar lets you auto-organize nodes in several patterns, but you still have total control of the location by dragging and dropping any node. At any time, it is possible to export the Code Map result, by choosing Share ➤ Export from the command bar. You can export images and XPS files directly into an email. To help in your debugging, you can add comments by right-clicking and choosing New Comment. It is also possible to flag any method either in the Code Map or by right-clicking any node and choosing Flag For Follow Up. From this menu, you can also change the color of the flag.

Using Code Map for Libraries By using Code Map, you can see the big picture of your solution. Right-clicking the solution and selecting Show on Code Map displays all projects of the solution and their relationships. When you hover the mouse over a node, a small arrow appears that allows you to fetch children. Fetching a project opens a container with all the folders that you have within the project. This process can be repeated until you reach the method. Figure 5-4 illustrates the relationship one level deep. As you can see, the amount of linking is huge. However, because containers are restricted to classes and methods, the information is still usable.

117


Chapter 5 ■ Code Improvement Tools

Figure 5-4.  Code Map for librairies

Finding Cloned Code The Code Clone Analyzer in Visual Studio 2013 is a powerful tool that helps you simplify and improve your code base by showing where duplication occurs. It helps you reduce code elements that have the same structure but not the same name. This tool is available in Visual Studio Premium and Ultimate.

How the Code Clone Analyzer Works You can find clones either throughout a whole solution or within a specific portion of your code. The Code Clone Analyzer is intelligent enough to identify classes, methods, fields, or variables that have different names but the same logic inside. During its analysis it detects the reordering of parameters or those with different names. To activate this feature, select the code for which you want to find any clones, right-click to display the context menu, and select Find Matching Clones in Solution. Another option is to choose Analysis ➤ Analyze Solution for Code Clones. This opens a panel called Code Clone Analysis Results, which groups together code that is similar and allows you to expand each group. Figure 5-5 shows two groups that have two clones each. Double-clicking any line redirects to the code editor.

118


Chapter 5 â– Code Improvement Tools

Figure 5-5.  The Code Clone Analysis Results window The best way to understand the duplication is to select both lines and right-click. The context menu has a Compare option that is the same as when you compare code from a source control. The screen is divided in two, and colors show the difference between the two files.

Refining Results You may not want to analyze, for example, a unit testing project within your solution, because it is not the code that you want to improve. To control that, the Code Clone Analyzer reads .codeclonesettings, which is located in the project whose settings you want to configure. For example, for a unit test project, you can add a .codeclonesettings file at the root of the project and add an XML tag to the exclude file. It is possible to use a wildcard to remove all C# files from the analysis, for example.

Limitations The Code Clone Analyzer has some limitations. First, it finds clones only of statements and not of fields, methods, or properties. Second, during the clone finding of a complete solution, only methods with over 10 statements are analyzed. Third, fragments of code with less than 40 percent similarity are not shown in the result. Designer files are also omitted in the analysis.

When to Use the Code Clone Analyzer The Code Clone Analyzer is useful if you have to maintain code. It lets you determine whether you really need to modify code at several places in your solution or if the logic can be coded only once. The tool also highlights possible refactoring of parts of the code. Instead of modifying multiple pieces of codes that have the same logic, it moves the cloned code into a single method. It increases reusability and avoids duplication.

119


Chapter 5 ■ Code Improvement Tools

If you have divided your application into several solutions, for code clone detection you should also create a single solution that contains all the projects of all your solutions. This approach is recommended because projects can be added to multiple solutions and otherwise may not be analyzed by the tool. The Code Clone Analyzer can then find duplicates across multiple solutions; you might find, for example, that you have to create a shared DLL for these projects to remove the duplicate.

Architecture Tools Editing

UML and Validation

Visualization

Visual Studio Ultimate edition provides a tool called the Architecture Explorer that can display the code in different graphical representations and thus helps you see the dependencies and nodes in solutions. Maintaining a high-level view of your code is difficult, and this tool can give you a fresh view of the situation. It is a tool set you can use to communicate with every developer on your team about the health of the project. The Architecture Explorer is now compliant with the UML 2.0 standard for various diagram types, including activity, use case, sequence, class, and component diagrams. It is also possible to see namespace groupings. Architecture tools can be bound to TFS to verify that classes and projects respect the architecture layers, for example. First we’ll explore the layer diagram, which is one of the higher levels of abstraction that the architectural diagrams can represent. Then, we will go deeper with the sequence diagram, class diagram, and activity diagram; those are the three most-used architecture tools. Finally, you will see a brief introduction to the component and directed-graph diagram types.

Layer Diagrams The layer diagram shows the big picture of all libraries and namespaces that you are using in your solution. It portrays what section of your code can access other sections by specifying which DLL refers to which one (which DLL, section code, or namespace, depending on the level of granularity you have chosen to do the layer diagram). But, you can also specify this level of accessibility with more granularity using namespaces. Under the Visual Studio 2013 Ultimate edition Architecture menu, select New Diagram, and a dialog like the one in Figure 5-6 appears. Here you can choose Layer Diagram, as well as the other diagram types we’ll discuss.

120


Chapter 5 ■ Code Improvement Tools

Figure 5-6.  Choosing Layer Diagram from the New Diagram dialog If you already have a solution with multiple projects, you can drag and drop a project into the Layer Designer (which produces the layer diagram shown at the top of Figure 5-7). This adds layer references to your code. From there, it is possible to right-click the designer to generate visual dependencies. However, the best way to use this tool is not this way. Instead of generating the dependencies, it is better to draw the layer that you want and to drag and drop projects into these layers. You can find the tool-like layer and dependency arrow in the toolbox (Views ➤ ToolBox). Once you have drawn what the layer structure should look like, you can drag and drop into it all the needed layer boxes, existing projects, folders inside projects, or direct classes. This will add a small number at the top right of each layer box. This means that an association is created and represents the number of artifacts linked to this layer. If you want to see the details, you can open the Layer Explorer to show a list of artifacts associated with the layer. You can remove artifacts from this window also.

121


Chapter 5 â– Code Improvement Tools

Figure 5-7.  Layer Designer with errors from validation Once you have your model and your associated code, you can enable automatic validation. Visual Studio can validate your architecture for you if you have followed the initial planning. It verifies links between the code sections and ensures that the entire project respects your architectural design. To validate your architecture, right-click the diagram and click Validate Architecture. This opens the Error List with any rules that have not been adhered to.

122


Chapter 5 ■ Code Improvement Tools

The lower part of Error! Reference source not found. shows that in this example the layer has three errors. The first error says that a Controller uses Mappers. In the layer, no association between the Controller (or Business Logic) and Mapper exists. This is an architectural error, since the code should not have a reference to the Mapper. It may also raise a flag that the architecture may be wrong. This would be a good scenario for the developer to contact the architect and discuss it.

■■Tip To have validation done in your Build Server, add /p:ValidateArchitecture=True in the MsBuild arguments of your agent.

Sequence Diagrams Sequence diagrams are suitable for showing the link between methods calling for specific flows. They are also a UML diagram type, as shown in Figure 5-6. Generating sequences from existing code with Visual Studio is very straightforward. First, select the method you want the diagram to build. Then right-click the code and, in the context menu, select Generate Sequence Diagram. A dialog like Figure 5-8 opens, with options to restrict the graphic’s call depth and scope.

Figure 5-8.  The Generating Sequence Diagram dialog Keep in mind that your diagram will be drawn from the method you have right-clicked. This means that you want to select a starting point from where you want to diagram to display method and not an ending method that you could see the original of the call. Selecting the method you want to know the caller will show nothing. After selecting a sequence parameter, click OK. This creates a UML 2.0 sequence diagram like that shown in Figure 5-9. You can either edit the diagram or right-click and go to the definition to jump back into the code. This tool is perfect for seeing a clean visualization of what happens in a method. For example, Figure 5-9 has been set to 4 degrees of depth. You can see that the MuscleController maps the model to the view model.

123


Chapter 5 ■ Code Improvement Tools

Figure 5-9.  Sequence diagram UML 2.0

Class Diagrams The class diagram is a static diagram that shows all classes in a project, their methods, and the relationships between classes. To create a class diagram, select Architecture ➤ New Diagram ➤ UML Class Diagram. This creates a blank page. From the toolbox, you can draw UML 2.0 components like classes, interfaces, aggregation, compositions, dependency, inheritance, packages, and comments. If you have existing classes, you can use them inside the class diagram. To do so, open the Architecture Explorer by choosing Architecture ➤ Windows ➤ Architecture Explorer. This explorer is different from all other explorers. It goes deeper from the Class view or Solution view and into the namespaces, classes, and methods. Figure 5-10 shows the Class view and the Model Namespace. In the third panel, you can see all the classes of this namespace.

124


Chapter 5 ■ Code Improvement Tools

Figure 5-10.  Architecture Explorer From the Architecture Explorer, you can drag and drop any components into the class diagram editor.

■■Note Modification of the diagram does not affect the code, and vice-versa. Associations between classes are automatically drawn if the dropped class finds a possible association with the code. Figure 5-11 shows two inheritance associations and one dependency association. Before dragging the base model, only the dependency association was shown.

Figure 5-11.  Example of a class diagram generated from the code

125


Chapter 5 ■ Code Improvement Tools

If you do not have the Ultimate edition, you can still use a class diagram, even though it is not generated by the architecture tool. It is possible to create a class diagram using the class designer. To create a class diagram with the class designer, add a new item to a project, and from Visual C# Items, select a Class Diagram. A blank designer opens, and from here you can to drag and drop a solution or classes from the Solution Explorer. Figure 5-12 shows how classes are represented when dragged from the Solution Explorer.

Figure 5-12.  Class Diagram created by the class designer tool A big difference between the Architecture Explorer tool and the class designer is that any modification made in a class designer diagram is reflected in the code. Adding a property inside a class will generate the code that has this property, too. This can sometimes be helpful, but at other times it can be annoying. If you just want to draft a fast possible solution without having the code generated, you cannot. By contrast, architecture tools are there for planning; they do not generate code, whereas class diagrams are there for existing classes that must be synchronized. Changes in the diagram affect the code, and changes in the code affect the diagram.

Activity Diagrams The activity diagram (choose Architecture ➤ New Diagram ➤ UML Activity Diagram) represents system workflow. The diagram shows each step, with possible decisions represented by a diamond shape. It starts with an initial node and ends with a final node. Visual Studio adheres to the rules of UML 2.0. Figure 5-13 shows these activity diagram shapes.

Figure 5-13.  Activity diagram

126


Chapter 5 ■ Code Improvement Tools

The activity diagram has a toolbox that allows you to add flows and decisions between actions. It works like many toolboxes. You first select the item you want to add to the graphic and drag it. When using the activity diagram, be sure the property window is open so you’ll be able to add information. Figure 5-13 shows two guards for a decision shape. One guard specifies that if it is active, execution goes to action 1, while the second guard has an inactive state.

Use Case Diagrams The purpose of the use case diagram is to show the various actors that use a system and the tasks each is allowed to do. This diagram type is used with system requirements because each use case represented by the diagram can be linked to a software requirement. It is possible to add components to the use case diagram to see relationships between components, users, and requirements. Actors in a use case diagram are represented by human shapes. It is possible to specify the name of the actor, like “Customer” or “Administrator.” Actors are linked to use cases by association lines. Oval shapes represent use cases. They have text that represents the specification. Use cases can be shared across several actors and can have dependency between each of them. A dashed arrow represents dependency. Figure 5-14 show dependencies between UseCase2 and UseCase3. A dependency also exists between UseCase1 and an artifact. It is possible to drag and drop classes from the Solution Explorer into a use case diagram. Artifacts can be anything that is a document or diagram. Artifacts are often useful if you want to split your work into multiple use cases.

Figure 5-14.  Visual Studio Use Case example Figure 5-14 shows a subsystem that contains two use cases. This view helps to define the scope of a system. Comments are also supported. The toolbox contains a comment item that can be dropped into the designer. From there, it is possible to add text. To associate the comment with an element, you can use another item of the toolbox, Comment Link. Visual Studio is compliant with UML 2.0 for use case diagrams, too. This means that it is possible to add Include associations and Extend and Generalization links.

127


Chapter 5 ■ Code Improvement Tools

Component Diagrams Visual Studio 2013 Ultimate edition allows you to draw component diagrams. This diagram is a very high level representation of the software system. It has no direct relationship to code files. It shows the communication between systems and interfaces. It is useful for illustrating how software systems interact between each other in an official UML syntax. Figure 5-15 shows at its left the Toolbox. The main item is the Component. A Component is a system or a part of a system or a functionality of a system. Components have interfaces for input and output. Input interfaces can be added to components by using the required interface. Output interfaces need to have provided interfaces added to components.

Figure 5-15.  Component diagram example with the Toolbox open Figure 5-15 also demonstrates in Component1 a required interface, which means it can provide information that can be used by another component. Often, provided interfaces and required interfaces are linked. Provided interfaces can be seen as .NET interfaces or as data contracts in WCF. They are a contract that can be filled by a required interface. Different associations exist. Dependencies are shown as dashed lines from provided to required interfaces. The diagram can visually mark which interfaces can connect to one another. Delegation is shown as a full line that specifies not only which interfaces can connect, but also whether the communication occurs. For example, a component can be accessed by multiple other interfaces (several dependency lines), but only one will finally be used (this one marked as delegation). Generalization association is the inheritance of one component from another. The symbol is the same as in the class diagram; a white arrow. Finally, you can add comments to any item of the diagram.

Directed-Graph Diagrams The directed-graph diagram is the final type of graphic you can create using Visual Studio 2013 Ultimate edition’s architectural tools. This one does not have any toolbox. Items can be added by using the Solution Explorer and the Architecture Explorer. This tool is not useful at the beginning of a project, but is in the maintenance phase. If you have to jump into a project that has already been created, and it does not have any diagram that shows the big picture of its references, the directed-graph is here to show those code references.

128


Chapter 5 ■ Code Improvement Tools

When you drag a project from the Solution Explorer, the DLL appears. It is possible to expand the DLL further using the left arrow icon; Figure 5-16 marks the arrow to expand the library. If you want to collapse an expanded library, select the node and go into the property panel. Under the Misc category, a Group property can be set to Compact or Collapsed. Or simpler still, you can click on this arrow again to collapse the library.

Figure 5-16.  Directed-graph diagram DLL not expanded Generating the graph can be time-consuming, because the tool calculates every reference. If you have nothing extended, the result should look like Figure 5-17. You can see the references between projects.

Figure 5-17.  A completed directed graph in the Diagram Designer When you expand a project in this view, you will have a box with the namespace that it contains. Visual Studio does a great job of not cluttering your vision by revealing only the arrows to expanded projects when your cursor is on another project. For example, in Figure 5-18, the cursor is above the DataAccessLayer DLL. Visual Studio shows only references from DataAccessLayer to Model. Selecting any item enhances its association, which is marked with darker arrows. All of these designer functionalities make this an interactive graphic. It is also possible to share the generated graphic, but without the additional information.

129


Chapter 5 ■ Code Improvement Tools

Figure 5-18.  References to an expanded DLL The directed-graph diagram can go inside a property to show its getter and setter. This means it is possible to know which class uses a setter from a property across the system. The capabilities of this graphic make the tool a very important one when it is time to take a look at a system that has been built by others.

Code Metrics Code metrics are a part of software engineering. They allow you to measure the health of the system and to evaluate how hard or easy it is to maintain the code base. Visual Studio offers a Code Metric tool that can compile a list of metrics, such as the number of lines of code, depth of inheritance, class coupling, cyclomatic complexity, and maintainability index. Code Metric is available for Visual Studio Premium and Ultimate editions. To analyze a project or solution, choose Analyze ➤ Calculate Code Metric for Solution. If you select a project, a new entry in the menu will be available to calculate for the selected project. I suggest that you use the solution; the calculation is very fast. It gives a better overview of the health of the software.

Lines of Code The Lines of Code reported in the Code Metric results are based on the interpreted lines of code. This number represents the lines of code developed by developers and generated by the Visual Studio compiler to be interpreted by the .NET virtual framework. The Lines of Code tool gives a portrait of how hard some methods will be to maintain. The theory is that a method with many lines of code is harder to maintain. The number shown must be low to be good. Label (1) in Figure 5-19 shows a project with 702 lines of code. This can be subdivided by namespace (2). It starts to get interesting with the statistic of classes (3). You can see, for example, that the AccountController has 88 lines, and the HomeController has 10. The AccountController is harder to maintain. This is a good start to know where to check and see whether some logic can be extracted from the controller to other classes. Classes are useful, but methods are even more helpful. The display shows a metric for each method. At (4) are all lines of code for each method of the WorkoutController. All methods have very low line counts, which indicates good maintainability.

130


Chapter 5 ■ Code Improvement Tools

Figure 5-19.  The Line of Code metric

Depth of Inheritance The Depth of Inheritance metric indicates the number of inheritances a class has, and it is only available for classes. Methods do not have this metric, as you can see in Figure 5-20, which shows blank cells for methods. It also shows that the WorkoutController has a high number, five. Only two of the five inheritances have been created by user code. The other three are from the .NET framework. The meaning of this metric must be analyzed deeper before you can reach any conclusions.

131


Chapter 5 ■ Code Improvement Tools

Figure 5-20.  Depth of Inheritance is one of the columns that appear in the Code Metrics Results window

Class Coupling The Class Coupling indicator measures class variables, properties, methods, interfaces, attributes, and return types. Every time a piece of code goes to an external class, it adds coupling to another class. Figure 5-20 shows some classes coupling. A low number is best. If a number is zero, it means that the class does not use any external classes. The theory is that the class coupling should be very low because that results in code with fewer links between classes. A low level of links means that every part does a specific task, which could be isolated for future replacement or testing. A result under 10 is very good. However, a low level of coupling is more difficult to achieve once you’ve created a software application that interacts with a lot of different logic. Nevertheless, it is always possible to divide the logic over more classes. This increases the number of classes but simplifies the testability of the code.

Cyclomatic Complexity The Cyclomatic Complexity statistic calculates the number of different paths the selected code can have. This metric analyzes all paths to provide a number that is not bound to a possible range because it increases as the code has more IF, While, Switch, and Loop structures, and greater recursiveness. The resulting number is the number of paths from the start of the code to the Return statement. In Figure 5-20 you can see that the workout controller has a high number of 34. The reason is a single method named EditWithSessionEdit. This method has a loop that contains a loop condition. The code is not pretty. Cyclomatic complexity found this method. It is also interesting to see that for this method, the coupling is very high, too, indicating that something is wrong with this method. A good rule of thumb is for cyclomatic complexity to be under 10 for each method.

132


Chapter 5 ■ Code Improvement Tools

Maintainability Index The Maintainability Index is the first metric to have a boundary. It goes from 0 to 100. The objective is to have a high index number. The interpretation of this index is not linear. An index between 0 and 9 means that this part of the code is not maintainable. A warning is raised if the number is between 10 and 19. Between 20 and 100, the code is maintainable. Of course, the higher the number, the better the maintainability is. The index is calculated by combining the line number, the cyclomatic complexity number, the Hallstead complexity measure (calculation with the number of operations and operators), and other factors. Figure 5-20 shows a score of 46 for EditWithSessionEdit. It is not catastrophic, but it is low compared to the rest of the project.

Static Code Analysis Visual Studio 2013 Professional, Premium and Ultimate have the Static Code Analyzer. This tool gives you a portrait of the code for elements of the code that can be found without having the code running. It can be launched manually, by choosing Analyze ➤ Run Code Analysis on Solution, or automatically. Automatic code analysis can be activated in a project property under the Code Analysis tab. Visual Studio 2013 offers a new feature with the Code Analysis panel. Instead of using the Error List panel, the analysis now has its own panel. This makes it easier to read all of an analysis than before.

The Code Analysis Panel The Code Analysis panel shows the rule number that has been violated, the rule name, and the file in the problem. Double-clicking an entry moves the code editor into the part to be changed. The panel also categorizes the rule. It is possible to sort by categories to focus on a specific type of problem if you have a lot of rules not respected. Figure 5-21 shows the panel with some results. First, the command bar at the top of the panel allows you to analyze only a project if required. In the screenshot we’ve chosen to see every project. It is possible to apply sorts by properties like rule number, categories, and so on. The Settings dialog lets the developer choose the set of rules to apply. We will see this feature a few times throughout Visual Studio 2013.

Figure 5-21.  Code Analysis Result panel

133


Chapter 5 ■ Code Improvement Tools

Results are listed one by one, with the rule number as a hyperlink that opens MSDN documentation with a description of the rule, the case, and how to fix the violation. Examples are also available. The rule number is followed by the rule name. Under this line, the file name, line, and category are shown. Figure 5-22 shows the dialog that opens if you click Code Analysis ➤ Settings.

Figure 5-22.  Solution configuration for project rules For each project, it is possible to choose what set of rules to use. It is also possible to configure these sets of rules. This dialog window is also available in the Analyze menu under Configure Code Analysis for Solution. You’ve just read about Visual Studio’s Code Analysis tool, but other static code analyzers are available, including FxCop and StyleCop.

FxCop, StyleCop, and Code Analysis FxCop is a very popular option and runs with binaries, whereas StyleCop runs with source code. StyleCop is limited to C# and does not accept F# or Vb.NET. This is where FxCop shines, because it uses compiled codes and can be used with any .NET compiled code like C# or Vb.NET. However, it cannot analyze proper code formatting like spaces, braces, or comments. FxCop is free and included in the Microsoft Windows SDK. It is a command-line tool that can be used by Visual Studio or a build server. Visual Studio Code Analyzer is very similar to FxCop. StyleCop is open source and can be found on CodePlex. It focuses more on the code formatting. If you are using the third-party ReSharper with the Inspector feature, then you are already somewhat familiar with StyleCop rules.

134


Chapter 5 â– Code Improvement Tools

Summary In this chapter, you have seen a lot of Visual Studio tools to improve your code. The first tool was using the Code Map feature to help find different paths in your code. Then you saw that the code clone analyzer can find similar blocks of code even if they do not share the same semantics. For Visual Studio Ultimate edition users, the diagrams available through the Architecture menu are also a huge part of the code improvement toolset; they are very useful for application architecture. They are in compliance with UML 2.0 standard, and include different diagrams like layer, sequence, class, activity, use case, component, and directed graph. Finally, you saw how to view code metrics, and how to enhance the health of your code with automatic analysis.

135


Chapter 6

Testing Your Applications Testing is a part of the application life cycle that you must do naturally to ensure that the specifications are fulfilled. Visual Studio provides tools for testing, including unit testing, code coverage, and performance testing. These tools will simplify your life. From unit testing to improve your code quality to load testing for performance, this chapter will guide you through Visual Studio’s testing features. In addition, this chapter shows you how to test Windows Store Applications and briefly introduces the exploratory testing platform.

Unit Testing and Code Coverage Unit testing is the most basic type of test that every piece of software should go through. It allows for testing every class while ensuring results. Visual Studio has a powerful framework for the creation of unit tests. It also has tools to run these tests in a few clicks. This section discusses unit testing with Visual Studio, along with a couple of related topics—coverage testing, to track which parts of a project have been unit tested, and the Microsoft Fakes framework, which provides testing tools known as shims and stubs.

Unit Testing Unit testing is popular in every language. A unit test is a simple test of a single task. Every tested unit must return a value that is asserted against an expected value. Visual Studio has built-in templates for unit testing. You can add a Unit Test Project by choosing File ➤ New Project ➤ Visual C# (or Visual Basic) ➤ Unit Test Project. This creates a new project and a default file with the skeleton of a simple unit test. This project also contains by default a reference to Microsoft.VisualStudio.QualityTools.UnitTestFramework. This reference specifies attributes to be used in unit tests. It also provides classes to assert values. Using this reference, Visual Studio can start unit tests and give a green or red flag if an assertion is true or false. Figure 6-1 is an example of the default file generated when a new Unit Test Project is added to a solution. TestClass (1) is the attribute that must be added to a testing class to join Visual Studio Testing mechanisms. All tests must have this attribute. At (2) is the start of a test method to be used. Every test method must be marked with the TestMethod attribute. A test class can have many tests. Finally, at (3) is an example of an assertion. Testing attributes and assertion methods are abundant in their namespace. The unit test framework has an attribute to specify methods that must be executed between each test. This type of attribute is useful for initializing values between tests. Assertions can compare values, verify if a value is null, verify if something is false, and perform many other comparisons.

137


Chapter 6 ■ Testing Your Applications

Figure 6-1.  Example of the default unit test skeleton Once created, a unit test needs to be executed. To execute unit tests in Visual Studio, choose Test ➤ Run. From the screen that results, several actions are available. Figure 6-2 shows that it is possible to execute not only the Selected Tests but also optionally All Tests or various groupings of tests.

Figure 6-2.  Visual Studio Test menu and Run submenu The first option, Selected Tests, is perfect when you’re developing and testing at the same time (which is a development model called test driven design). The All Tests action is perfect if you want to capture a global portrait of the system. Modifying one part can affect other parts, and by executing every test, it is possible to see if something has changed in its behavior. Four other options are available. Visual Studio can run all previously Failed Tests. This is useful if you ran tests that failed, then made corrections, and now want to verify that the correction has changed the result. You can also execute all Not Run Tests—those that have never been run yet. This is useful if you are developing new tests and want to have fast development. You can also run all previously Passed Tests; however, this is less often used. It is also possible to Repeat Last Run. It executes the same batch of tests from the last time Visual Studio ran tests.

Code Coverage Code coverage simply means keeping track of which portions of your code have been tested. A tool for analyzing coverage is available in all editions of Visual Studio. This means that when a method is executed within a unit test, it is marked as covered. It does not mean that covered code is without problems; it simply means that at least one test has executed the statement. To access code coverage in Visual Studio, choose Test ➤ Analyze Code Coverage ➤ Selected Test or

138


Chapter 6 ■ Testing Your Applications

All Tests. In both cases, unit tests are executed, and Visual Studio records all paths. The result is displayed in a coverage panel, which is saved into a TestResult folder of the solution. However, this format is only for Visual Studio. If you want to export the test results for your personal use, the Code Coverage Panel allows you to export them into XML. Figure 6-3 shows this export feature in its action bar at the top of the panel (1).

Figure 6-3.  The Code Coverage panel The result of the class tested is highlighted at (2). As you can see, only 75% of the code is covered for the class and for the method. This is normal because the class has only one method and the result is the same. To determine which statements have been covered, you can click icon (3) to display a red highlight over any line that has not been executed. Figure 6-4 shows what this looks like. In this case, the reason the code was not executed is that the parameter was set to False during the test. In fact, a test should test this method as True or False. The result of the code coverage would be 100% after this change.

Figure 6-4.  Coverage highlighted on the code Code coverage is beneficial in providing an overview of which parts of an application have not been tested at least once. However, this tool must be used with a deeper analysis of what is being tested and what is not. Once the code has been covered, a second thought must be incorporated into the analysis. Are there other possibilities for testing for something already tested? This is often the case with boundary values. For example, if a method takes an integer in a parameter, it is a good idea to validate a negative number, zero value, and a positive value.

139


Chapter 6 ■ Testing Your Applications

Microsoft Fakes

The Microsoft Fakes framework is a library that was added in Visual Studio 2012. It is available with Visual Studio 2013 Premium and Ultimate versions. It allows you to fake an assembly. It simplifies code testing by making it possible to transform existing compiled code into a proxy class that allows you to inject return values. Microsoft Fakes has the advantage of letting you change values from almost anything inside a compiled library. To generate the proxy classes, commonly named fake classes, open the References of the testing project and right-click to open the context menu. It is important to note that you can only fake a class that is not inside the same assembly as the unit test. Figure 6-5 shows the context menu of a library that will generate fakes.

Figure 6-5.  Microsoft Fakes Clicking Add Fakes Assembly generates a Fakes folder in the testing project. The folder should contain one file per assembly. This file must have the name of the assembly with the extension .fakes. In fact, this file is an XML file that contains information for Visual Studio.

Shims The Microsoft Fakes framework allows two testing strategies. The first one is called a shim. Unit tests must declare a context where all instantiated classes that use the shim must reside. This context uses the class ShimsContext from the Microsoft.QualityTools namespace. Figure 6-6 (1) shows how to declare a shim context.

Figure 6-6.  Example of a Shim test

140


Chapter 6 ■ Testing Your Applications

Label (2) shows that before invoking the method to test, we have to shim the method. Figure 6-6 shims Method2, which returns an integer. This method is called by the tested method, Method1. It is private. Microsoft Fakes, with the use of a shim, allows you to change the private method to a specific value. The benefit of this is that it focuses a test on the tested method without having to execute inner methods. In addition, as in this example, the private method returns unexpected integers (like random numbers). When doing unit tests, it is a good practice to test boundary values. Having a shim lets you specify all boundary values of inner methods without having to modify your code.

Stubs Another possibility is to use a stub as a testing strategy. With this approach, no context is required. The framework allows you to create concrete classes for interfaces without having to create tests for each of your concrete classes. For example, if an interface has a method that returns an integer, you do not need to create three classes to test with negative, zero, and positive values for the method. In fact, you just use a stub for this interface that returns the value for the test. Figure 6-7 shows the use of the generated Fakes class to instantiate the Stub of the interface.

Figure 6-7.  Example of a Stub test Within this class, we can define the return value of any methods of the interface. The arrow in Figure 6-7 shows that the method stubbed for this test is named MyMethodInt32. For this test, the parameter value is simply returned. With this stub, we can expect to have the value 2 since we are passing this value by using a parameter. All boundary values can be tested without having to create any classes. The main advantage of using stubs is that they allow you to create a fast replacement class to supplant interfaces with a concrete class without having to define a lot of code. However, the disadvantage is that it uses fake classes and not the real ones. This is why it is recommended to use other mocking frameworks for an interface rather than stubs.

Load Testing and Web Performance Testing Load testing is often required on multiuser applications like web applications. It allows you to test the code by running multiple occurrences in a short period. Load testing and performance testing require Visual Studio Ultimate edition. This section walks you through all the steps to create stress tests for your application. For load tests and web performance tests, a unique project must be created. Figure 6-8 shows the New Project window under the Test category.

141


Chapter 6 ■ Testing Your Applications

Figure 6-8.  Creating a new Web Performance and Load Test Project

Load Testing To create a load test, first add a new item to the Web Performance and Load Test Project. This opens the New Load Test Wizard, which consists of about ten steps. After a first screen of some instructions, the second step lets you name your test scenario. This enables you to create multiple load tests for different scenarios. On this wizard page you can also set the Time Profile to define how the time is calculated between the navigation of pages. The third step, shown in Figure 6-9, allows you to choose a load pattern to simulate. You can have a Constant Load of users or have Step Load increment the number of users at different invervals. Figure 6-9 shows a configuration set to a finite number of users for the test.

Figure 6-9.  Choosing a Load Pattern for the Load Test The fourth wizard step executes the test mix (Figure 6-10). It specifies the probability of a load user running a test in the test mix. In a similar format, the fifth step adds tests. You can add unit tests, but real load tests should add a web performance test. Web performance testing is covered in the next section. This wizard step lets you customize the load test’s distribution. The total distribution is automatically adjusted by Visual Studio to a fixed 100%.

142


Chapter 6 ■ Testing Your Applications

Figure 6-10.  Tests in the mix with distribution In the next step you select the network mix. By default, it is a LAN, but a test can be simulated from 3G to Cable or Dial-Up. Finally, you can add monitoring performance counters and agent machines if you’re working in a distributed environment. Otherwise this screen is usually left empty. The last step configures the load test duration or the number of iterations that must be performed. Figure 6-11 shows the two different configurations. The load test can have a Warm-Up Duration; this specifies the time before Visual Studio starts recording sample values.

Figure 6-11.  Load Test Run settings To execute the load test, open the .loadtest file of the performance project you previously created, and click the Run Load Test button at the top of this window, indicated by the arrow in Figure 6-12.

143


Chapter 6 ■ Testing Your Applications

Figure 6-12.  Load Test Execution Bar with Run Load Test button The results are exhaustive. Figure 6-13 shows only a small portion of what is available. You can display a summary (1) that indicates the starting time and ending time with all information configured previously. It gives the number of results executed for each test and the number of tests failed. Information is listed about the machine processor and RAM. Graphics are also available (2). You can select which counter you want to display and export to Excel (3).

Figure 6-13.  Load Test Graph results

Web Performance Testing A Web Performance Test is an item that can be added to a Load Test and Web Performance Project. Right-clicking on the test project, selecting Add, and choosing Web Performance Test is the fastest way to create a web performance test. However, be sure that your website is running, because this step will launch Internet Explorer and start recording. By default, Visual Studio uses Internet Explorer, but you can configure it to use the browser you desire. Once the performance test is launched, a plug-in will record all your steps and communicate the information to Visual Studio. It is required that you enable this plug-in; otherwise, nothing will be sent to Visual Studio and the test will remain empty. If you are testing a website in debug mode with Visual Studio 2013, you may see BrowserLink requests. You can remove these requests when the recording is over. BrowserLink is a Visual Studio mechanism that communicates with browsers. We will cover BrowserLink in Chapter 9.

144


Chapter 6 ■ Testing Your Applications

The Web Performance tool records every request and can execute them later. Figure 6-14 is a snapshot of the result of a web performance test.

Figure 6-14.  Web Test Performance results Web Performance is helpful with load testing because it simulates the loading of real pages containing images, JavaScript, CSS, and HTML requests. It can also easily simulate a different Active Directory account if you are working with an intranet. To do so, use the Set Credential action in the toolbar. From the Web Performance toolbar, you can also convert the test into code. This allows you to have full power over what it is executing. However, code cannot be converted back to a test. It is always better not to convert the test into code, because if you do, you will lose the test tool capability of setting the test for you. It is also possible to add a data source to a database using a CSV file or XML file. This is useful if you want to associate an HTML form with custom data that changes during tests. Once the data source is created, you can open the HTTP request, for example the account login, and change the HTTP input user name and password by opening the property panel and binding the field with the data source. Figure 6-15 shows a request open, and the property panel with the value set to the CSV file.

Figure 6-15.  Binding a CSV file to Web Performance test HTTP parameters Several other options are available with Visual Studio and Web Performance. It is possible to customize almost everything, like having URL source coming from an external list, or to create transactions for some tests. It is possible to add loops to tests that allow you to repeat actions that have been done once in the recorded test. Other options, like validation rules, can be added. It is possible to add validation about request times, form fields, response URLs, and similar items. This tells Visual Studio to hook some information into the test, such as the memory usage, the CPU activity or HTTP request time. Such a test can raise flags if one of these metrics reaches a specific threshold for each validation. For example, if a request takes more than 1 second, then you can have validation rules to raise a flag.

145


Chapter 6 ■ Testing Your Applications

Testing Windows Store Applications In this section, you will learn how to create a UI test project and how to run Windows store applications from Visual Studio with the emulator. Remote debugging is also described as the last subject of this section

Coded UI Test Project Coded UI tests (CUIT) and the Coded UI Test Builder are a new feature in Visual Studio 2013 for debugging Windows Store applications. To be able to use the Coded UI Test, you need Visual Studio 2013 and Windows 8.1. Under your favorite language, and under Windows Store, you’ll find a new project template. It is named Coded UI Test Project (Windows Store). This automatically opens a generated code dialog that offers two options, as shown in Figure 6-16.

Figure 6-16.  Generate Code dialog The first option, Edit UI Map Or Add Assertions, allows you to edit with a cross-hair tool. It opens a tool that you can use to click any Windows Store application element to then edit it. The second option is for manual testing. It does not generate any code. The shortcut Ctrl+Shift+I will open the property window for the UI. Once you have selected all elements you want to use in your test, you can click the last button of the UIMap toolbar to generate the code and UI map file (Figure 6-17).

146


Chapter 6 ■ Testing Your Applications

Figure 6-17.  UIMap toolbar for Coded UI The map file contains information about the UI in a tree view, as shown in Figure 6-18.

Figure 6-18.  UI Control Map With this UI Control Map, you can also use the Gesture API to interact with all of the XAML controls listed in the map, as shown in Figure 6-19.

147


Chapter 6 ■ Testing Your Applications

Figure 6-19.  Example of test with UI Control Map Code generated by a UI Control Map can be executed like any other unit test. The difference is that, in this example, your computer will launch the Windows calculator, and you will see that the specified buttons have been tapped because the //Act portion of the test simulates the gesture of tapping the button. Then the test closes the calculator. If the result is the one expected, which should be 56, the test passes.

Visual Studio Remote Debugging Visual Studio Remote Tools enable you to debug a Windows Store application that runs on a machine other than your development machine. The main goal of using remote debugging is to gain the benefits of functionalities that your computer may not have, like gesture with touch or an accelerometer. Remote debugging is not very easy. It requires a complicated setup, but once installed it works pretty well. First, be sure that both devices are connected on the same network. Remote debugging works only on a LAN, not over the Internet. The remote device, for example a Windows Phone, must have a developer license installed. Finally, be sure that no firewall is on during the test. The remote debugging tools are not installed in Visual Studio 2013 by default; you must download them. They can be found by searching “Visual Studio Remote Tool VS 2013” on any search engine. The download is about 50 MB, and it takes about 5 minutes to install.

■■Note

Remote Debugger is installed in the Common7 folder. For example, on my machine the path is

C:\Program Files\Microsoft Visual Studio 12.0\Common7\IDE\Remote Debugger.

The next step is to start the Remote Debugger Configuration Wizard. This configures the Remote Debugger security settings. Then, you need to start the remote debugger by double-clicking RemoteDebugger.exe. Finally, you can set up the debug within Visual Studio on a Windows 8 App project. Open the project’s property window, as shown in Figure 6-20, and choose the Debug panel. From here, you can select a remote machine as the target device. This is also the place where you specify the remote machine. If the remote machine name does not work, try the IP address instead.

148


Chapter 6 ■ Testing Your Applications

Figure 6-20.  Debugging a remote machine Before starting Visual Studio to debug the remote application, be sure that the remote devices, such as the Remote Debugging Monitor, are running. Once they are running, you can choose Start Debugging from the Debug menu. Visual Studio will send the program to the remote destination and start debugging as if you were on your machine.

Visual Studio 2013 Windows Phone Emulator In some cases, you may not have access to the hardware to test your application. This is often the case with Windows Phone apps. Visual Studio can connect to an emulator for Windows Phone. The emulator is a Windows Phone application that simulates the real Windows Phone. The main advantage of the emulator is that it can test multiple resolutions without requiring you to purchase multiple devices. Before going any further, note that Visual Studio 2012 SP3 or Visual Studio 2013 must be used. Any previous version will not work with emulation. Your computer must also support hardware virtualization to run the emulator, which runs inside Microsoft Hyper-V. This means that you must have a computer with SLAT (Second Level Address Translation) support. The first step is to get the emulator. Like the remote debugging tools, it must be downloaded. The emulator is included with the Windows Phone SDK. I suggest that you search for “Download Windows Phone SDK” and install the package. If you open the project’s property window and select Debug, you can choose Simulator as the target device. You can also choose the emulator type from the toolbar, as illustrated in Figure 6-21. If you choose Execute, the code is published and executed. You can debug any code that you have on your computer.

149


Chapter 6 ■ Testing Your Applications

Figure 6-21.  Emulator Device choices

Microsoft Test Manager Microsoft Test Manager comes with Visual Studio Test Professional. If you have Visual Studio Ultimate or Premium, the Test Manager is also installed with your initial installation. However, Visual Studio Test Professional is a special edition of Visual Studio designed for testing. The difference between Team Web Access and Microsoft Test Manager is that Web Access allows you to create test cases but not record steps, add automatic screenshots, or add an IntelliTrace log and other data. Microsoft Test Manager is perfect for people who are testing only, without doing any coding. The first topic of Microsoft Test Manager is exploratory testing.

Exploratory Testing Exploratory testing records your actions while performing a test. It can be used for Windows applications or for web applications. For Windows Applications, the executable must be on the same machine as the Microsoft Test Manager. If it is a web application, only the browser needs to be on the same machine as the Microsoft Test Manager. Open Microsoft Test Manager and click the Test tab at the top of the Testing Center. Click Do Exploratory Testing in the menu that appears. See Figure 6-22.

Figure 6-22.  Testing Center with exploratory testing

150


Chapter 6 ■ Testing Your Applications

This window has an Explore button that when clicked will start recording your movements. Be sure to have the web server running if you are using a web application. This will remove some noise on the recorder. The Microsoft Test Manager has a Test Runner window that allows you to add comments when doing actions or to add screenshots to different steps of your test. If a bug is found during the test, all of your steps can be added automatically to a bug item in Team Foundation Server; this will be covered in Chapter 7. It is also possible to create new test cases from a sequence of actions you just recorded. This allows you to run all the actions without having to type all the steps. During the recording, it is possible to pause if you need to enter a credential (user name and password). If you do not pause the test recorder, your credential will be saved with the test, which could compromise your information. You can see any test you have performed by choosing Test ➤ View Exploratory Test Session. You can see if you have linked the test session to bugs or test cases. You can see your comments, screenshots, and all steps that were recorded. Steps are located under the Attachments portion of the session, as shown in Figure 6-23.

Figure 6-23.  Test session steps Microsoft Team Manager lets you visit test sessions. The Testing Center’s Test ribbon (look back at Figure 6-22) includes another action, View Exploratory Test Sessions, which lists all tests sessions. It is possible to see the owner but also which items are associated with this one. Double-clicking any test session opens the details of it with all steps, images, and comments. If the bug is related to a Test Case and was recorded during any session, it is possible to play back a test. Creating a bug during a recording session is a rich experience because many fields are already filled for you. The steps to reproduce the bug are set from the recording step. You just need to set a title and assign the bug. It is also possible to create a test case from a test bug that was created by a recording session.

Lab Center Microsoft Test Manager’s interface is divided in two. So far, you have seen the Testing Center, but it also has a Lab Center. The Lab Center can be opened at the top the workspace. Figure 6-24 shows where to click to change from the Testing Center to the Lab Center.

151


Chapter 6 ■ Testing Your Applications

Figure 6-24.  Lab Center The Lab Center allows you to set up Lab environments, Test Settings, a Library, and Controllers. A lab environment is a cluster of computers managed by a central point. It lets you record information about the environment in which the test is occurring. For example, if you are testing a website, the environment consists of the web server and the database server. From the Lab Center screen, you can set up a machine that can be used for testing and collecting diagnostic data while you are coding. You can also set up a virtual Environment with a virtual machine. This is a very advanced operation, and it displays all machine states. On the other hand, the Test Settings Manager (Figure 6-25) controls the diagnostic data adapters. For example, action recordings, action logs, event logs, system information, screen captures, video capture, and voice recording can all be specified here. By default, screen and voice recording is disabled.

Figure 6-25.  Lab Center and Test Settings

152


Chapter 6 â– Testing Your Applications

Summary In this chapter, you saw how to test your applications with Visual Studio. You learned how to unit test code and how to analyze what has already been tested to avoid duplication. You also learned how to modify method return values with Microsoft Fakes. We then explored types of testing that go beyond the popular unit test. These tests are aimed at evaluating performance and include load tests and web performance tests. Both provide statistics from defined tests that can be repeated. In another aspect of development, you saw how to test Windows Store applications with Coded UI Test. The chapter briefly showed how to do remote debugging and how to use an emulator for Windows Phone, and finally introduced Microsoft Test Manager.

153


Chapter 7

Teamwork with Visual Studio Visual Studio is more than just a coding editor. In combination with Team Foundation Server (TFS), it can set up management of your whole development lifecycle. This integration has the benefit of providing a central place for your team to track everything and at the same time introducing collaboration tools. This chapter starts with a presentation of TFS Source Control and its integration with Visual Studio. You will also see how to review your team’s code by using tools instead of a manual process. This chapter also looks in depth at work items, which are at the heart of all processes like source control, project schedule, bug tracking, and Microsoft agile tools.

How to Use TFS Source Control This chapter starts with source control because Visual Studio and TFS Source Control are the best-known features of Team Foundation Server. In most cases, developers do not realize that many other tools come with those two software programs. Nevertheless, it is important to know how you can use TFS Source Control with Visual Studio. This introduction will show you how to commit your code to TFS server, how to get source code from a teammate, how to do branching to divide your work into different code paths, and how to use labels and history. You will also learn about annotation, shelving, and other techniques.

What Is a Branch? To answer the question of what a branch is, you first need to know that TFS Source Control always has a main repository for your project, known as the root, or the trunk. The first branch of any project is a copy of the trunk that will create a new parallel line of development. The goal of branching is to maintain a copy of the code that is isolated from all other branches. This means that you can branch from a branch or branch from the trunk again. It allows parallel development without affecting other people’s work. For example, if you are working on software that must integrate a module that is planned to take several weeks of development, you may want to develop this feature in a different branch than your main one. Doing so will keep the trunk stable and available for smaller updates and releases. How does TFS keep the trunk stable? Every time code is checked (pushed) in, the code is saved for the branch only. With TFS, a branch maintains a link with its parent, the initial source of the branch. For example, if it is your first branch, the parent is the trunk. This means it is possible to push back the code from the branch to the parent. However, it is not possible to merge from a branch to another branch that is not a parent-child relationship without losing the history. If we go back to our example, once the team has finished its work after a few weeks, the code must go back to the main branch for release. This process is called merging, and it will be explained soon. This is possible because the branch knows its parent. It would also be possible to create a branch from this branch. In that case, the grandchildren would be able to commit to their parents and to the main. It is a chain of communication for the code. Visual Studio allows you to create branches by opening Team Explorer (Figure 7-1), which opens the Source Control Explorer for your TFS server.

155


Chapter 7 ■ Teamwork with Visual Studio

Figure 7-1.  Visual Studio Team Explorer From here, you can right-click the trunk and select Branching and Merging from the context menu, as shown in Figure 7-2, and choose Branch. As you can see, the action is located above Merge in the same menu because these two actions are related. One creates a new path of development, and the other merges them back together.

Figure 7-2.  Branching and merging with Visual Studio

156


Chapter 7 ■ Teamwork with Visual Studio

This option brings up a dialog window that lets you choose the source branch and a target branch to create. The target branch must not be under the folder of the source, but it can be at the same level. For example, you can have the following structure:   $/YourProject/Code/Main $/YourProject/Code/Branch1 $/YourProject/Code/Branch2   But you cannot have this:   $/YourProject/Code/Main $/YourProject/Code/Main/Branch1 $/YourProject/Code/Main/Branch2

Merging Your Code Merging occurs when you move the code from TFS to your machine, or when you want to push the code from one branch to another branch. The goal of merging is to decide which version of a piece of code is the one that should remain in the future. Most of the time, TFS can automatically merge changes. For example, if you and your teammate are working on the same branch and check in code in the source control, and then you want to get this code, you will choose Get Latest Version. Figure 7-2 shows Get Latest Version as the first action in the context menu. It is at the top of the menu because it is a frequently used operation. This is to be sure that you are working with the latest version of the code. The merging action is in the context menu of all branches in the Source Controller Explorer. Figure 7-3 shows that the first step to merging code is to select the source branch and target branch in the Source Control Merge Wizard.

157


Chapter 7 â– Teamwork with Visual Studio

Figure 7-3.  Merge Wizard You can merge two pieces of code that do not have a parent-child relationship, but it is not recommended. The action is called a baseless merge. A baseless merge usually has more conflicts because it has fewer similarities. After performing a baseless merge, TFS merges histories and creates a relationship between the two branches. Sibling branch merges are automatically baseless merges. It is preferred to merge to the parent and then back to the sibling.

Resolving Conflicts Merging takes your code and your teammate’s and aggregates both modifications. In the case that two team members are working on different pieces of code, TFS will automatically merge files. However, if the code has changed at the same place in both versions, Visual Studio opens a Resolve Conflicts window, which contains a list of all conflicts. From there, you can choose which version to keep, but you can also go deeper into each file conflict and choose, line by line, which line should be used. In some scenarios, it would be possible to choose both versions. For example, suppose there are two new methods added at the end of a class; once the code is merged, you must commit the file to TFS Source Control to share the result of your merging with other team members.

158


Chapter 7 ■ Teamwork with Visual Studio

The Resolve Conflicts window appears when you get the latest version of a piece of code only if conflicts are present. However, it is possible to go to View ➤ Other Windows ➤ Pending Changes or open the Team Explorer panel and click Pending Changes. To resolve any conflicts, click the Actions button (1) to the right of the Check In and Shelve buttons, as shown in Figure 7-4. Select Resolve Conflicts. This will open the Resolve Conflicts window, which contains a command bar (2) that includes an AutoResolve All button, a Get All Conflicts button, and a Refresh button.

Figure 7-4.  The Resolve Conflicts window

Change Tracking Visual Studio has the capability to display a visualization of the branches. This can be helpful by providing an overview of how you can merge code later. Figure 7-5 shows a trunk called Main, and it has several branches. The Prod/PreLivrable.Dev code has been branched a few times. This window can be accessed at any time from the History window by right-clicking and choosing Tracking Changeset.

Figure 7-5.  Example of the Tracking Changeset window

159


Chapter 7 ■ Teamwork with Visual Studio

It is also possible to click the Tracking Changeset icon at the top of the History window, as shown in Figure 7-6.

Figure 7-6.  Tracking Changeset in the History window The toolbar can be filtered by branch names or can display all branches. It is also possible to know what happened more specifically by using Timeline Tracking. Figure 7-7 shows the merge time, horizontally and vertically, for all branches. It is possible to know the Changeset that has been merged from branch to branch. You can see that on July 2, 2013, the code was merged to the branch Iteration4, to the Main, and so on.

Figure 7-7.  Visual Studio Timeline Tracking

■■Note  Visualization has been enabled by default since TFS 2010.

Checking In and Checking Out Code At some point, if you want to save your code into TFS, you must send this code to the server. Sending code is called a check-in. You check your code into TFS. When the file is sent to TFS and you are using it, Visual Studio has by default the ability to check out a file when it is modified. However, it is also possible to check out a file manually. Manual checkout can be done in the Team Explorer or the Solution Explorer. Just select a file you want to check out, right-click, and select Checkout for Edit. A code file that is checked in does not change its status in TFS. However, checking out code marks the file with your username. Thus, it is possible to know who is working on which file.

160


Chapter 7 ■ Teamwork with Visual Studio

The best practice with checking-in is to get the latest version of the code first. This allows you to get all new code on your machine to merge any conflicts, to compile and test, and then to push all the code back to TFS. It allows you to make those changes and compile them before sharing the code. Otherwise, checking in code without having the latest version can cause overwriting code from others. Visually, Visual Studio shows checked-out code with a check icon next to the file. Otherwise, a lock icon is shown. Checking out a file does not by default lock other team members from modifying the same file, but it can. Team Foundation Server Source Control can behave differently depending on your needs by using locks.

Viewing an Application’s History In Visual Studio, using either the Team Explorer or the Solution Explorer, it is possible to show the history of any file. Figure 7-8 shows the History result of right-clicking a file named ApplicationUser.cs from the Team Explorer.

Figure 7-8.  Visual Studio History of a file from TFS As you can see, all changesets are visible. A changeset is created every time you check in code to TFS. It contains a number that auto-increments. A description of what happened is given along with who checked the file in. Finally, the comment that was entered during check-in is shown. Including a comment with each commit is a good practice, and we can see why when we are searching in the history. The goal of the history is to show changes during the life cycle of a file, or a folder of files. It can be crucial when debugging to see what was there before and what has now changed that does not produce the desired effect. One amazing tool in Visual Studio is the Compare tool. It is tightly bound to History. If you select two different versions from the History panel and right-click, you can select Compare (Figure 7-9).

Figure 7-9.  The History window’s Compare tool This opens the Compare tool, which is divided into two panels. The left panel is the older file, and the right panel is the newer version of the file. Figure 7-10 shows what has been removed (1) between these two file versions. These lines are red for removed lines and green for added lines (2).

161


Chapter 7 ■ Teamwork with Visual Studio

Figure 7-10.  Visual Studio Compare tool On the right margin is a special scrollbar that shows with red and green highlights what happened inside these two files. This is a fast way to navigate big files.

Labeling a Check-In You have checked in your code with comments, you are using History, and you can search what happened during the life cycle of your files. At some point, the history will become huge, and finding a specific version will become a nightmare. A good example: if your software has a problem in a specific version, you might want to go back in time to create a patch. To find a specific version, TFS offers labeling. It adds a caption to a changeset. The easiest way to add a label to a changeset is to go to the Source Control Explorer and select a folder or file to apply the label. Right-click the file or folder and choose Advanced ➤ Apply Label. It is possible to add labels, modify them, or delete them at any time. To consult labels, select a branch or trunk and open the History. From there, select the tab called Labels. By default, it is the Changesets tab that is open.

Annotating Code You may want to contact the person who wrote a specific line of code in your project. In SubVersion source control or Git, this is called blame. With Visual Studio and TFS it is called Annotation and can be found in Team Explorer in the context menu or in the context menu displayed when you choose Source Control ➤ Advanced in the Solution Explorer. Annotation opens its own code editor window in read-only mode. It has a left margin with the most recent changeset that changed the line of code, the name of the developer who made the modification, and the date. See Figure 7-11. A link is available under the Changeset number. Clicking this link opens the Changeset detail view, where the comments can be shown with all other files that have changed during check-in.

162


Chapter 7 ■ Teamwork with Visual Studio

Figure 7-11.  Visual Studio Annotation window It is also possible to get additional information by moving your cursor over one entry. Right-clicking an annotation allows you to compare it with the previous version.

Shelving Your Code Shelving code is similar to checking it into TFS but without affecting any branches. This is useful if you want to have your code backed up into the source control without affecting other developers. For example, suppose it is Friday, you have worked the whole day, but your code does not compile. By shelving it, you can be sure that if something happens to your computer, the code will not be lost. Shelving is the right thing to do. To shelve your code, open the Team Explorer and open Pending Changes. At the right of the Check In button is the Shelve option. This is shown in Figure 7-12.

Figure 7-12.  The Shelve option in Pending Changes Naming the shelf is required, and it is important to provide a meaningful name because the shelf will be listed by this name. With this name, you will be able to return to the code or delete the shelf. To find existing shelves, go to File ➤ Source Control ➤ Find ➤ Find Shelvesets.

Code Review Visual Studio and TFS allow you to request a code review from a team member, which is beneficial before committing the code to the repository. The problem is that until you commit the code, no one will be able to see it. You would have to ask your teammate to come to your desk to do the code review on your machine. However, this won’t be possible if you are working remotely or if the reviewer can’t do the review at the time you are available.

163


Chapter 7 ■ Teamwork with Visual Studio

If you go to the Team Explorer of Visual Studio 2013, you will see an entry called My Work. The features of My Work are described in more detail in the next section, “Managing Your Work with Work Items.” Nonetheless, one of the important features in this panel is the Request Review. It is located under the In Progress Work. You can see it in Figure 7-13.

Figure 7-13.  Request Review in the Team Explorer Clicking Request Review opens a new panel for New Code Review (Figure 7-14). You can add one or more reviewers from the list of available users (1) for the TFS project.

Figure 7-14.  The New Code Review panel in Team Explorer

164


Chapter 7 ■ Teamwork with Visual Studio

At (2) is the subject for the code review. This is the name that will be listed in the Code Review panel. It is possible to specify an area of the path for code review (3). Finally, you can add an optional description (4). It is a good practice to fill out this text area. It gives the code reviewer more indication about what to review. Submitting a request initiates two actions. First, it sends to the reviewer a code review; second, it inserts the review into a workflow. The list of reviews that contains the review number and subject is under Team Explorer ➤ My Work ➤ Code Reviews (Figure 7-15).

Figure 7-15.  Code Reviews Request You can right-click the review request and click Open. This will give you two choices: accept the request or decline it. In the case where you are too busy, you can decline, and the requester can send its request to someone else. In Figure 7-16 you can see (1) that a reviewer can Complete or Abandon the review.

165


Chapter 7 ■ Teamwork with Visual Studio

Figure 7-16.  Code Review actions The link at (2) is a good place to communicate with the requester directly or comment to everybody. Finally, it is possible to see files that have changed (3). Double-clicking any file opens the file in a review code editor that is similar to Code Compare. It has one additional feature; it allows you to right-click any line to add comments. During that time, the requester may want to continue working on something else. This is why the requester can Suspend his or her works. Suspending work is available only in TFS 2012. The difference between shelving and suspending your work is that suspending creates a shelf for you and changes the work item associated with Suspend. When the work is resumed, it takes the code back from the shelf and changes the work item state to In Progress. Work items are discussed in the next section. Figure 7-17 shows the button to Suspend your work (1). At (2) is a description of the suspension; it could be “Waiting for review.” By default, the description is filled up with the number of files created and modified.

166


Chapter 7 ■ Teamwork with Visual Studio

Figure 7-17.  Team Explorer suspending work

Managing Your Work with Work Items Work items are available with Team Foundation Server to track the progress of development, and also to maintain an official list of what tasks must be done. Work Items have different types, and can be used to divide the work between team members and distribute them across sprints (if you are using a Scrum template).

Work Item Types To create a new work item, open the Team Explorer and select Work Items (Figure 7-18).

Figure 7-18.  Choosing the Work Items option in Team Explorer There are seven distinct types of work items (Figure 7-19). The first one is Bug. A Bug work item tracks code defects.

167


Chapter 7 ■ Teamwork with Visual Studio

Figure 7-19.  Creating a new work item Bug work items must have a title that is used as an identifier for most of the screen. Figure 7-20 shows the default template for a Scrum work item, for Bug. However, other work items are very similar. They all have the capability to assign someone to work on the item.

Figure 7-20.  Bug work items A State field is available; its value depends on the work item type. For bugs, the default state is New. Unlike other item types, Bug work items provide a place to include the steps to reproduce the bug. This feature allows you to use bullet points and include images with the bug. At the right, it is possible to define the acceptance criteria, what should be done to close the bug. The Bug work items allow links from the bug to a use case previously created. It is a good idea to associate bugs with requirements, because all requirements are attached to check-ins. This way, everything is associated, and it is easy to see the working path of a bug. Figure 7-21 shows the screen for a Task work item. As you can see, it is very similar to the Bug Work Items screen. However, it does not have anything related to a test case or the steps to reproduce an effect.

168


Chapter 7 ■ Teamwork with Visual Studio

Figure 7-21.  The Task work items window Task work items are a subset of Backlog work items, which are a subset of Feature work items. A feature is the highest level of abstraction you can have for the definition of a task. A task is a feature divided into smaller parts. For example, a feature could be “Managing user account.” Backlog items for this feature could be “Create a new account,” “Modify a new account,” “Have something to send forgotten password by email,” and so on. Tasks could be “Setup to user interface for creating a new account,” “Configure the database for users,” or similar. In short, features take time to produce. They are broken into a product backlog to fit into a timeframe of a single sprint. A task allows you to divide the work between team members. They are short tasks that can be done within a few hours. An Impediment work item prevents a task from being completed efficiently. This is not related directly to a coding problem, but is usually a teamwork issue, such as communication problems among the team, a network outage, or external services that cannot be reached. The last type of work item that can be created is the Test Case. This is where your tester can add all the steps that must be done for a manual test.

Querying Work Items The backlog is the container that has all the work items. It tends to become huge over time. This is why Visual Studio has a Query Editor that allows you to create your own query and save it for reuse. It is possible to share those created queries with your team, too. To use or create queries, open the Team Explorer and click Works Items. The last panel is named Queries. Figure 7-22 shows the context menu for My Queries. This is where you can start the Query Editor, by selecting New Query.

169


Chapter 7 ■ Teamwork with Visual Studio

Figure 7-22.  Choosing New Query in the Work Items window The Query Editor allows you to add lines in a grid for an AND or OR condition. Then you can add fields and the desired value. Figure 7-23 shows a query that returns only work items for the current project. It goes even further by only showing Task work items that are open to work. This is why the OR operator is between the In Progress and New. Finally, it filters down the list of the current sprint, which is the first one listed.

Figure 7-23.  Query Editor for work items

Multiple Workspace A workspace is the mapping between your TFS Source Control code and the local code you have on your computer. By default, when you get code from a repository, a workspace is created on your local machine. It is possible to see your current workspace by choosing Team Explorer ➤ Home ➤ Solutions ➤ Workspace. You can click the workspace name here and select Manage Workspaces. The other way to access this feature is to open the Source Control Explorer, display the Workspace dropdown, and select Workspaces. In both cases, the Manage Workspaces dialog opens as shown in Figure 7-24. From this window, you can add new workspaces or edit the current one. If you select the current one to edit, the Edit Workspace opens. Figure 7-24 shows two source controls for a single workspace; one is for BourseVirtuelle.com and the other one is for Gym. In both cases you can see where the code is locally situated.

170


Chapter 7 ■ Teamwork with Visual Studio

Figure 7-24.  Manage Workspaces and Edit Workspace

Visual Studio Integration with Different Development Processes We have seen with Work Items that Visual Studio and Team Foundation Server use some concepts that come from the agile development movement. To implement a particular development process or model, you select a corresponding process template in the Process Template Manager. The default is Microsoft Visual Studio Scrum 2013.2, but you can also choose MSF for Agile Software Development 2013.2 or MSF for Capacity Maturity Model Integration (CMMI) Process Improvement 2013. When you create a new team project, you select which of the processes you want to follow. In fact, changing the process changes the Workflow, Reports, Queries, and Work Item fields. Figure 7-25 shows some wording differences between processes.

Process

Scrum

Agile

CMMI

Product

Backlog Item

User Story

Requirement

Bug

Bug

Bug Triage Workbook

Bug Triage Workbook

Project Management

Impediment

Issue Issue Workbook

Issue Risk Review Issue Workbook

Figure 7-25.  Differences between processes

171


Chapter 7 ■ Teamwork with Visual Studio

It is possible to download additional process templates or modify a current process with the Process Template Manager. Within Visual Studio, open the Team Explorer, and go into Team Explorer ➤ Settings ➤ Team Project Collection Settings ➤ Process Template Manager. Figure 7-26 shows that TFS is configured to use by default the Microsoft Visual Studio Scrum 2013 template. It also shows that it is possible to upload a process template to TFS or to download a template to edit it locally (and then to upload it). For example, if you want to add new fields for the Scrum template, you can download the Scrum template from the Process Template Manager. Then, you can make your change and upload it to TFS.

Figure 7-26.  Process Template Manager

Life Cycle with Scrum With Scrum, you must create features and a product backlog. As mentioned previously, features are at a higher level and contain backlog items. Backlog items are then set to a sprint by the team. During the definition of backlog items, efforts are set to estimate the amount of work required. Business value is specified to be able to know which elements are more important compared to others. Then, every new sprint, you go through all of the backlog items to divide them into tasks. Bugs are also planned to be fixed. Once everything is planned and assigned, it is the responsibility of the developer to open the work item and change the status from New to In Process and then Done. This way, it is possible to track the progress of every sprint.

Life Cycle with Agile With Agile Processes, you have to create user stories. All user stories are associated with a rank that is used to know which user stories to develop first. Developers must estimate the effort and work for each user story. This ranking is done with Story Points. Other ratings can be provided, such as risk. By default, three values are possible: high, medium, and low risk. Description in all user stories defines what must be done, but does not go into detail of how to do it. Details are written inside tasks. Tasks are associated with user stories. For each iteration, user stories are selected. Tasks are defined by the team, and the development process can start. Developers can update the status and remaining time on the task during the development. Tasks include development duty, tests, and any work to accomplish the user stories.

172


Chapter 7 ■ Teamwork with Visual Studio

Life Cycle with CMMI Visual Studio and TFS offer a template to have the Capacity Maturity Model Integration (CMMI) life cycle directly integrated into Visual Studio. First, you create requirements. Requirements can be divided into tasks at any time. A requirement contains a title, and also a type. The available types are Functional, Business Objective, Feature, Interface, Operational, Quality of Service, Safety, Scenario, and Security. Priorities are set to every requirement with regard to the amount of work that must be done. They are all defined in a very abstract way, not according to time. However, tasks can be estimated in the Effort section of the work item.

Managing Your Project with the Web Visual Studio 2013 offers great tools for managing all work items, iterations, and progress within the same tool. However, a project manager or product owner may not want to have a Visual Studio license just to manage the project or to see the progress. This is why a web portal is available to manage work. The web address can be found directly in Visual Studio on the Team Explorer Home panel. Figure 7-27 shows where the Web Portal link is located in the Home panel.

Figure 7-27.  Web Portal website link This link opens a web portal with a dashboard that gives a nice overview of the situation for the current project. Figure 7-28 shows an example of the Overview screen. At (1) is the project name. If you are working on different projects, you will find it handy to be able to quickly see which project you are currently viewing with the dashboard. It is also the place to click to change the project. A project manager can switch between projects without having to ask the developer for the URL.

173


Chapter 7 â– Teamwork with Visual Studio

Figure 7-28.  Visual Studio Team Portal The main menu(2) contains the Home button, which displays the project dashboard. Code allows you to see the code online. The Work button is everything related with work items, sprints, and managing resources. The Build item is to see the build server. Finally, the Test link shows all test links. The How To section (3) can be hidden if you desire. There are four links to documentation to learn about how to use these features offered in the menu. When working with a Scrum template, the current sprint is displayed (4). It shows an overview of the health of the sprint with the remaining time and the backlog items for the sprint. Next to it, a burning chart is available (5). Pinned Items (6) is a custom section that allows you to show graphics and statistics depending on what you see in all other windows. For example, if you have a query that shows all bugs, you could have a graphic that shows the number of bugs across all sprints. Work items can be added directly from this page with the Work section (7). Team Foundation Server offers a way to communicate with your team with the Team rooms feature (8). This is a persistent chat room for your team. It is possible to create conversation categories, called rooms. By default, every project has one room. It is possible to see who is online in the room, and also who can join the room. Every day, a page is created for the room. It is possible to go through the past messages to read old conversations. It is also possible to tag other team members by using the @ symbol followed by their name. This way, they can be notified that they have something related to them. It is also possible to add to the team room by having the build server, code changes, work items update, or code review posted in the room. This can be a good idea if you are working remotely and want to open the team room in one of your screens and see what is going on. To create a link to a work item, you can use the # symbol followed by the item number. Finally, it is possible to use emoticons in the chat room.

174


Chapter 7 ■ Teamwork with Visual Studio

At (9) are Members of the project. Here it is possible to add and remove users. Finally, the project setting (10) is where you can set up a team, iterations, areas, security, alerts, version control, and services. Iteration configurations consist of setting up release dates and creating Sprint/Iteration names and date ranges. To add a new sprint or release, right-click and select New. Figure 7-29 shows the Create Iteration dialog that appears when a New iteration is selected. You can see that you have to choose an iteration name with a Start and End date.

Figure 7-29.  Creating a new iteration for a release with TFS Online Among the project settings (10) is a menu named Area. An area is a group of work items. This group can contain anything, including logical work items or functional categories. Areas can be used to categorize work items. For example, you can have one area for development, and one for configurations. Alternatively, you can have one area for a website, one for web services, one for Windows services, one for reports, and so on. Sub-areas are also available to define and segregate your area. Also on the project setting page are Securities to create Visual Studio Teams, Groups, and Users. It is also possible for you to change permissions for several actions. Alerts can be configured to send emails depending on specific triggers. An Alert Builder is available to create a clause defining a condition that must be true before an alert will be sent. Alerts can be modified and removed on this screen. Figure 7-30 shows an example of an alert that sends an email to me if the build fails for a specific project.

175


Chapter 7 ■ Teamwork with Visual Studio

Figure 7-30.  TFS Online Alert Builder The version control settings are the same as Visual Studio version control settings. They allow you to control which users and groups can do specific actions.

Build Server Visual Studio’s Team Explorer has a Builds button on its Home screen. When you first open it, the build server is empty, but you can create build definitions. TFS Build Server compiles code on a machine that is not the developer’s. It has the advantage of knowing if the source control has a missing file, or if something is wrong when compiling on a neutral environment. When setting up a build server, you need to choose a trigger from a manual build, or from a more continuous integration that compiles every time a check-in is done. Figure 7-31 shows the Trigger screen. Other configurations, like copying the compiled file to a shared drive, are available. These can be useful if you are using other software to publish code in a different environment. By compiling your code in a central place, your team is aware if someone on the team has introduced a bug that breaks the build. It also displays a notice on the screen (and can be configured to send email) if unit tests fail. Of course, this requires you to have unit tests as part of the solution compiled by the build server.

176


Chapter 7 ■ Teamwork with Visual Studio

Figure 7-31.  Build Server Trigger After you’ve committed a build, the Builds screen shows the status of the build, all unit tests, and additional configurations like executing the Architectural Layer validation. Figure 7-32 shows a result report from Visual Studio after committing. In this example, the build has compiled everything with success. Nevertheless, it has three compilation warnings and four unit tests that did not pass. From there, developers can check in code and the build server will run again. This process is executed until everything is working again correctly.

177


Chapter 7 â– Teamwork with Visual Studio

Figure 7-32.  Result of a build server compilation

Summary In this chapter, you have learned how to use Team Foundation Source Control. Branches, merges, conflicts, and many other basic source control features were explained to show how Visual Studio can interact with TFS to execute them. Visual Studio has a powerful code review tool that can be used with TFS to communicate without having to be with the user who created the code. It removes the need for all email and direct communication. Then you saw what a work item is and how it is at the center of all the life cycles that Visual Studio can manage. We have briefly seen three life cycles that Visual Studio and TFS support. Finally, the web portal was introduced. This website comes with Team Foundation Server and allows you to do a lot of tasks that Visual Studio can do. The main advantage is that it does not require you to have Visual Studio installed, and can be used with any type of device. This is also true for the build server, which is fully integrated and removes the need to configure your own server for this specific task.

178


Chapter 8

Framework-Specific Features Some Visual Studio features are unique to the framework you are working with. This is the case for every project. In this chapter I have selected some popular frameworks to introduce unique features for each of them. The goal of this chapter is to give you an overview of what Visual Studio can do for each of these frameworks. You will see the Web framework, the SharePoint framework, the WinForm framework, the WPF framework, the Windows 8 framework, WCF, the Workflow Foundation framework, and a brief overview of LightSwitch and TypeScript.

Web Frameworks Visual Studio works with the web using two distinct methodologies. One is older and is named Web Forms, and the other one is newer and regroups MVC, the Web API, or SignalR. Both are different and come from a different epoch. Visual Studio offers different capabilities to work with them. Although MVC, Web API, and SignalR are different technologies, they share a lot of common aspects that Visual Studio handles in the same way. The ASP.NET Web Form framework has an editor that allows you to create web pages with drag and drop. This is a convenient tool for people who do not know how to write HTML code perfectly. It fills the gap between Windows Form applications and the Internet. The ASP.NET project type is available when creating a new project. It is found under Visual C# or Visual Basic, both of which have an ASP.NET Web Application template. Figure 8-1 shows the New ASP.NET Project window, where you choose between an ASP.NET Web Form, an ASP.NET MVC, and a Web API template. This section is more about Web Forms, since that project type has more Visual Studio capabilities. SignalR is a messaging protocol that sits alongside the ASP.NET stack and can be added to any of these project types. Visual Studio does not offer additional tools that need to be described.

Figure 8-1.  ASP.NET Web Form or ASP.NET MVC

179


Chapter 8 ■ Framework-Specific Features

The designer is available when you right-click any .aspx file and choose View Designer. Otherwise, when you double-click the file, the source code editor will open. However, from the source code editor, it is possible to switch to the designer easily using the bottom toolbar shown in Figure 8-2 at (2). The Design button switches to the designer mode, the Split button splits the screen in two for the code and for the designer, and the Source button shows only the source. Label (1) is the context menu available on the .aspx file. In the list of possible views are the options View Code and View Markup. View Markup opens the source editor with all the HTML markup. View Code shows the ASP.NET code behind, which is the C# code that is executed on the server side. At (3) you can see that the designer opens the .aspx page in its context. This means that the master page is displayed, but is not editable, and that the page inside this one is editable.

Figure 8-2.  ASP.NET web form designer One of the strongest features of ASP.NET Web Forms is the ability to use toolbox items. The toolbox is available in View ➤ Toolbox. A small subset of the tools is shown in Figure 8-3. The main advantage of the toolbox is that tools can be reused from one page to another. You just need to click the desired item and drag it into the designer. The position where you drop the tool is the position it will have in the web page.

180


Chapter 8 ■ Framework-Specific Features

Figure 8-3.  Toolbox for ASP.NET Web Forms If a tool has more options available, an arrow called a Smart Tag appears next to the tool and allows you to set additional information. The Properties window also contains properties that you can configure. Figure 8-4 shows Visual Studio in Split view.

Figure 8-4.  ASP.NET Web Form Split panel and the Properties window At the left is the code generated from the designer after an image was dropped into the About page. We have increased the size of the image, which results in the code changes at the left and also changes in the Properties window at the right. Changing any values on any one of these three screens updates all values.

181


Chapter 8 ■ Framework-Specific Features

The SharePoint Framework SharePoint is a web application that has existed since 2001. It is more than just a document-management tool. It is also a content manager and a platform to develop intranet websites. It has many capabilities, including by default a collaborative website. The site developer can collect pages and templates to configure the website with blogs, collaborative tools for your team, document browsing with all check-in/check-out features, meeting features, and more. SharePoint integrates with Active Directory in a very easy way that makes it an excellent choice for an intranet. From a development perspective, SharePoint has a persistent mechanism called lists and libraries. Every list is a collection of metadata that you create as if you were creating a database table. It also has the notion of Web Parts. This reusable component can be integrated into pages. Since 2007, Web Parts in SharePoint have been based on ASP.NET Web Parts. SharePoint 2013 adds the XML Localization Interchange File Format (XLIFF). SharePoint uses XLIFF to localize contents. Another new feature is the support of AppFabric, a Microsoft technology to create scalable software that runs with IIS (Internet Information Services). SharePoint 2013 has a new development tool that supports ASP.NET MVC. This allows you to use something other than just ASP.NET Web Forms and still have the ability to work in Visual Studio. When creating a new app, Visual Studio pops up a New App for SharePoint dialog window that lets you choose the project type, as shown in Figure 8-5.

Figure 8-5.  SharePoint ASP.NET Web options SharePoint development requires that not only Visual Studio but also SharePoint Foundation 2013 or SharePoint Server 2013 be installed on the development system.

The Windows Forms (WinForms) Framework Visual Studio has offered the ability to develop Windows applications with the Windows Forms (WinForms) framework since its beginning. You can create a new project with WinForms using templates for the two-supported languages, Visual Basic and C#.

182


Chapter 8 ■ Framework-Specific Features

Changing WinForms Properties The Windows Forms framework’s principal panels are the Designer, the Properties panel, and the Toolbox panel. Figure 8-6 shows those three panels open. At (1) is the Toolbox. It contains all the Windows Form controls that Visual Studio offers with the WinForms framework. It is possible to drag and drop these controls into the Designer. The Designer automatically opens when you double-click the form item in the Solution Explorer. You can also right-click the form item and select View Designer. The Designer allows you to move every control in the form to create your Windows Application the way you want it. To set custom properties or behaviors, you can use the Properties panel. This panel can be opened by pressing the F4 shortcut if you are in the Designer, or you can open it with View ➤ Properties Window.

Figure 8-6.  WinForms principal panels The Solution Explorer contains all the forms in your project. Each form can be expanded to three files. The first file is the Designer file. This is where all information about the graphic interface is translated. You should not modify this file, because the Windows Forms Designer generated this code. Modifying this file can result in some loss of information if something changed in the Designer. The second file is the resource file, which lets you set captions, labels, and text in multiple languages. The third file is the code behind a WinForm and is where you can set your custom event codes or action codes. Figure 8-7 shows a new WinForms project with a single form named Form1 that contains the three files that we just discussed.

Figure 8-7.  Behind a WinForms project

183


Chapter 8 ■ Framework-Specific Features

Laying Out a WinForm with Visual Studio The WinForms framework has components and containers in its toolbar. A container allows you to lay out your form in a structured way. Figure 8-8 displays the Containers category of the Toolbox. It has seven different ways to lay out components.

Figure 8-8.  Toolbar containers Using containers with the two properties called Dock and Anchor is the way to set up your layout. Containers allow an official structure with a specific appearance, while Dock and Anchor control positioning. The Dock property is similar to adding magnets to your component. It is possible to choose which sides are magnetized. Once set, this property will allow you to change the form size, and the control of width and height will follow. The Anchor property has the same type of configuration; you choose which edge of the selected control is affected, but this property affects which edge of the container the control is bound to. Figure 8-9 shows the layout in the Properties panel. The Dock is open, allowing you to choose multiple edges with a graphical edge chooser.

Figure 8-9.  Visual Studio Dock and Anchor options for Layout

184


Chapter 8 ■ Framework-Specific Features

Accessing Component Events with WinForms Every component has a set of events that you can customize for your application. For example, a button can be pushed, and you can write code to define what that event will trigger. It is possible to access the code for any event from several places in Visual Studio. The first way to access component events is the simplest. Double-clicking a control opens its associated source code. If there is no associated code yet, the default event code is generated. In the case of a button, the click event is generated in the form’s class. To access other events, Visual Studio has an Events panel within the Properties panel. This is the second way to access events, by using the lightning icon (1), as shown in Figure 8-10. Label (2) indicates where to set the name of the desired event.

Figure 8-10.  Visual Studio Events Properties panel Once the name is set for the desired events, press Enter and events in the code are generated with all the correct parameters. Figure 8-11 shows the generated code for the Click event. The sender and event arguments are automatically generated.

185


Chapter 8 ■ Framework-Specific Features

Figure 8-11.  Generated code from the Properties panel The last way to create an event is to write the code. You can at any time use the name of the component and select an event. IntelliSense will provide you with the list of possible events, using a lightning symbol in front of the method name to specify an event.

The WPF Framework Windows Presentation Framework (WPF) is the newer presentation framework for a fat client, used since 2008. It came after WinForms and created a richer interface. WPF does not work with forms, but with WPF pages, controls, documents, and windows. All of these elements are available in the Add New Item wizard, as shown in Figure 8-12.

Figure 8-12.  Add New WPF Item WPF reuses the concept of controls from WinForms. It is possible to drag and drop from a list of controls directly into canvas controls. The toolbox is still used. It is accessible by using the F4 shortcut or by choosing View ➤ Toolbox. Figure 8-13 shows at the left the WPF toolbox controls (1). These elements can be dragged into the designer (2).

186


Chapter 8 ■ Framework-Specific Features

Figure 8-13.  Visual Studio WPF Designer When something changes in the designer, it is automatically changed in the XAML source code (3) and vice versa. The synchronization between the two panels is automatic when a save is applied.

The Visual Designer Visual Studio has a very strong WPF designer. Figure 8-14 shows some of its features. Label (1) indicates a toolbar at the bottom. This toolbar has a zoom dropdown that affects only the creation; it does not affect the rendering of the final executable. The FX button enables effects rendering; it shows or hides effects. The goal is to see how components render with or without effects quickly. Disabling an effect increases the performance of Visual Studio. Next to the FX button is a button with six little squares that activates a grid to help position controls. Next to this button is a button that allows you to snap the design to the grid. This helps designing with controls aligned correctly. The last option is the snap-to guideline. Label (4) in Figure 8-14 shows the guideline option activated. The red dashed line appears when you move a component, and has a snapping effect when borders are aligned.

187


Chapter 8 ■ Framework-Specific Features

Figure 8-14.  WPF visual designer Label (2) in Figure 8-14 shows three buttons that transform the WPF designer into different views. The top button splits the screen vertically, so that the left panel is the visual, and the right panel becomes the source code. The middle button splits the screen horizontally: at the top is the designer and at the bottom is the code. The bottom << button opens the designer at its maximum, giving the WPF designer a bigger viewport. Label (3) points to three buttons. The top one and the middle one show the designer and the code behind the designer. The bottom button toggles between the code and the designer when each occupies the full screen. Otherwise, if the screen is divided in two, as we see with label (2), this bottom button does nothing. However, new buttons will appear, letting you switch between left-right and bottom-top. The third button in this group opens the document outline, which contains all controls used in the canvas. Every control, when selected, has a little square that appears at each corner (5) and each edge that lets you resize the shape of the control. Label (6) shows that Visual Studio provides guidance for margin dimensions. Every time a control is selected and moved, the size changes.

The WPF Properties Window Figure 8-15 shows the Properties window of a textbox in WPF. The WPF Properties window is more enhanced than its equivalent in Windows Forms.

188


Chapter 8 ■ Framework-Specific Features

Figure 8-15.  WPF Properties window At the top is the name of the control. This is the name that you will be able to reference in your code. Next to the name is a wrench icon, which shows all properties. Clicking the lightning icon next to the wrench shows all events. As you can see, every property provides developers with precise control. The user experience of modifying controls is easy with the use of icons. Dark squares at the right of every property allow for binding, allowing you to let a value change automatically depending on another value.

Windows Store Applications Visual Studio can create a Windows Store application. In Visual Studio you can do coding, debugging, localization, packaging, and deployment. To create Windows Store apps, you will also need Windows 8.1. Another requirement for developing Windows Store applications is a developer license. If you don’t already have one, a prompt for requesting a developer license appears on the first run of Visual Studio or Microsoft Blend (discussed in the next section), as shown in Figure 8-16.

189


Chapter 8 ■ Framework-Specific Features

Figure 8-16.  Windows 8.1 Developer license To create a new Windows Store app, go to File ➤ New Project and click the language you prefer (C# or VB). Under the language, you will find that Windows Store. Blank App, Grid App, Hub App, and Split App are the four most used templates. They are shared across VB and C#. The goal of having these templates is to speed up development. Figure 8-17 shows the list of new templates for C#.

Figure 8-17.  Creating a new Windows Store application

190


Chapter 8 ■ Framework-Specific Features

After you select the desired template, Visual Studio creates default folders and file structures. Then you can use Visual Studio’s visual designer to create your UI. It is also possible to edit the UI by code or by using a tool named Blend. To open your project in Microsoft Blend, right-click the project and select Open in Blend.

What Is Microsoft Blend? Figure 8-18 shows the result of opening a Windows 8 App in Microsoft Blend from Visual Studio. As you can see, it is a very similar tool to Visual Studio, but the experience is richer. The left side shows the Solution Explorer at the top and at the bottom the objects that it uses. In the middle is the visual designer. On the right is the Properties panel.

Figure 8-18.  Microsoft Blend with a Visual Studio Win8 App open Microsoft Blend has an advantage over Visual Studio in animation, where it simplifies creation. It is also more design-oriented and less code-oriented. This tool is for any XAML-based software like Silverlight, WPF, or Win 8 applications.

Using JavaScript to Create Win 8 Apps Windows 8 applications can be created in C#, VB, or JavaScript. A template category exists for JavaScript, with a subcategory named Windows Store. Five templates are available; the most commonly used ones are Blank, Grid, and Split Application. Figure 8-19 shows the structure of a JavaScript project.

191


Chapter 8 ■ Framework-Specific Features

Figure 8-19.  Windows 8 JavaScript file structure As you can see, Visual Studio creates a CSS folder for the whole application style sheet. It does the same for images and JavaScript. Visual Studio also specifies a folder in which every page has a subfolder with a unique CSS, HTML, and JavaScript file. The manifest file, named package.appxmanifest, contains the name of the application. It also has the description, title, start page, splash screen, and other meta-information. Visual Studio allows you to start the application for debugging, just like any other application. Once you are finished developing, you just have to press F5 to launch the Debugger, build, deploy, and start your application.

Visual Studio WCF Tools Visual Studio is the perfect tool for developing with Windows Communication Framework (WCF) because it has a project template to help you create the WCF service. WCF allows you to create several type of service bindings with strict contracts. Visual Studio also has a tool to test services, and a tool to modify the configuration. You can also easily integrate VS into a solution as a consumer of a WCF service. It is possible to create WCF services with the VB language or C#. The WCF option is located under the language template, as shown in Figure 8-20.

192


Chapter 8 ■ Framework-Specific Features

Figure 8-20.  Visual Studio WCF Templates for Visual C# The difference between the four templates available for WCF is minimal. The WCF Service Library contains the minimum classes to create a service. The output of this template is a single DLL file. Choosing WCF Service Application lets you create a WCF application that can be hosted on IIS or WAS (Windows Process Activation Service). A WCF Workflow Service Application can be hosted on IIS and WAS but is managed with Microsoft AppFabric. Finally, the Syndication Service Library template fulfills the need to create an Atom or RSS service.

Configuring the WCF Service The WCF configuration files are quite complex. Many configurations are available, and Visual Studio has a tool to simplify this configuration process. To open this tool, right-click the configuration file, named web.config, and select Edit WCF Configuration. Figure 8-21 shows the context menu to open the configuration.

Figure 8-21.  WCF configuration tool One of the first things to do is to create a binding endpoint, and the WCF Configuration tool has a complete list of all possible bindings. Click the Bindings folder to create bindings (Figure 8-22). From here, the Create a New Binding dialog appears at the right and lets you select the binding type.

193


Chapter 8 ■ Framework-Specific Features

Figure 8-22.  WCF Configuration tool and creation of bindings Depending on the binding, configurations will change. Figure 8-23 shows the Binding tab containing the configuration for the basic HTTP binding. This is where you can configure the name of the binding and all configurations for size, time out, quotas, and encodings.

Figure 8-23.  WCF binding configurations

Testing a WCF Service If you have created a WCF service from the Application template, it is possible to execute it directly from Visual Studio. Set your startup project to your new WCF project (right-click and select Set As Startup Project) and press F5. It is also possible to start the WCF Test Client by opening the Developer console and typing wcftestclient.exe. Finally, you can directly open the Test Client by going into the installation path of Visual Studio ➤ Common7 ➤ IDE ➤ WcfTestClient.exe. Figure 8-24 is an example of a simple WCF Test Client that uses an integer as an input and as output displays a sentence in a string that uses the integer.

194


Chapter 8 ■ Framework-Specific Features

Figure 8-24.  WCF Test Client example Label (1) shows the first step, when the WCF Test Client appears. If the service URI is correct with a valid WSDL file, then all methods of the service appear. Double-clicking a method (2) opens the panel on the right side, which has at its top all input values, and at the bottom, the result (3).

Consuming a WCF Service Visual Studio has a wizard that simplifies the use of services. Right-click any of your project references that want to consume a service and choose Add Service Reference. This opens the Add Service Reference dialog, where it is possible to paste a service address. The next step is to click Go and see the services and operations available. Label (1) in Figure 8-25 shows where the address must be set. The Go button fills the Services and Operations list. The Discover button searches WCF projects in the current solution. Also important in this screen is the Advanced button (2). This opens another window that lets you change the access level, asynchronous operations, message contracts, collection type and dictionary collection type, and other options. Often, we change the collection type option, which is by default System.Array. You can change it to a generic List. When you are finished, click OK in the Add Service Reference window; the result is the creation of a service reference and proxy objects. Those objects come from the Data Contract defined by the publisher. You can instantiate them and use the service class generated by the service reference to communicate with the host that handles the service.

195


Chapter 8 ■ Framework-Specific Features

Figure 8-25.  The Add Service Reference dialog

The Workflow Foundation Framework Workflow Foundation (WF) is a Microsoft framework used for event-driven development. A workflow is a set of steps that are associated with each other. Available with C# and VB, Workflow Foundation has its own category under both. Four templates are available, from a simple Workflow Console Application to a WCF Workflow Service project that can be hosted on IIS and managed by Microsoft AppFabric. Two others templates are available, for creating an activity designer and an activity library. Workflows are a huge concept, and this section focuses on the Visual Studio editor for sequential and state machines.

Building a Flowchart Workflow The Flowchart is a primitive workflow diagram that works with logical steps. Each step has conditions to indicate whether it must go in one direction or another. Arrows in the diagram show the direction of the information flow. Figure 8-26 shows a workflow in Visual Studio 2013. At the left is the Toolbox, which contains several categories of items. One of them is specialized for a Flowchart (1). Every item in the Toolbox can be dragged into the designer (2). As you can see, a Flowchart surrounds all other activities. Everything starts with the Start activity and goes from one activity to another.

196


Chapter 8 ■ Framework-Specific Features

Figure 8-26.  Flowchart workflow in Visual Studio and WF In the example in Figure 8-26, arguments and variables are defined at the bottom of the designer (3). This allows you to write and pass information from your application to the workflow. In this example, we assign the Target variable a random value and we prompt the user to enter a value. This value is assigned by Workflow Foundation to a variable and increments the variable Turns. Then we test whether the max number of Turns has been reached. If not, we check to see if the number guessed is the correct one.

197


Chapter 8 ■ Framework-Specific Features

Building a Sequential Workflow A Sequential workflow is a series of steps linked to one another. The steps are very closely timed and are usually built for tasks that do not involve human interactions. To create a Sequential workflow, double-click the activity in the Solution Explorer. An activity has the extension .xaml. Double-clicking the file opens the designer. From here, the Toolbox must be open to be able to create the workflow. The Sequential components are under Control Flow. Figure 8-27 illustrates some controls that can be dragged and dropped into the activity canvas. Sequence is the control most used in the Sequential workflow.

Figure 8-27.  ToolBox for workflow and sequential activity The simple workflow we created in “Building a Flowchart Workflow” can be made into a Sequential workflow. This time, it is a sequence, which means that everything goes from top to bottom. It is still possible to loop. Figure 8-28 shows the same workflow, but in Sequence. This time, it starts with a Sequence activity. This type of activity can be embedded; for example the first sequence assigns a variable and then works while prompting and assigning. This type of diagram can work like a Flowchart. They can even be used inside of each other. For example, a Flowchart can contain a Sequential workflow as an activity. Nevertheless, Sequential workflows are preferred instead of a Flowchart for a more linear workflow.

198


Chapter 8 ■ Framework-Specific Features

Figure 8-28.  A Sequential workflow in Visual Studio

199


Chapter 8 ■ Framework-Specific Features

Building a State Machine Workflow A State Machine workflow works with states and transitions. This type of workflow is more event-driven than either the Flowchart or the Sequential workflow. Figure 8-29 shows that it is smaller than the two previous ones. However, all states can be double-clicked to be expanded.

Figure 8-29.  A State Machine in Visual Studio WF Every state has an Entry and Exit position. It does not mean that you have to specify both of them. Figure 8-29 shows the Initialize Target with a single icon that has an arrow that goes into the cycle; it means that it has only an entry position. Other states, like Enter Guess, have both. Figure 8-30 is a representation of a state. The Entry position consists of an activity that displays text at the top. It also has an Exit position at the bottom, which assigns a variable. Under the state are the transitions. You can click any source or destination to move between states. These are defined at the State Machine workflow level with arrows. Note that there is no transition arrow in the Toolbox; Visual Studio hides arrows on every state. To add an arrow, instead go to the desired source state. A small square will appear on the border of the state at the closest position of your mouse. Click the square and go to another state. This will generate the association. It is possible to have a circular reference if the source and destination have the same state.

200


Chapter 8 ■ Framework-Specific Features

Figure 8-30.  Inner state of a State Machine workflow

Visual Studio LightSwitch Visual Studio LightSwitch is designed to simplify and shorten development time. It creates websites that can run with all browsers, even mobile browsers. It has connectors to data sources like OData as well as more traditional data sources like SQL databases. LightSwitch supports the Visual Basic and C# languages. This is why you can find four LightSwitch templates, two in each language (Figure 8-31). One is for Desktop applications, and the other is for HTML applications. The Desktop application is based on Silverlight, and the HTML application is based on HTML5 with jQuery.

Figure 8-31.  Visual Studio 2013 LightSwitch templates

201


Chapter 8 ■ Framework-Specific Features

After you select the language and the desired template, Visual Studio creates all the default files. Figure 8-32 shows the startup page, which asks (1) if we want to start by creating a new table or attaching to an external data source. In the Solution Explorer, three projects should have been created. The first (2) is empty with the name of the project you have specified. Another is a JavaScript project that contains all the client-side files (3). Finally, the last project (4) is a web project with all the server-side files.

Figure 8-32.  Visual Studio LightSwitch file structures

LightSwitch follows the Create-Read-Update-Delete (CRUD) model. This is the reason why it asks to create a new table first, and then will generate a screen to display the data, to create and update data, and finally to delete actions. To create a new table, open the Data Designer, as shown in Figure 8-33. Here (2) you can describe your entity in a three-column grid. One column is for the name of the field, the second column is the type, and the last specifies whether it is required or not. You may also notice the first row, named Id. This is added by default and is used as a primary key. You cannot rename it or delete it.

202


Chapter 8 ■ Framework-Specific Features

Figure 8-33.  LightSwitch Data Designer Figure 8-33 shows (1) a command bar. The Relationship button allows you to define associations between tables. This is like creating a foreign key in SQL. The Computed Property button adds a field that is not persisted but computed when read. Using the Query button it is possible to create a query that sorts or filters tables, and even creates new tables. The New Table button creates a new table, and every table created is inside the LightSwitch server project under the Data Sources folder. This example has a collection of data in a table named ApressTable that resides inside an internal database named ApplicationData, which is the default repository name that LightSwitch uses. It can be found in the bin\data folder of your application. Figure 8-33 also shows the Properties panel (4). This allows you to do some additional configuration for the table, such as enabling the creation and modification of the properties. This feature enables LightSwitch to keep track of any modifications to the data. This adds some fields about auditing in the background. The date of the creation and modification are added, along with the name of the person who did the modification. You will not see these fields in the Data Designer, only onscreen. It is possible to change the table name and add visual settings. If a field is selected from the table, the Properties panel changes to display the field properties instead. For example, you can create a unique index for a string field but also specify the maximum length if the field is required. It is also possible to add custom validation; this opens the code editor, where it is possible to specify C# or VB code with advanced validation. Finally, the Data Designer has two perspectives; one is the server, and the other is the HTML client. Going into the HTML client, it is possible to add screens using the LightSwitch screen editor. Figure 8-34 shows the creation of a new screen. The left part (1) is a list of screens. In the middle (2) is a visual hint of how the screen will look once generated. The last step (3) is the data binding where the table is chosen.

203


Chapter 8 ■ Framework-Specific Features

Figure 8-34.  LightSwitch screen editor Visual Studio has an .lsml file under the Screens folder of the LightSwitch client project. It contains all fields, even those for the audit. Figure 8-35 shows what Visual Studio displays after a new screen is created. The Command Bar Add option adds commands to the bar; for example, in the screenshot we are creating a button for adding or editing a new entity.

Figure 8-35.  LightSwitch client-side screen configuration

204


Chapter 8 ■ Framework-Specific Features

Visual Studio TypeScript TypeScript is a language for web application that uses JavaScript. In fact, TypeScript can be compiled into JavaScript. This means the code is usable on any web browser that can execute JavaScript. Code can use either the TypeScript syntax or JavaScript syntax. TypeScript can make many Visual Studio tools available, including the refactoring tools, syntax highlighting, and jumping to a reference or declaration. TypeScript can be installed on any Visual Studio edition since 2012. It requires you to have .NET Framework 4 or later. Then, TypeScript must be downloaded from Microsoft if you are using Visual Studio 2013 SP1 or earlier. Beginning Visual Studio 2013 SP2, TypeScript is a part of Visual Studio. If you have an earlier Visual Studio version than this version, Visual Studio will open a web page with a link to Microsoft, where you can download TypeScript, if it does not find TypeScript installed. Once you have TypeScript installed in Visual Studio, you will see a new category called TypeScript under New Project, where it is possible to create an HTML Application With TypeScript. This is not the only place where TypeScript can be added. In fact, you can add a TypeScript file to the context menu of any Web project. Right-click anywhere in the project and choose Add ➤ TypeScript File. If the project is not a TypeScript project, Visual Studio will prompt you to configure your project to be compatible with TypeScript. Figure 8-36 shows this message. You have to accept it only if you want to use NuGet manager for TypeScript. Otherwise, the project already has been configured to support TypeScript.

Figure 8-36.  Visual Studio TypeScript project Visual Studio has the ability to use breakpoints to improve the debugging experience with TypeScript. You can use features like debugging, examining values of an object, using the watches, viewing the call stack, and so on. It is also possible to debug the JavaScript generated. TypeScript configuration generates the JavaScript file when you save. You can find the build settings in the Properties panel of the project under the TypeScript Build tab, which also has some compilation options. You can choose the ECMAScript version, the module system, and what to generate for output and debugging features. TypeScript can use JavaScript, but to have all the IntelliSense power, it requires a declaration file (d.ts). Visual Studio makes it easy to get these declaration files; you simply right-click any JavaScript file and choose Search for TypeScript Typings. This opens NuGet to find the package with the definition file to be installed into your project. If you do not see the JavaScript file generated when saving your TypeScript file, click Show All Files in the Solution Explorer. You will see two generated files: one .js and one .js.map. The JavaScript file is the TypeScript translated into the JavaScript language. The mapping file is for Visual Studio to know how to map between JavaScript and TypeScript. It is used when debugging to be able to put breakpoints into the TypeScript file even if the JavaScript file is executed.

205


Chapter 8 ■ Framework-Specific Features

If you want to have a better experience with TypeScript, you can download the Web Essentials extension, which will enable you to split the screen in two—one side with TypeScript, and the other one with JavaScript. However, this Visual Studio Extension does not work with the Express edition.

■■Note  You can download Web Essentials 2013 at http://vswebessentials.com/.

Summary In this chapter, we have seen Visual Studio from the perspective of different frameworks and languages. We have gone through Web framework and SharePoint to fat-client technologies with the WinForms and WPF frameworks. We have briefly seen that Visual Studio is perfect to create Windows 8 applications, WCFs, and Workflow Foundation projects. Finally, we have seen LightSwitch create rapid applications and TypeScript, a richer client-side language.

206


Chapter 9

Extending Visual Studio This last chapter covers advanced topics that you may not use at first. However, as you work with Visual Studio, you will stumble into some situations where it does not do exactly what you want. Fortunately, Microsoft and Visual Studio do a great job of allowing you to customize their tools. This chapter starts with the heart of extending, which is the Visual Studio Software Development Kit (SDK). Then you will learn about T4 templates, which can generate files, text strings, and program logic, and have existed for several editions. You’ll also learn about code snippets, HTML smart tags, browser links, and the new SideWaffle tool for extending Visual Studio 2013. Finally, you’ll see how to protect your code by obfuscating it.

Downloading and Exploring the Software Development Kit (SDK) The SDK is at the core of development in Visual Studio. Advanced developers need to know what they can extend in Visual Studio with the SDK. This chapter introduces basic concepts of extending Visual Studio. Before going any further, you must download the SDK, which does not come with Visual Studio by default. However, it has been available since Visual Studio 2005, and you can download it for free from Microsoft Developer Network (MSDN). The download is less than 15 MB and includes project templates, tools, tests, and reference assemblies required to build extensions. To download the SDK, search on Google or Bing for “Download Visual Studio 2013 SDK.” You will land on a Microsoft website where it is possible to download the SDK. A minimum system requirement to use the SDK is Windows 7 with the latest service pack, or Windows 8/8.1. The downloaded file should be named vcsdk_full.exe. Be sure to close Visual Studio before installing the SDK and to have at least 112 MB of available hard drive space. The installation should take less than 5 minutes.

What You Can Do with the SDK The Visual Studio SDK allows you to extend Visual Studio by adding commands, windows, and other IDE components. It can extend the editor for every supported language, but it also allows you to create your own language. You can extend the data designer, create your own project templates, or create integrated custom source control plug-ins. The customization does not stop there, because you can customize the debugger, or even replace the default one, with a custom version. The SDK provides several strategies to extend Visual Studio. You can create Visual Studio add-ins, wizards, or custom commands. Using the Visual Studio package is the perfect strategy for creating a large component. However, if you create an application that relies on Visual Studio, you should create a Visual Studio isolated shell application. These two kinds of extensions are based on VSPackages. It is also possible to use the Managed Extensibility Framework (MEF) to customize or extend Visual Studio. This is simpler because Visual Studio uses an open contract with MEF to extend the functionality of Visual Studio. This removes the need to use VSPackages. Figure 9-1 shows a new template category named Extensibility added by the SDK. Two templates, Visual Studio Package and VSIX Project, are discussed in the following subsections.

207


Chapter 9 ■ Extending Visual Studio

Figure 9-1.  Visual Studio SDK adds an Extensibility template category

Installing VSPackages with Visual Studio VSPackages consist of software modules that Visual Studio loads. They provide graphical elements, services, projects, editors, and designers. Visual Studio is extended with the addition of VSPackages. You can create your own package, and it will be loaded with the default Visual Studio ones. VSPackages are not only a functionality but also a way to publish your extensions. Every VSPackage must implement the IVsPackage interface. This interface has a SetSite method that allows Visual Studio to inject itself into the VSPackage. The VSPackage can then manipulate Visual Studio. The SDK installation provides a series of Visual Studio interop assemblies to access COM interfaces. One can be found at <Visual Studio SDK Installation Path>\VisualStudioIntegration\Common\Assemblies.

VSIX Project Templates VSIX Project templates can be used to create extensions for Visual Studio. They support deployment of VSPackages. A new VSIX Project template consists of C#/VB.NET classes, icons, and a manifest file that has information about the extension. It can be easily installed and is a simple way to install many other extensions. This section shows you how to use VSIX to create an extension for a simple C# project custom template. The first step is to create a new project of type C# Project Template with all default files in File ➤ New Project ➤ C# Project Template. For example, a ProjectTemplate.csproj file is created with default project options. Information about icon, order, required framework, and project type (C#, VB, and so on) can be edited. By default, creating a new C# Project Template also creates a new class, configured to use specific libraries, depending on the framework. Figure 9-2 is an example of a class configuration that will be transformed when used in Visual Studio once the VSIX package is installed.

208


Chapter 9 ■ Extending Visual Studio

Figure 9-2.  C# Project Template example The second step is to create a new VSIX Project. This option is also found in the Extension category installed with the SDK, as shown in Figure 9-2. It creates a simple project with a single file that is the manifest. Visual Studio has a special editor for the vsixmanifest file. Double-clicking the manifest file opens a metadata editor. You can then create your VSIX code. Once you’ve done that, you need to use the previous C# Project Template in your VSIX project. Open the project template and go to File ➤ Export Template Wizard. This opens a wizard that lets you choose which extension project you want to export and lets you define some options as shown in Figure 9-3.

209


Chapter 9 ■ Extending Visual Studio

Figure 9-3.  Exporting an extension from Visual Studio You can add the created zip file to your VSIX project and set the property of the zip file so that it’s always copied when compiled. In the output directory, you should see the zip file that contains the C# Project Template we want to install into any Visual Studio, along with a manifest file that has the information about the extension we just created, and the VSIX file that can be executed. Figure 9-4 shows the output generated with the compilation of the VSIX project that contains the compressed file of the extension project.

Figure 9-4.  VSIX compiled files Executing the VSIX file starts the VSIX installer and prompts you for authorization. If you restart Visual Studio, you will see the new C# Project Template, called ApressVSIXProject, as illustrated in Figure 9-5.

210


Chapter 9 ■ Extending Visual Studio

Figure 9-5.  Visual Studio C# Project Template installed

Uninstalling an Extension You may want to remove one or many extensions installed in Visual Studio. This can be done by going into Tools ➤ Extensions and Updates. You can search for installed extensions or browse them by categories. From here, select the extension to uninstall and click Uninstall in the side bar.

Visual Studio Shell Extensions Visual Studio Shell Extensions will not be covered here because they are only useful for external tools that work with Visual Studio. They are stand-alone applications, used to create specialized tools that can communicate with Visual Studio. Something to know is that Visual Studio Shell Isolated projects are not found under your favorite language under Extensibility like all others extensions, but can be found under Other Project Type ➤ Extensibility.

T4 Templates T4 text templates create files, text within these files, and logic that can be generated by Visual Studio. This is the case for any project that Visual Studio uses. For example, if you select a new ASP.NET MVC project, Visual Studio generates a default controller, views, setup folders for Script, Content, and so on, all with T4 templates. This section covers two T4 templates, Runtime and Design-time.

211


Chapter 9 ■ Extending Visual Studio

Runtime T4 Templates Runtime T4, or preprocessor text, templates are executed to produce text strings. They are very simple, and the templates look a lot like the final output. The difference from a static file is that these can contain small chunks of code between <# and #> markers. They are described as runtime, or preprocessor, because the template executes the code during the execution of the program, not during the insertion of the template into your project. Here is an example:   <#@ template language="C#" #> <html><body> The date and time now is: <#= DateTime.Now #> </body></html>   This code is executed only when the application runs. In this example, the time printed is the execution time. However, if this example had been created with the Design-time T4 template, the printed time would have been the time when the file was inserted into the project. Because it does not execute anything before run time, the Design-time T4 template type does not require Visual Studio. We will discuss Design-time T4 in the next section. To create a Runtime T4 file, select Add New Item from the Add menu. Under your preferred language (VB or C#) in the General category, select Runtime Text Template. This is illustrated in Figure 9-6.

Figure 9-6.  Adding a new Runtime Text Template Once the template is created, you can use it in your code. To do so, call the T4 template by its name as if it was a class to instantiate an object. The instantiated T4 can then be used with the method TransformText to produce the output. Here is an example of code with a T4 template called ApressRuntimeTextTemplate1.tt.   var t4 = new ApressRuntimeTextTemplate1(); var t4Compiled = t4.TransformText();   It is possible to create Runtime templates that are more complex, by passing parameters to them. The parameters are passed by the constructor. To create a constructor to your T4 template, you need to have a class that has the same name as the T4 template filename. For example, with the ApressRuntimeTextTemplate1.tt you can create an ApressRuntimeTextTemplate1Code.cs and have a class named ApressRuntimeTextTemplate1 inside it. The .tt file can use any element that the class contains, even private fields.

212


Chapter 9 ■ Extending Visual Studio

Design-Time T4 Templates Design-time T4 templates are used by Visual Studio for ASP.NET MVC. The engine executes dynamic files and folder structures. Their main advantage is that you can generate code from simple business logic information. This creates stable and strong code that can be easily regenerated at any time, and it allows you to centralize a structural change once and generate the template again to apply changes. T4 text templates used for Design-time T4 contain static text and program code. Code allows you to do loops, manipulate variables, and create conditional statements to generate files. For example, you can have a custom T4 template that generates the Model, Entity, and View Model classes from a simple static file that has a list of names with properties. Running the T4 template would create three files for each entry. If in the future a new property is required, you could just change the T4 template and execute it again to generate all Model, Entity, and View Model classes. To create a new T4 template, go to New Item on any of your projects, select your language (C# or VB.NET), and choose General ➤ Text Template, as shown in Figure 9-7.

Figure 9-7.  Creating a Design-time T4 template If you click the generated .tt file and open the Properties panel, you will notice that it uses the Custom Tool TextTemplatingFileGenerator. Previously, with the Runtime T4, the Custom Tool was set to TextTemplatingFilePreprocessor. The difference is that if you expand the .tt file, you will see a.txt file generated with the content of the .tt file. This .txt file is generated every time the T4 template is saved. Figure 9-8 shows a T4 template that adds the time. It is also possible to choose Transform All T4 Templates from the Build menu to execute the template.

Figure 9-8.  T4 Template and the generated file

213


Chapter 9 ■ Extending Visual Studio

Of course, the file you create does not need to be a.txt file. You can create a .cs file to create classes. You can also choose where to publish the output file or files. Notice that the first line is a template instruction. The Debug property can be set to True, and breakpoints can be set in the template as in ordinary C# or VB.NET code.

New Visual Studio 2013 Features for T4 Templates Visual Studio 2013 has new features for T4 templates. One is the ability to include T4 snippets by including only one template. The only modification is to add a once property set to true (once="true") to the Include statement. Visual Studio 2013 enables project-relative assembly reference without having to pass through environment variables. It is now possible to use project properties with include and assembly instructions. T4 templates are now used with Asp.NET (MVC and WebForm) scaffolding features. It is now possible to use all T4 features in scaffolding. Finally, it is now possible to have Visual Studio clean up memory with a specific instruction. This has the disadvantage of slowing down the use of T4 because the cache is cleaned, but it also reduces the memory footprint. This instruction is an XML element that must contain your T4:   <#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #>

SideWaffle SideWaffle is a Visual Studio add-on. It adds snippets, projects, and items templates into Visual Studio. Its goal is to simplify the extensibility of Visual Studio by developing tools for it so that developers can be more productive. This add-on is a community-driven project, but is backed up by the Microsoft team of Sayed Hashimi and Mads Kristensen. You can get this add-on at http://sidewaffle.com/. SideWaffle contains project templates for Browser Link Extension, Code Snippet Extension, Google Chrome Extension, Theme and Web Store App. It has item templates for AngularJS (controller, directive, factory, module, and so on), Build Script, Caliburn, CKEditor, DurandalJS, HTML smart tags, Knockout binding, NUnit fixtures, a ReadMe.md file, a Robot.txt file, an SVG file, and so on. It also comes with snippets for Angular, Cross Browser gradient, Nancy, and WCF client usage. You can download SideWaffle using the Visual Studio Extensions and Updates screen. The file downloaded is a .vsix file of about 6 MB. The installation should take less than 5 seconds. From here, you can use templates like the Angular template, but let’s focus on how to use SideWaffle to extend Visual Studio.

Extending Visual Studio with the SideWaffle Item Template You can create a new project of type class library and add new items from Visual C# Items ➤ Extensibility ➤ SideWaffle Item Template. This creates a folder that has the name of the item you just created and contains a definitions folder. By default, this folder holds the Visual Studio template for C# and VB and their web equivalents. You can rename a file by removing the filename’s dash suffix. Figure 9-9 shows both. Label (1) shows the C# file that does not have the trailing dash, whereas label (2) is the VB template file that has it.

214


Chapter 9 ■ Extending Visual Studio

Figure 9-9.  SideWaffle Item Template example What is interesting is that you can add any other files you want to your item template. You could insert an HTML file if you want without a problem into your item template folder, and add this file to the .vstemplate file under ProjectItem in the TemplateContent element. Figure 9-9 shows, on the left side, the .vstemplate that indicates that the readme.txt file is an item. You can do the same.

Extending Visual Studio with the SideWaffle Project Template You can create a project template with SideWaffle as well. For example, if you have a structure that you reuse regularly, you can create a project template from an existing structure. Every time you create this project, the files and structure will be generated for you. To do this, first export your project structure and files. This can be done with Visual Studio by choosing File ➤ Export Template ➤ Project Template. This opens a wizard where you will be asked to specify a template name, template description, and so on, as illustrated in Figure 9-3 earlier in the chapter. The result of this wizard is a compressed file (zip). SideWaffle is used for the distribution. You can create a new C# Project Template and add the exported files to this project (you need to decompress it first). To make the project work with SideWaffle, create a folder named Definitions and drag and drop the .vstemplate into this new folder. This is similar to the SideWaffle Item Template. You will have to rename the file to CSharp if you want this project to be available to C# or rename it to Vb for a VB.NET project.

Browser Link Communication with Visual Studio Browser Link is a new feature included with Visual Studio 2013. It allows communication between Visual Studio and any browser. I decided to discuss Browser Link in this chapter because you can create extension code and custom features for Visual Studio with Browser Link in addition to what is installed from scratch with VS. Browser Link opens communication from Visual Studio to any web project in any web browser. It is a channel of communication created with the combination of JavaScript and Microsoft SignalR technology. Visual Studio is a SignalR server that opens a channel of communication. Visual Studio injects JavaScript into any of your debugging projects and starts a two-way directional communication. This mean that Visual Studio can send data to your web pages, but it also means that modifications on the web pages can be pushed back to Visual Studio. Imagine that you modify a CSS file in Visual Studio; this can be updated to your browser without having to refresh anything. This is also the case if you modify a CSS property directly from any browser inspector; Browser Link could map the modification back to the source code in Visual Studio. Browser Link requires the latest version of Microsoft Web Essentials, which adds new capabilities to Visual Studio for the web. Web Essentials can be found on the Internet (http://vswebessentials.com/) or in Visual Studio Extension libraries.

215


Chapter 9 ■ Extending Visual Studio

Starting any web project by pressing F5 starts the default browser with an attachment from Visual Studio to IIS Express (or IIS). You can open multiple browsers for the same website, and Visual Studio will connect to all of them. It is possible to see all browsers that Visual Studio has a communication channel open with through the Browser Link Dashboard, which you can open in View ➤ Other Windows ➤ Browser Link Dashboard. Figure 9-10 shows the icons to refresh every browser linked to Visual Studio with Browser Link (1). At (2) is the Browser Link Dashboard, where all connections are available.

Figure 9-10.  Browser Link icon in the toolbar and the Browser Link Dashboard The Browser Link Dashboard is very useful if you have multiple browsers open, emulators for phones, or different browser resolutions open. You can click this button and have everything reloaded without having to go through every browser. You can use the dashboard to find what connection you have, but also to cherry-pick which browser to update. Closing a browser that was connected automatically closes the connection between Visual Studio and that browser. Further updates will not update or reopen the closed browser. You can also hover your mouse over the Command button to see all connected browsers. This has the advantage of not having the dashboard open to see what is connected to Visual Studio. Figure 9-11 shows an example of code injected by Visual Studio to enable communication with SignalR and JavaScript. You can disable that feature if you are debugging JavaScript to remove some noise. Unchecking Enable Browser Link from the dropdown command item of the toolbar disables this feature. It is also possible to change an appsetting to disable the communication. Setting an entry inside the appsetting with the key vs:EnableBrowserLink and the value False produces the same effect. This will disable Browser Link. Otherwise, keeping this code allows you to use Browser Link. Do not worry about having this code in a production version of your application, because it is only available when compiled in Debug.

Figure 9-11.  Example of the injected code by Visual Studio for SignalR communication

216


Chapter 9 ■ Extending Visual Studio

Extending Visual Studio with Browser Link Extending Visual Studio with Browser Link adds several useful features, and Microsoft has created a project called Web Essentials that uses Browser Link capability. You can write this kind of extension yourself if you want. I will concentrate on Web Essentials to show you what is possible with Browser Link. You can get Web Essentials from Visual Studio Gallery or directly from Visual Studio in the Extensions and Updates window, located in Tools as shown in Figure 9-12. A benefit is that this extension is updated every two weeks.

Figure 9-12.  Web Essentials 2013 is available at Extensions and Updates Once it is installed and you start a web project, a new bar will appear at the bottom of the web page. Figure 9-13 shows an example of what is injected into the HTML. This toolbar can be hidden if you click Auto-hide. To make it appear, just press the Ctrl key on the keyboard.

Figure 9-13.  Web Essentials web page toolbar The Design button lets you select any web component. It transforms one component into an editable control directly in the web page. The editing done in the page is automatically pushed back to Visual Studio. This means that if you change a label text, it will be changed automatically in the .cshtml of the view. The Inspect button inspects any HTML element. Your mouse cursor becomes a cross, and you can click anything on the web page. This will move you to Visual Studio at the place where the .cshtml generates the HTML. This can be done because of a Browser Link that associates the rendered webpage with the source in Visual Studio. In Figure 9-14, we’ve selected Application Name on the left; on the right, Visual Studio automatically opens to the file that generated the link.

Figure 9-14.  Using the Browser Link Toolbar’s Inspect button

217


Chapter 9 ■ Extending Visual Studio

You can apply all the changes by pressing F12 or, if you check the F12 Auto-Sync option in the toolbar, the display will change automatically to Visual Studio. Finally, when the Auto-hide button is checked, it starts recording the use of CSS until you uncheck it.

Customizing Code Snippets With only a few keystrokes in the code editor, you can have the Code Snippets Manager generate code. This tool simplifies development by creating reusable code that can be accessed rapidly. Two popular snippets are ctor to generate a class constructor and prop to create a property. Generated snippets can be intelligent, by providing placeholders, too. For example, prop generates a property with placeholders for a type and for the name. You can create your own code snippet and use it on all your projects where the snippet is installed. Under the hood, a code snippet is an XML file. Usually the extension is .snippet. You can save your snippet anywhere you want and then import that folder from Visual Studio. To import snippets, select Tools ➤ Code Snippet Manager in Visual Studio. You can also add a new folder to be linked into Visual Studio. Figure 9-15 shows the Code Snippets Manager. As you can see, a Visual C# snippet is linked to program files. You can add your own snippet repository in your My Documents folder if you want. The Add button of the manager lets you select snippets to be added to your snippet folder, which is located here: %USERPROFILE%\Documents\Visual Studio 2013\Code Snippets\Visual Basic\My Code Snippets. On the other hand, clicking Import can add a new folder at the location you want.

Figure 9-15.  Code Snippets Manager An example of a snippet follows. You can see that it begins with a <Header> element, where you define the name of the snippet and its description. This is also where you specify the shortcut that is used to trigger the code in the snippet defined under the <Code> element. The <Code> element has an attribute where the language, such as C# or VB, is specified.

218


Chapter 9 ■ Extending Visual Studio

<?xml version="1.0" encoding="utf-8"?> <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title>Apress Title</Title> <Author>Patrick Desjardins</Author> <Description>I am writting some code.</Description> <Shortcut>apress</Shortcut> </Header> <Snippet> <Code Language="csharp"> <![CDATA[public void ApressMethod(string param1) { //This is empty }]]> </Code> </Snippet> </CodeSnippet> </CodeSnippets>   This snippet can add references. For example, if you are using something that must have references to assemblies, you can specify within the snippet which one to add. Simply add under the snippet a <Reference> element with the assembly you want to import, as shown here:   <References> <Reference> <Assembly>ToImport.dll</Assembly> </Reference> </References>   You will also want to add the Using statement at the top of the file where the snippet is activated. To do so, you must add an <Import> element with the desired import:   <Imports> <Import> <Namespace>Your.Name.Space</Namespace> </Import> </Imports>   Finally, it is possible to include placeholders. These are called replacements and can be of two forms: literals or objects. Literals change a string like a variable name or a value. Object replacements are instances of some type other than a string:   <Declarations> <Literal> <ID>VariableToBeReplaced</ID> <ToolTip>Describe the goal of the variable</ToolTip> <Default>"Default Value"</Default> </Literal>

219


Chapter 9 ■ Extending Visual Studio

<Object> <ID>VariableObjectToBeReplaced</ID> <Type>System.DateTime</Type> <ToolTip>Describe the goal of the variable</ToolTip> <Default>defaultDateTime</Default> </Object> </Declarations>   The last step is to add the replacement placeholder. You do this by specifying the variable ID in the code snippet between dollar signs. From here, if you open Visual Studio, type the shortcut, and press the Tab key, the shortcut will be erased and the focus will be on the first replacement variable. Pressing Tab again without typing will insert the default value and set the focus to the other replacement variable, and so on. Visual Studio can generate snippets that insert code as we just saw, but it can also generate surrounding code. For example, you can insert code before and after the selection. This is useful for structures like try-catch or if-else. This second type of snippet is named SurroundWith. These snippets are triggered by right-clicking and selecting Surround With, or by pressing the Ctrl+K, S shortcut. You’ll see a list of all possible snippets, as shown in Figure 9-16.

Figure 9-16.  Creating a Surround With snippet To create this type of snippet you must add to the header element a <SnippetTypes> element that contains the SurroundsWith type:   <SnippetTypes> <SnippetType>SurroundsWith</SnippetType> <SnippetType>Expansion</SnippetType> </SnippetTypes>   You can also use the keyword $selected$ to specify in the code where the surround must take place. A good way to learn more about code snippets is to open an existing one. They are all located in the Code Snippet Manager. Learning is easy because code snippets are XML files.

Creating Your Own HTML Smart Tag An HTML smart tag is a little box that provides options for refactoring. The box can be open and display multiple choices. You can display a smart tag by pressing Shift + Alt + F10, or by moving your mouse over the box. You can see smart tags not only in HTML but also in C# classes. Figure 9-17 is an example of a smart tag open for a placeholder.

220


Chapter 9 ■ Extending Visual Studio

Figure 9-17.  The HTML smart tag feature in action To create your own HTML smart tag, you must have SideWaffle installed. It has an item that can be added to an Editor Classifier project. The selection of an Editor Classifier project is useful because if you set the project as the startup project and press F5, you will be able to debug the extension. You can also use other types of projects, like VSIX, to create your own HTML smart tag. In fact, you want a project template that has a .vsixmanifest extension to be able to deploy your extension. Whatever the type (vspackage or vsix) of project chosen, you must delete all .cs files to start your new HTML smart tag. Figure 9-18 shows the panel that has the HTML Smart Tag item template to use. In this example it is under C# ➤ Extensibility ➤ HTML Smart Tag, but the same panel can also be found under VB. This is the item you must have to be able to develop an HTML Smart Tag extension.

Figure 9-18.  Add a new Extensibility item for creating an HTML smart tag Opening this panel will create a single .cs file that has two classes. One is a provider that inherits from IHtmlSmartTagProvider, and the other is your smart tag class, which inherits from HtmlSmartTag. Visual Studio will read the provider and register it. Every provider registered has a condition to trigger your smart tag. For example, it’s possible to have a smart tag on a specific HTML tag, such as a DIV tag. It is also possible to specify that you want the smart tag to appear only when it does not have a class specified. Once you have written the provider, you can develop the smart tag. You specify the name that will be written in the smart tag, and also the action. For example, you can write “Add Apress class” in the smart tag, and if the user decides to click it, then you can make it add the class attribute with a named class apress. If you press F5, Visual Studio opens in a sandbox with a temporary extension installed for you. In this sandbox, if you have an HTML element that does not have a class attribute, you will see the smart tag available to be clicked, as shown in Figure 9-19.

221


Chapter 9 ■ Extending Visual Studio

Figure 9-19.  An HTML smart tag triggered Once pressed, this executes the Invoke() method that contains that action to be done by your smart tag. In this example, it has added a class named apress; the result is illustrated in Figure 9-20.

Figure 9-20.  HTML smart tag applied

Creating a Smart Tag for the Code Editor It is also possible to create a smart tag for any element in Visual Studio. Doing so allows a set of actions to appear on any text in the code editor. Often, in the Visual Studio code editor, you see a red line that appears under a variable or a class. This is where you can suggest your own action within a smart tag. The process of creating a new smart tag starts by creating a new project with the Editor Classifier template. Figure 9-21 shows this template. Three C# or VB files are created, along with a .vsixmanifest file. These three files can be deleted because they are used to extend Visual Studio in a different way than by using a smart tag. The first step is to create a class that inherits from SmartTag.

Figure 9-21.  Creating a smart tag for the code editor Then, create a new constructor that calls the base class. You have the choice of two smart tag types to pass to the base class. The first type is Factoid; a blue line, known as the Ephemeral, appears under the selected word when a smart tag is available. The second type is a red line that appears under the last character of the desired word. It is important for IntelliSense to know that this tag class can trigger our custom smart tag. From there, we must create the tag action. Create a new class that implements the ITagger<T> interface. This generic interface will take the class we just created as a template. This new class provides a tag for Visual Studio. You must implement the GetTags method to be able to get all tags that intersect strings. We will not go into detail on this method, but you can navigate through the code in the code editor and add some logic with the cursor position and the text behind it to figure out if your smart tag should trigger.

222


Chapter 9 ■ Extending Visual Studio

The next step is to create a provider class that implements IViewTaggerProvider. This class must use some attributes, like Export, before you can use the MEF plug-in system that Visual Studio uses. You can also provide other attributes, like the context type, the tag type, and the order. Finally, you must create at least one ISmartTagAction. The action appears once the tagger has found a match. Our class that inherits from ITagger has a method called GetSmartTagActions, which gives actions that are added and returned. These actions must inherit from ISmartTagAction. It is possible to define the text to display, the icon to show, the action enable status, and the action that must be invoked for your smart tag. As you saw with the HTML code snippet, if you set your smart tag project to be the startup project, you build the project and run the project. Visual Studio starts a new instance of Visual Studio with the smart tag installed for you to test.

Using an MSIL Disassembler Whatever you are doing, at some point you will have to manipulate DLLs. Even your code is compiled into a DLL. The .NET virtual machine reads Microsoft Intermediate Language (MSIL) code, which is now more often named Common Intermediate Language (CIL). It shows what is in the DLL, not your C# or VB code. CIL provides a standard way to use your chosen language as a common base for .NET. To create a wrap up, when you are compiling from Visual Studio, your C# or VB code is translated into CIL. The CIL is assembled into bytecode and packaged into a DLL. When it is time to execute the code, the CIL assembly is translated into native code. Let’s look at two disassemblers: ildasm.exe and ILSpy.

Using ildasm.exe Visual Studio comes with ildasm.exe, which takes a file and displays the interpreted language. It is possible to see the interpreted language (IL) for .exe or .dll files. The command line that follows is an example of how to execute the tool to generate an output file with the interpreted language.   ildasm MyFile.exe /output:MyFile.il   However, the tool also has a user interface. You can simply execute ildasm and the application will show a menu that lets you choose the file to dissemble to show the interpreted language. This tool can be opened easily by typing ildasm at a Visual Studio developer command prompt. Otherwise, you can find this tool in Visual Studio tools. Figure 9-22 shows the interface that opens to a small class library that does not have a lot of methods. If you double-click one of the methods, a window opens with the IL code of this C# code.   public int Method1(int x) { var result = x; result += Method2(); return result; }

223


Chapter 9 ■ Extending Visual Studio

Figure 9-22.  ildasm.exe user interface This ildasm tool is useful if you want to optimize your code. If you are struggling between algorithms, you can create them, see the number of instructions they produce, and then compare them. You can also search for a hard-coded string.

Using ILSpy ILSpy is an open source project that is not part of Visual Studio. It is a .NET decompiler that opens an .exe or .dll like ildasm. However, instead of just providing the IL, this tool transforms the IL into C# code. This is very useful if you are using a library that does not belong to you but want to understand how it works. You will be able to see the code. Figure 9-23 shows the same DLL decompiled with ILSpy that we earlier decompiled with ildasm. This time, the tool has a drop-down with three different outputs (1). You can choose C#, VB, or IL. If you select C#, the tool extracts the IL and builds back C#. This means that it will not have the same syntax as your C# code, nor will it contain any comments. It is not the real source code but the interpreted code. Label (2) shows where all methods and properties of all classes of the selected file are listed. If you click any library element, the right panel (3) shows the output.

224


Chapter 9 â– Extending Visual Studio

Figure 9-23.  ILSpy decompiling an assembly into C# code

Obfuscation Techniques to Protect Your Code Obfuscation is the process of modifying the assembly code so it cannot be read by any disassembler. Depending on the type of project you are developing, you may have to deliver your software with your libraries and executables. However, you saw in this chapter that it is possible to disassemble the code and get the C# code. This is not always desired, because your competitor can get your logic and use it. This is where obfuscation comes into play. Obfuscation occurs in different flavors. It can change names of classes, methods, properties, and variables to make them hard to understand. Obfuscation can change strings into a structure that makes it harder to search for them. Searching for strings could indicate where a specific behavior could be. Obfuscation can generate code to make it harder to associate strings and behaviors. It is also possible to have obfuscation for control flow. It modifies the program to have the result as the same as it would be without obfuscation. It also possible for some obfuscators to encrypt the MSIL. Visual Studio does not provide obfuscation by default with the 2013 version. However, Visual Studio 2003 to 2008 had an obfuscator included.

Summary This chapter was all about extending Visual Studio. The techniques covered here are not ones we use every day, but they can be valuable to improve your productivity by allowing you to avoid repetitive tasks. We saw that we could improve Visual Studio with T4 templating, which can generate code files for you. Extensibility is easier than ever with SideWaffle, which is a layer over Visual Studio that reduces complexity to improve functionality. Finally, we saw tools to create code snippets and explore code that has been compiled.

225


Index

A, B Application Lifecycle Management (ALM), 40

C Class Library, 54 Code Map architecture activity diagrams, 126 class diagrams, 124 components diagram, 128 directed-graph diagrams, 128 layer diagrams, 120 sequence diagrams, 123 use case diagrams, 127 clone analyzer limitations, 119 maintainence, 119 refined results, 119 working principles, 118 code metrics class coupling, 132 cyclomatic complexity, 132 inheritance, 131 lines of code, 130 maintainability index, 133 libraries, 117 methods command bar, 117 FilteredDbSet, 115 references, 116 SetOwnable method, 116 show containing type, 117 static code analysis FxCop, 134 panel, 133 StyleCop, 134

Configurations database tools, 47–48 debugging, 44 environment, 29 Add-in Security, 31 AutoRecover panel, 31 documents, 31–32 Extensions and Updates, 33 Find and Replace dialog, 33 Fonts and Color, 33 General panel, 30 Import and Export Settings panel, 33 International settings panel, 33 keyboard panel, 33–34 Quick Launch panel, 34 Startup panel, 35 synchronized settings panel, 35 Tabs and Windows panel, 35 Task List panel, 37 Web Browser, 38 HTML Designer, 49 Import and Export Settings, 51–52 IntelliTrace panel, 45–46 menu bar, 26 Add Command, 27 Customize dialog, 25 group creation, 27 renaming, 27 package sources panel, 50 performance tools, 46 project properties Application/Library panel, 53–54 Build Events panel, 54 Build panel, 54 code analysis, 57 Debug/Web panel, 55 Resources tab, 55

227


■ index

Configurations (cont.) Signing panel, 56 types, 53 Projects and Solutions panel default values, 39 General area, 38 symbolic renaming, 39 UNC path, 39 Source Control pane, 40 Text Editor (see Text Editor panel) toolbar commands, 28–29

D Debug.Assert method, 98 Debugging breakpoints conditional, 95 edit and continue, 96–97 Filter, 96 Hit Count option, 96 overview of, 93 usage, 93 Call Stack, 107 Code Map, 108 Counter method, 107 Hot Path, 112 IntelliTrace Events view, 109 HouseName method, 110 modes, 109 navigation buttons, 110 Page Inspector, 105–106 performance and diagnostics, 112 process, 97 profiling, 112 tracepoint, 111 window autos, 100–101 breakpoints, 102 immediate, 99 locals, 100–101 memory, 103 modules, 105 output, 98 parallel stacks, 104 process, 105 QuickWatch, 100 threads, 103 watch, 99 Debug.Write methods, 98 Development tools, 59 documentation C#, 84 Razor comments, 86

228

VB.NET comments, 85 Visual C++ comments, 86 XAML, 86 editor window (see Editor window) navigability (see Navigability) NuGet command prompt, 91 FlagConsole library, 91 libraries, 90 package manager console, 90–91 Restore option, 92 One Click Web Deployment, 87 Web Deploy, 87 Win8 application, 88–89

E Editor window C# IntelliSense, 59 Code Lens, 63 CSS IntelliSense, 62 database panel, 67 definition, 59 Go to Definition, 65 Go To View, 65 JavaScript IntelliSense BootStrapper, 60 JQuery, 60 variable, 61 Peek Definition, 64 Razor Add View controller, 65 attributes, 67 model class, 65 report designer data source configuration, 69 limitations, 71 parameters, 71 properties, 71 rdlc file, 70 resource files, 74 WPF editor (see Windows Presentation Foundation (WPF) editor)

F, G, H Framework SharePoint framework, 182 WCF, 192 configuration tool, 193 service consume, 195 templates, 193 testing, 194 web frameworks, 179


■ Index

WF framework flowchart workflow, 196 sequential workflow, 198 state machine workflow, 200 windows store application, 189 creation, 190 developer license, 190 Microsoft blend, 191 Win 8 Apps, 191 WinForms framework, 182 access component events, 185 layout components, 184 properties panel, 183 WPF framework, 186 properties window, 188 visual designer, 187

I, J, K IntelliTrace panel, 45–46

L LightSwitch client-side screen, 204 data designer, 203 file structures, 202 screen editor, 204 templates, 201

M Managed Extensibility Framework (MEF), 207 Menu bar, 26 Add Command, 27 Customize dialog, 25 group creation, 27 renaming, 27 Microsoft Fakes framework shims, 140 stubs, 141 test manager exploratory testing, 150–151 lab center, 152 Microsoft Developer Network (MSDN), 207 MSIL disassembler ildasm.exe, 223–224 ILSpy, 224–225

N, O, P, Q, R Navigability BaseModel, 77 Base Types, 77 bookmark toolbar, 81

Calls option, 78 Derived By, 77 features, 76 filter icon, 82–83 Find and Replace options, 81 Find in Files option, 80 Is Called By, 79 Is Used By, 77, 79 IUserOwnable, 77 logical elements, 81 method, 78 Navigate To option, 79 physical elements, 81 Quick Find, 80 scrollbar, 83–84 ViewModel classes, 81 Navigation Bar, 43

S SideWaffle, Visual studio, 214 item template, 215 project template, 215 Software Development Kit (SDK) template category, 207 visual studio shell extensions, 211 VSIX Project templates, 208, 210–211 VSPackages installation, 208

T T4 templates design-time, 213 features for, 214 runtime, 212 Team foundation server (TFS), 3, 40, 155 Team foundation services (TFS), 3 Testing code coverage panel, 139 Coded UI tests (CUIT) code dialog, 146 UI control map, 147 UIMAP toolbar, 147 load testing execution bar, 144 graph results, 144 load pattern, 142 run settings, 143 tests distribution, 143 Microsoft Fakes framework shims, 140 stubs, 141 Microsoft test manager exploratory testing, 150 lab center, 151

229


■ index

Testing (cont.) unit testing built-in-templates, 137 default file, 137 tests action, 138 Visual Studio remote debugging, 148 Windows Phone emulator, 149 web performance testing, 144 Text Editor panel All Languages, 42 Drag and Drop, 41 Highlight Delimiter, 41 settings options, 43–44 Track Changes, 42 TFS source control branch branching and merging, 156 maintainence, 155 merging, 155 team explorer, 156 build server, 176 code management, 157 application history, 161 Changesets tab, 162 check-in, 160 check-out, 161 code annotation, 162 merge wizard, 158 resolving conflicts, 158 shelving code, 163 Tracking Changeset, 159 code review, 163 actions, 166 panel, 164 request, 164–165 suspending work, 167 lifecycle development agile, 172 CMMI, 173 processes, 171 scrum, 172 project management, web Alert builder, 176 iteration dialog, 175 pinned items, 174 team portal, 174 web portal link, 173 work items, 167 bug work, 168 multiple workspace, 170 querying, 169 task work, 169

230

TFS Source Control, 41 ThreadFunction(), 103 TypeScript, 205

U Universal Naming Convention (UNC) path, 39

V Visual Studio, 207 browser link communication with Dashboard, 216 JavaScript, 215 SignalR, 215–216 Toolbar’s Inspect button, 217 Web Essentials, 217 code and debug, 16 Code Snippets Manager class constructor and property, 218 class snippet, 20 <Code> element, 218 intellisense, 20 literals/objects, 219 <Import> element, 219 <Reference> element, 219 SurroundWith creation, 220 command window, 14 configurations (see Configurations) docking panels, 11 error list panel, 14 express edition, 1 find and replace dialog, 21, 23 HTML Smart Tag creation C# classes, 220 DIV tag, 221 Editor Classifier template, 222 Invoke() method, 222 item template panel, 221 IViewTaggerProvider class, 223 immediate window, 14 intelliSense list members, 17 Method List, 18 Parameter Info display, 17 Quick Info display, 18 TemplateForComponentD (TFCD), 18 MSIL disassembler (see MSIL disassembler) Obfuscation techniques, 225 Object Browser, 15 online plans, 3–4 pinning panels, 10 premium edition, 1, 3


■ Index

professional edition, 1–2 properties pane, 14 SDK (see Software Development Kit (SDK)) smart tag, 16 solution explorer, 12 start page, 8 ThisIsAlsoAMethod, 19 T4 templates design-time, 213 features for, 214 runtime, 212 ultimate edition, 1, 3 user interface (UI) feedback features, 5 footer information, 5 Quick Launch textbox, 6

W, X, Y, Z Window autos, 100–101 breakpoints, 102 immediate, 99

locals, 100–101 memory, 103 modules, 105 output, 98 parallel stacks, 104 process, 105 QuickWatch, 100 threads, 103 watch, 99 Windows communication framework (WCF), 192 Windows Forms (WinForms) Framework, 182 Windows Presentation Foundation (WPF) editor CamelCase matching, 73 Fuzzy matching, 73 Go To Definition, 72 <StackPanel> tag, 74 XAML code, 72 Windows presentation framework (WPF), 186 Workflow Foundation (WF) framework, 196

231


Visual Studio Condensed

Patrick Desjardins


Visual Studio Condensed Copyright © 2014 by Patrick Desjardins This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law. ISBN-13 (pbk): 978-1-4302-6824-6 ISBN-13 (electronic): 978-1-4302-6823-9 Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. As of the publication date of Visual Studio Condensed, Patrick Desjardins has been an employee of Microsoft Corporation. The views expressed in this book are those of the author, Mr. Desjardins, and do not necessarily reflect those of Microsoft Corporation. Publisher: Heinz Weinheimer Lead Editor: Gwenan Spearing Technical Reviewer: Robert Swafford Developmental Editor: Anne Marie Walker Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Louise Corrigan, Jim DeWolf, Jonathan Gennick, Jonathan Hassell, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Steve Weiss Coordinating Editor: Christine Ricketts Copy Editor: James A. Compton Compositor: SPi Global Indexer: SPi Global Artist: SPi Global Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail rights@apress.com, or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this text is available to readers at www.apress.com. For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/.


I dedicate this book to my wife, MĂŠlodie Savaria, who has been patient during the time I took to write this book. I also dedicate this work to my parents, who opened the path to all my realizations, present and future.


Contents About the Author �������������������������������������������������������������������������������������������������������������� xvii About the Technical Reviewer ������������������������������������������������������������������������������������������� xix Acknowledgments ������������������������������������������������������������������������������������������������������������� xxi Introduction ��������������������������������������������������������������������������������������������������������������������� xxiii ■■Chapter 1: Introducing Visual Studio ���������������������������������������������������������������������������������1 Visual Studio Editions ��������������������������������������������������������������������������������������������������������������������1 Visual Studio Express Edition �������������������������������������������������������������������������������������������������������������������������������� 1 Visual Studio Professional Edition ������������������������������������������������������������������������������������������������������������������������� 2 Visual Studio Premium Edition ������������������������������������������������������������������������������������������������������������������������������ 3 Visual Studio Ultimate Edition ������������������������������������������������������������������������������������������������������������������������������� 3 Visual Studio Online ����������������������������������������������������������������������������������������������������������������������������������������������� 3

Guided Tour of the Visual Studio UI �����������������������������������������������������������������������������������������������4 The General UI ������������������������������������������������������������������������������������������������������������������������������������������������������� 5 The Start Page ������������������������������������������������������������������������������������������������������������������������������������������������������� 7 Pinning Panels ����������������������������������������������������������������������������������������������������������������������������������������������������� 10 Docking Panels ���������������������������������������������������������������������������������������������������������������������������������������������������� 11 Navigation ������������������������������������������������������������������������������������������������������������������������������������������������������������ 12 Properties ������������������������������������������������������������������������������������������������������������������������������������������������������������ 14 Command Window ����������������������������������������������������������������������������������������������������������������������������������������������� 14 Immediate Window ���������������������������������������������������������������������������������������������������������������������������������������������� 14 Error List �������������������������������������������������������������������������������������������������������������������������������������������������������������� 14 The Object Browser ��������������������������������������������������������������������������������������������������������������������������������������������� 15 Code vs. Debug View ������������������������������������������������������������������������������������������������������������������������������������������� 16

vii


■ Contents

Smart Tag ������������������������������������������������������������������������������������������������������������������������������������������������������������ 16 IntelliSense ���������������������������������������������������������������������������������������������������������������������������������������������������������� 17 Code Snippet ������������������������������������������������������������������������������������������������������������������������������������������������������� 19 Find and Replace ������������������������������������������������������������������������������������������������������������������������������������������������� 21

Summary �������������������������������������������������������������������������������������������������������������������������������������23 ■■Chapter 2: Configuring Visual Studio ������������������������������������������������������������������������������25 Customizing Menus and Toolbars ������������������������������������������������������������������������������������������������25 Menu �������������������������������������������������������������������������������������������������������������������������������������������������������������������� 25 Toolbars ��������������������������������������������������������������������������������������������������������������������������������������������������������������� 28

Visual Studio Options ������������������������������������������������������������������������������������������������������������������29 Environment �������������������������������������������������������������������������������������������������������������������������������������������������������� 29 Projects and Solutions ����������������������������������������������������������������������������������������������������������������������������������������� 38 Source Control ����������������������������������������������������������������������������������������������������������������������������������������������������� 40 Text Editor ������������������������������������������������������������������������������������������������������������������������������������������������������������ 41 Debugging ����������������������������������������������������������������������������������������������������������������������������������������������������������� 44 IntelliTrace Configuration ������������������������������������������������������������������������������������������������������������������������������������� 45 Performance Tools ����������������������������������������������������������������������������������������������������������������������������������������������� 46 Database Tools ����������������������������������������������������������������������������������������������������������������������������������������������������� 47 HTML Designer ���������������������������������������������������������������������������������������������������������������������������������������������������� 49 Package Manager ������������������������������������������������������������������������������������������������������������������������������������������������ 50

Import and Export Settings ����������������������������������������������������������������������������������������������������������51 Project Properties ������������������������������������������������������������������������������������������������������������������������52 Application/Library ���������������������������������������������������������������������������������������������������������������������������������������������� 53 Build �������������������������������������������������������������������������������������������������������������������������������������������������������������������� 54 Build Events ��������������������������������������������������������������������������������������������������������������������������������������������������������� 54 Debug/Web ���������������������������������������������������������������������������������������������������������������������������������������������������������� 55 Resources ������������������������������������������������������������������������������������������������������������������������������������������������������������ 55 Signing ���������������������������������������������������������������������������������������������������������������������������������������������������������������� 56 Code Analysis ������������������������������������������������������������������������������������������������������������������������������������������������������ 57

Summary �������������������������������������������������������������������������������������������������������������������������������������58

viii


■ Contents

■■Chapter 3: Development Tools �����������������������������������������������������������������������������������������59 The Editor Window ����������������������������������������������������������������������������������������������������������������������59 C# IntelliSense ����������������������������������������������������������������������������������������������������������������������������������������������������� 59 JavaScript IntelliSense ���������������������������������������������������������������������������������������������������������������������������������������� 60 CSS IntelliSense �������������������������������������������������������������������������������������������������������������������������������������������������� 62 Code Lens ������������������������������������������������������������������������������������������������������������������������������������������������������������ 63 Peek Definition ���������������������������������������������������������������������������������������������������������������������������������������������������� 64 Go To Features ����������������������������������������������������������������������������������������������������������������������������������������������������� 65 Razor ������������������������������������������������������������������������������������������������������������������������������������������������������������������� 65 The Database Panel ��������������������������������������������������������������������������������������������������������������������������������������������� 67 Report Designer ��������������������������������������������������������������������������������������������������������������������������������������������������� 69 The WPF Editor ���������������������������������������������������������������������������������������������������������������������������������������������������� 71 Resource Files ����������������������������������������������������������������������������������������������������������������������������������������������������� 74

Navigability ����������������������������������������������������������������������������������������������������������������������������������76 Solution Explorer Class Navigation ���������������������������������������������������������������������������������������������������������������������� 76 Navigating Methods in Solution Explorer ������������������������������������������������������������������������������������������������������������� 78 Navigate To ���������������������������������������������������������������������������������������������������������������������������������������������������������� 79 Quick Find and Find in Files �������������������������������������������������������������������������������������������������������������������������������� 80 Bookmark ������������������������������������������������������������������������������������������������������������������������������������������������������������ 81 Search Solution Explorer ������������������������������������������������������������������������������������������������������������������������������������� 81 The Pending Changes Filter ��������������������������������������������������������������������������������������������������������������������������������� 82 The Enhanced Scrollbar ��������������������������������������������������������������������������������������������������������������������������������������� 83

Documentation ����������������������������������������������������������������������������������������������������������������������������84 C# ������������������������������������������������������������������������������������������������������������������������������������������������������������������������ 84 Visual Basic ��������������������������������������������������������������������������������������������������������������������������������������������������������� 85 Razor ������������������������������������������������������������������������������������������������������������������������������������������������������������������� 85 XAML ������������������������������������������������������������������������������������������������������������������������������������������������������������������� 86 Visual C++ ����������������������������������������������������������������������������������������������������������������������������������������������������������� 86

ix


■ Contents

Deploying Your Code ��������������������������������������������������������������������������������������������������������������������86 Web Deploy ���������������������������������������������������������������������������������������������������������������������������������������������������������� 87 One Click Web Deployment ���������������������������������������������������������������������������������������������������������������������������������� 87 Click Once ������������������������������������������������������������������������������������������������������������������������������������������������������������ 88 Win8 Application Deployment ������������������������������������������������������������������������������������������������������������������������������ 88

NuGet ������������������������������������������������������������������������������������������������������������������������������������������90 Summary �������������������������������������������������������������������������������������������������������������������������������������92 ■■Chapter 4: Debugging ������������������������������������������������������������������������������������������������������93 Breakpoints ���������������������������������������������������������������������������������������������������������������������������������93 An Overview of Breakpoints �������������������������������������������������������������������������������������������������������������������������������� 93 Conditional Breakpoints, Breakpoint Filters, and Hit Counts ������������������������������������������������������������������������������� 95 Edit and Continue ������������������������������������������������������������������������������������������������������������������������������������������������ 96

Attaching to a Process ����������������������������������������������������������������������������������������������������������������97 Debugging Windows ��������������������������������������������������������������������������������������������������������������������97 The Output Window ��������������������������������������������������������������������������������������������������������������������������������������������� 98 The Immediate Window ��������������������������������������������������������������������������������������������������������������������������������������� 99 The Watch Window ���������������������������������������������������������������������������������������������������������������������������������������������� 99 The QuickWatch Window ����������������������������������������������������������������������������������������������������������������������������������� 100 The Autos and Locals Windows ������������������������������������������������������������������������������������������������������������������������� 100 The Breakpoints Window ����������������������������������������������������������������������������������������������������������������������������������� 102 The Memory Window ����������������������������������������������������������������������������������������������������������������������������������������� 102

Advanced Debugging ����������������������������������������������������������������������������������������������������������������103 The Threads Window ����������������������������������������������������������������������������������������������������������������������������������������� 103 The Parallel Stacks Window ������������������������������������������������������������������������������������������������������������������������������ 104 The Modules Window ���������������������������������������������������������������������������������������������������������������������������������������� 105 The Process Window ����������������������������������������������������������������������������������������������������������������������������������������� 105 The Page Inspector �������������������������������������������������������������������������������������������������������������������������������������������� 105

Tracing ���������������������������������������������������������������������������������������������������������������������������������������107 Call Stack ����������������������������������������������������������������������������������������������������������������������������������������������������������� 107 Code Map ����������������������������������������������������������������������������������������������������������������������������������������������������������� 108

x


■ Contents

IntelliTrace ��������������������������������������������������������������������������������������������������������������������������������������������������������� 109 Tracepoint ���������������������������������������������������������������������������������������������������������������������������������������������������������� 111

Memory Analysis with Profiling �������������������������������������������������������������������������������������������������112 Summary �����������������������������������������������������������������������������������������������������������������������������������113 ■■Chapter 5: Code Improvement Tools ������������������������������������������������������������������������������115 Code Map ����������������������������������������������������������������������������������������������������������������������������������115 Using Code Map for Methods ���������������������������������������������������������������������������������������������������������������������������� 115 Using Code Map for Libraries ���������������������������������������������������������������������������������������������������������������������������� 117

Finding Cloned Code �����������������������������������������������������������������������������������������������������������������118 How the Code Clone Analyzer Works ����������������������������������������������������������������������������������������������������������������� 119 Refining Results ������������������������������������������������������������������������������������������������������������������������������������������������� 119 Limitations ��������������������������������������������������������������������������������������������������������������������������������������������������������� 119 When to Use the Code Clone Analyzer ��������������������������������������������������������������������������������������������������������������� 119

Architecture Tools ����������������������������������������������������������������������������������������������������������������������120 Editing ��������������������������������������������������������������������������������������������������������������������������������������������������������������� 120 UML and Validation �������������������������������������������������������������������������������������������������������������������������������������������� 120 Visualization ������������������������������������������������������������������������������������������������������������������������������������������������������ 120 Layer Diagrams ������������������������������������������������������������������������������������������������������������������������������������������������� 120 Sequence Diagrams ������������������������������������������������������������������������������������������������������������������������������������������ 123 Class Diagrams �������������������������������������������������������������������������������������������������������������������������������������������������� 124 Activity Diagrams ���������������������������������������������������������������������������������������������������������������������������������������������� 126 Use Case Diagrams ������������������������������������������������������������������������������������������������������������������������������������������� 127 Component Diagrams ���������������������������������������������������������������������������������������������������������������������������������������� 128 Directed-Graph Diagrams ���������������������������������������������������������������������������������������������������������������������������������� 128

Code Metrics �����������������������������������������������������������������������������������������������������������������������������130 Lines of Code ����������������������������������������������������������������������������������������������������������������������������������������������������� 130 Depth of Inheritance ������������������������������������������������������������������������������������������������������������������������������������������ 131 Class Coupling ��������������������������������������������������������������������������������������������������������������������������������������������������� 132 Cyclomatic Complexity �������������������������������������������������������������������������������������������������������������������������������������� 132 Maintainability Index ����������������������������������������������������������������������������������������������������������������������������������������� 133

xi


■ Contents

Static Code Analysis ������������������������������������������������������������������������������������������������������������������133 The Code Analysis Panel ������������������������������������������������������������������������������������������������������������������������������������ 133 FxCop, StyleCop, and Code Analysis ������������������������������������������������������������������������������������������������������������������ 134

Summary �����������������������������������������������������������������������������������������������������������������������������������135 ■■Chapter 6: Testing Your Applications �����������������������������������������������������������������������������137 Unit Testing and Code Coverage ������������������������������������������������������������������������������������������������137 Unit Testing �������������������������������������������������������������������������������������������������������������������������������������������������������� 137 Code Coverage ��������������������������������������������������������������������������������������������������������������������������������������������������� 138 Microsoft Fakes �����������������������������������������������������������������������������������������������������������������������������������������������������������������140

Load Testing and Web Performance Testing ������������������������������������������������������������������������������141 Load Testing ������������������������������������������������������������������������������������������������������������������������������������������������������� 142 Web Performance Testing ���������������������������������������������������������������������������������������������������������������������������������� 144

Testing Windows Store Applications �����������������������������������������������������������������������������������������146 Coded UI Test Project ����������������������������������������������������������������������������������������������������������������������������������������� 146 Visual Studio Remote Debugging ���������������������������������������������������������������������������������������������������������������������� 148 Visual Studio 2013 Windows Phone Emulator ��������������������������������������������������������������������������������������������������� 149

Microsoft Test Manager �������������������������������������������������������������������������������������������������������������150 Exploratory Testing �������������������������������������������������������������������������������������������������������������������������������������������� 150 Lab Center ��������������������������������������������������������������������������������������������������������������������������������������������������������� 151

Summary �����������������������������������������������������������������������������������������������������������������������������������153 ■■Chapter 7: Teamwork with Visual Studio ����������������������������������������������������������������������155 How to Use TFS Source Control �������������������������������������������������������������������������������������������������155 What Is a Branch? ��������������������������������������������������������������������������������������������������������������������������������������������� 155 Merging Your Code �������������������������������������������������������������������������������������������������������������������������������������������� 157 Resolving Conflicts �������������������������������������������������������������������������������������������������������������������������������������������� 158 Change Tracking ������������������������������������������������������������������������������������������������������������������������������������������������ 159 Checking In and Checking Out Code ������������������������������������������������������������������������������������������������������������������ 160 Viewing an Application’s History ����������������������������������������������������������������������������������������������������������������������� 161

xii


■ Contents

Labeling a Check-In ������������������������������������������������������������������������������������������������������������������������������������������� 162 Annotating Code ������������������������������������������������������������������������������������������������������������������������������������������������ 162 Shelving Your Code �������������������������������������������������������������������������������������������������������������������������������������������� 163

Code Review ������������������������������������������������������������������������������������������������������������������������������163 Managing Your Work with Work Items ���������������������������������������������������������������������������������������167 Work Item Types ������������������������������������������������������������������������������������������������������������������������������������������������ 167 Querying Work Items ����������������������������������������������������������������������������������������������������������������������������������������� 169 Multiple Workspace ������������������������������������������������������������������������������������������������������������������������������������������� 170

Visual Studio Integration with Different Development Processes ���������������������������������������������171 Life Cycle with Scrum ���������������������������������������������������������������������������������������������������������������������������������������� 172 Life Cycle with Agile ������������������������������������������������������������������������������������������������������������������������������������������ 172 Life Cycle with CMMI ����������������������������������������������������������������������������������������������������������������������������������������� 173

Managing Your Project with the Web �����������������������������������������������������������������������������������������173 Build Server �������������������������������������������������������������������������������������������������������������������������������176 Summary �����������������������������������������������������������������������������������������������������������������������������������178 ■■Chapter 8: Framework-Specific Features ����������������������������������������������������������������������179 Web Frameworks ����������������������������������������������������������������������������������������������������������������������179 The SharePoint Framework �������������������������������������������������������������������������������������������������������182 The Windows Forms (WinForms) Framework ���������������������������������������������������������������������������182 Changing WinForms Properties ������������������������������������������������������������������������������������������������������������������������� 183 Laying Out a WinForm with Visual Studio ���������������������������������������������������������������������������������������������������������� 184 Accessing Component Events with WinForms �������������������������������������������������������������������������������������������������� 185

The WPF Framework �����������������������������������������������������������������������������������������������������������������186 The Visual Designer ������������������������������������������������������������������������������������������������������������������������������������������� 187 The WPF Properties Window ������������������������������������������������������������������������������������������������������������������������������ 188

Windows Store Applications ������������������������������������������������������������������������������������������������������189 What Is Microsoft Blend? ����������������������������������������������������������������������������������������������������������������������������������� 191 Using JavaScript to Create Win 8 Apps �������������������������������������������������������������������������������������������������������������� 191

xiii


■ Contents

Visual Studio WCF Tools ������������������������������������������������������������������������������������������������������������192 Configuring the WCF Service ����������������������������������������������������������������������������������������������������������������������������� 193 Testing a WCF Service ��������������������������������������������������������������������������������������������������������������������������������������� 194 Consuming a WCF Service ��������������������������������������������������������������������������������������������������������������������������������� 195

The Workflow Foundation Framework ��������������������������������������������������������������������������������������196 Building a Flowchart Workflow �������������������������������������������������������������������������������������������������������������������������� 196 Building a Sequential Workflow ������������������������������������������������������������������������������������������������������������������������� 198 Building a State Machine Workflow ������������������������������������������������������������������������������������������������������������������� 200

Visual Studio LightSwitch ����������������������������������������������������������������������������������������������������������201 Visual Studio TypeScript ������������������������������������������������������������������������������������������������������������205 Summary �����������������������������������������������������������������������������������������������������������������������������������206 ■■Chapter 9: Extending Visual Studio �������������������������������������������������������������������������������207 Downloading and Exploring the Software Development Kit (SDK) ��������������������������������������������207 What You Can Do with the SDK �������������������������������������������������������������������������������������������������������������������������� 207 Installing VSPackages with Visual Studio ���������������������������������������������������������������������������������������������������������� 208 VSIX Project Templates �������������������������������������������������������������������������������������������������������������������������������������� 208 Uninstalling an Extension ���������������������������������������������������������������������������������������������������������������������������������� 211 Visual Studio Shell Extensions ��������������������������������������������������������������������������������������������������������������������������� 211

T4 Templates �����������������������������������������������������������������������������������������������������������������������������211 Runtime T4 Templates ��������������������������������������������������������������������������������������������������������������������������������������� 212 Design-Time T4 Templates �������������������������������������������������������������������������������������������������������������������������������� 213 New Visual Studio 2013 Features for T4 Templates ������������������������������������������������������������������������������������������ 214

SideWaffle ���������������������������������������������������������������������������������������������������������������������������������214 Extending Visual Studio with the SideWaffle Item Template ����������������������������������������������������������������������������� 214 Extending Visual Studio with the SideWaffle Project Template ������������������������������������������������������������������������� 215

Browser Link Communication with Visual Studio ����������������������������������������������������������������������215 Extending Visual Studio with Browser Link ������������������������������������������������������������������������������������������������������� 217

xiv


■ Contents

Customizing Code Snippets �������������������������������������������������������������������������������������������������������218 Creating Your Own HTML Smart Tag ������������������������������������������������������������������������������������������220 Creating a Smart Tag for the Code Editor ���������������������������������������������������������������������������������������������������������� 222

Using an MSIL Disassembler �����������������������������������������������������������������������������������������������������223 Using ildasm.exe ����������������������������������������������������������������������������������������������������������������������������������������������� 223 Using ILSpy �������������������������������������������������������������������������������������������������������������������������������������������������������� 224

Obfuscation Techniques to Protect Your Code ���������������������������������������������������������������������������225 Summary �����������������������������������������������������������������������������������������������������������������������������������225 Index ���������������������������������������������������������������������������������������������������������������������������������227

xv


About the Author Patrick Desjardins has been a Microsoft Most Valuable Professional (MVP) in ASP.NET since 2013. He has studied software engineering and is known for his analysis, resourcefulness, and ability to find effective solutions quickly. Since the early days of his professional career, his focus has been on keeping his knowledge up to date in order to provide quality service to meet his customers’ needs. His main area of interest is Web development, which he has embraced since the early 2000s, and he continues to train in new technologies on a daily basis. Patrick has been developing on .NET professionally since 2004. He has also developed many projects in PHP, giving him a broad perspective on how to develop for the Web. Patrick is driven to help people embrace Microsoft technologies in the enterprise. He is a strong believer in ASP.NET MVC and Entity Framework, which help to produce professional quality websites that follow good standards using HTML5, CSS3, and proven design patterns.

xvii


About the Technical Reviewer Rob Swafford is a senior developer at Sonoma Partners, LLC, specializing in Microsoft Dynamics CRM and .NET web application development. He has been developing in .NET since the early days of the framework, and has been a Visual Studio user since Visual C++ 6.0. His industry experience spans nearly a decade in a wide range of companies from small start-ups to state and local government, and multinational corporations. He currently resides in the greater Milwaukee, Wisconsin area with his wife Jeanna and two young sons.

xix


Acknowledgments Thank you to Simran Chaudhry, Microsoft Community Program Manager, for honoring me as Microsoft MVP in 2013. Also, a big thanks to Gwenan Spearing for giving me the opportunity to write this book with Apress.

xxi


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.