April 2010

Volume 25 Number 04

Better Coding - Better Coding with Visual Studio 2010

By Doug Turnure | April 2010

It’s been 13 years since Microsoft first rolled out Visual Studio, its long-running flagship integrated development environment. The 1997 inaugural release began the alignment of versions 5 of Visual Basic and Visual C++ into a common IDE. It included an Enterprise Edition with a once-famous cast of technologies including Visual InterDev, Microsoft Transaction Server and Visual SourceSafe 5.0. The core purpose of that release was to help developers build distributed applications with components, both as client/server and as Web applications.

We’ve come a long way as developers since then. While modified forms of client/server and Web architectures still dominate the coding scene, the scope and demands of these applications have exploded out of the realm of homogenous systems and strongly typed object-to-object calls.

Representational State Transfer (REST) and related technologies are now becoming mainstream foundational communication mechanisms. Applications are beginning to find a home in cloud-based architectures, putting scalability, reliability and data security in the hands of third parties. And Web application patterns are aligning to commoditized styles and standards. Even hardware is changing, as processor speeds are nearing theoretical peaks with current chip technology, and multicore systems are providing the new way to squeeze ever more performance out of a single computer.

It is into this world, and its unprecedented demands of software and software developers, that Visual Studio 2010 arrives. And, loaded with new capabilities, it stands poised to deliver on the growing requirements of software in a world that now stretches across platforms, cores, styles and standards. This article will cover some of the prominent ways Visual Studio 2010 addresses today’s challenges, to help developers build solutions that thrive in the complex industry where they now reside. Not every new capability will be covered here; rather, the goal of this article is to highlight some of the specific features that developers will be able to put to use immediately in their daily work. Full feature lists are readily available in the product documentation.

Visual Studio IDE Improvements

As software development continues to address more and more complex scenarios, developers often feel pressure to be more productive. Visual Studio 2010 adds several new visual features to the editor itself that help with productivity. I’ll discuss three of them in this section.

One of the simpler improvements to try out in the Visual Studio 2010 IDE is the ability to drag a child window outside of the IDE parent window. Monitors have become affordable enough to allow developers to use two (or more) in their work, and this new feature lets you spread out your coding and design windows across multiple screens.

How It Works Simply click on the tab for the window and drag it outside the Visual Studio IDE window. The window will re-dock just as easily by clicking the title bar and dragging it back into the IDE area, aligning the title bar to the tabs of the other windows. When re-docking, you’ll receive a visual cue when the window is properly aligned: the window will become shaded to indicate it’s ready to re-dock when you release it. Figure 1 shows a code window that has been pulled outside of the IDE’s containing window.

Figure 1 Untethering a Window from the IDE
Figure 1 Untethering a Window from the IDE

Another nice new feature in the Visual Studio 2010 editor is the ability to box select and edit a vertical block of text. Sometimes you need to apply edits to an extended list of items, and you find yourself doing the familiar rapid-repeat keyboard sequence (for example, “n+down arrow+back arrow” over and over). While this may not be the most frequent problem you face, it does happen occasionally, and many developers find themselves wishing they could select a whole vertical block and apply a common change to all lines at once. Visual Studio 2010 introduces this block-edit capability.

How It Works Press and hold down the Alt key and make the vertical selection you want to edit. The highlighted area will function just like a single-line edit, but the edits will be duplicated simultaneously on all selected lines, as shown in Figure 2*.*

Figure 2: box selecting
Figure 2 Box Selecting

There is also a helpful highlighting feature for references in your code. In the editor, when you click on a variable, object, method, property, type or other symbol, all references to that symbol in your code will become highlighted to help you quickly discover where the item is being used.

How It Works Pick a type/variable/method/whatever and simply click on it, and the other instances will become highlighted. Figure 3 shows this for a variable named jumpList; note the gray shading of all uses in code after selecting it with a mouse click.

Figure 3 Highlighted Symbols
Figure 3 Highlighted Symbols

Support for Parallel Programming

Moving a bit deeper into the new IDE capabilities, the next significant new feature I’ll cover is support for parallel programming. Visual Studio 2010 ships with diagnostic tools to help debug and analyze parallel applications. Before jumping into the tooling, however, I’ll briefly discuss what parallel programming is, and then we can see how the runtime and libraries implement these new capabilities.

Many of today’s standard developer machines are multicore, meaning they have two or more individual processors, and the current trend is toward machines with many more cores. Aside from pure innovation, factors such as power conservation and realistic limitations of clock-speed, power consumption and heat are influencing the trend toward multicore systems. Some industry leaders predict that mainstream machines will have 50 or more cores in the next few years.

This presents a unique problem. Prior to the multicore revolution, faster machines meant faster-running applications. However, software that is tied to a single core (as is most current software) can’t take advantage of this emerging architecture. It is therefore critical to target multicore architectures going forward. Before Visual Studio 2010 and the .NET Framework 4, writing code that could make use of more than one core was difficult. To meet this challenge, this release includes some updates to the runtime—and some new types, libraries and tooling—to help developers take advantage of multicore systems.

The .NET Framework 4 includes Parallel Extensions, which has three components: a new Task Parallel Library (TPL), a new PLINQ Execution Engine and a handful of new Coordination Data Structures (CDS). The TPL contains two primary classes. One of these, System.Threading.Tasks.Parallel, includes parallel constructs, such as parallel versions of For and ForEach methods. As the name implies, the PLINQ Execution Engine is a parallelized version of LINQ to Objects, providing a ParallelEnumerable class in place of LINQ’s Enumerable class. Using PLINQ is similar, but not identical, to using LINQ to Objects. Finally, CDS includes a group of thread-safe collections and synchronization primitives to simplify parallel scenarios. CDS includes the familiar players you’d expect in thread-safe collections (ConcurrentDictionary, ConcurrentQueue and ConcurrentStack, for example) and synchronization types (SemaphoreSlim, SpinLock, SpinWait and more).

Visual Studio 2010 brings in support for parallel extensions via a new Parallel Stacks Window, a Parallel Tasks Window and a Concurrency Visualizer. These windows are all designed to give you a better idea of where various tasks are at a given moment in their execution. The Parallel Stacks Window shows how multiple tasks are working their way through their dedicated paths and displays call stacks for the tasks. You have the option to view it in terms of task abstraction or directly as threads. Figure 4 shows the Parallel Stacks window at runtime displaying the task abstraction view option.

Figure 4 Parallel Stacks Window in Visual Studio 2010
Figure 4 Parallel Stacks Window in Visual Studio 2010

The Parallel Tasks Window has been added specifically to support the new task-based programming model. When your application is in break mode, you can use this window to see things such as the list of tasks, the currently executing method for each task, the affiliated thread, application domain, task ID and more. The window is more than a mere static view; you can click a specific task and the IDE will show its status by bringing the currently executing code to the front. Figure 5 shows this window for a sample application. Using this window side by side with the Parallel Stacks Window is a nice way to get a quick view into your executing code.

Figure 5 Parallel Tasks Window in Visual Studio 2010
Figure 5 Parallel Tasks Window in Visual Studio 2010

Finally, to get a deeper analysis of a parallel application, there is a new Concurrency Visualizer in Visual Studio 2010. This window is much more complex than the other two windows and does not currently support Web projects. Its purpose is to give you some insight as to how your application interacts with its environment in multicore and multithreaded scenarios. There are three views:

  • CPU Utilization View shows processor activity.
  • Threads View shows how the threads in your application interact.
  • Cores View provides specific insight on how your threads migrate across cores.

The Concurrency Visualizer depends on Event Tracing for Windows, which means it needs to run in Windows Vista or later. The views—ranging from basic text through full graphical displays—find inefficiencies in your code caused by poorly distributed load across CPUs, execution bottlenecks, contentions and other potential performance inhibitors. Figure 6 shows the Concurrency Visualizer displaying thread usage for a profiled application.

Figure 6 The Concurrency Visualizer in Visual Studio 2010
Figure 6 The Concurrency Visualizer in Visual Studio 2010

Web Updates

Along with the general updates I discussed, you’ll find some notable improvements for Web developers who move to Visual Studio 2010. Of course, the new Model-View-Controller (MVC) programming model tooling is now included, and I’ll cover it in the next section. And there are improved Web development experiences for both client- and server-side Web technologies, as well as a new one-click Web deployment model. But I’ll begin with ASP.NET AJAX and the IDE’s associated new capabilities.

ASP.NET AJAX tooling existed in Visual Studio as of Visual Studio 2008. However, the server-centric templates have led some developers to believe that it did not add significant value to client-side development. While client-side capabilities have always been there, Visual Studio 
2010 includes additional support that really surfaces both the client and server-side capabilities of ASP.NET AJAX. Client-side templates and controls are a significant part of the new features list, as they empower you to take advantage of the improved client data access capabilities, but many other new items such as the jQuery integration are also worth covering.

Prior to Visual Studio 2010 and the .NET Framework 4, if you wanted to use the software download and incorporate the Microsoft AJAX Library with Visual Studio, you got the whole thing injected into your page when you added the ScriptManager. With this release, the Microsoft AJAX Library and the AJAX Control Toolkit have been combined. Also, the Microsoft AJAX team refactored the libraries so you can now ask for the individual pieces you want, rather than be forced into an all-or-nothing choice. You can specify a mode, requesting all, none or specific pieces of the Microsoft AJAX Library.

How It Works In the ScriptManager tag, simply include the AjaxFrameworkMode attribute. You can set it to Disabled, Enabled or Explicit:

<asp:ScriptManager ... AjaxFrameworkMode="Disabled"/>

Disabled means you don’t want the Microsoft AJAX Frameworks loaded. Enabled means you want the existing behavior from previous 
versions (loading the full library). Explicit lets you specify which Microsoft AJAX Library files you want loaded. You can verify this at runtime using View Source with the page loaded.

Similarly, the new Content Delivery Network (CDN) attribute lets you use the most up-to-date versions of script libraries. Previously, you included script libraries such as jQuery or Microsoft AJAX in your project, and the versions you included were the versions you were stuck with for that release. Now, you can request that the latest version be downloaded from Web, rather than stuffing a fixed version into your solutions.

How It Works In the asp:ScriptManager tag, you can include the EnableCdn attribute, setting it to “true”:

<asp:ScriptManager ... EnableCdn="true"/>

ASP.NET AJAX 4.0 also lets you define purely client-side templates. You set up a placeholder <ItemTemplate> and let the client do the rendering based on runtime values, such as a JSON-bound object. The runtime does the instantiation on your behalf, and you don’t have to do the DOM coding to make it work.

One of the most useful additions to ASP.NET AJAX 4.0 is the improved client data access, which uses a new DataView control and client templates to provide easy access and two-way data binding in the client. It’s designed to consume ASMX Web Services, WCF Services, WCF Data Services, MVC Controllers or really anything that returns JSON, and it does this completely from client-side code.

The DataView control is the primary control for supporting client templates. It functions similarly to a ListView control, but it’s implemented purely in client code. It lets you define a template in the client, pull in the data at runtime and then apply formatting to the records as you display them.

How It Works You can set the stage with a very basic setup: create an Entity Data Model over the Northwind SQL database and use a vanilla WCF Data Service that pulls it straight through with no changes, meaning the Employees table should be available for query. With that backdrop, you select the control you want to serve as the template and give it an ID attribute and a class=“sys-template” attribute. When you create the data view, the ID is used to signify the destination for the data pulled through on the bind. You can bind manually, but there is also a syntax using curly braces to directly embed the field name in the markup, which will be replaced when the data is fetched and bound to it. There are multiple syntaxes to accomplish this, but one of the more readable ways to write the script and markup to execute this is using the double curly braces, as shown in Figure 7*.*

Figure 7 Improved Data Access with the DataView Control

   <script type="text/javascript">
                 Sys.components.adoNetServiceProxy], function () {
       var adoNetDataServiceProxy = 
         new Sys.Data.AdoNetServiceProxy('NWDataService.svc');
       Sys.create.dataView("#employeetemplate", {
         dataProvider: adoNetDataServiceProxy,
         fetchOperation: "Employees",
         autoFetch: true
  <div id="employeetemplate" class="sys-template">
      <span>{{ FirstName }}</span><br/> 

One more ASP.NET AJAX item of note is that it has been set up to integrate much more closely with jQuery. With a goal of letting jQuery developers take advantage of the controls in ASP.NET AJAX, all the AJAX Control Toolkit controls are now exposed as jQuery plug-ins automatically. This means jQuery developers can use the controls without having to change their style of development. You can simply think of them as extensions to jQuery.

Beyond the realm of ASP.NET AJAX, there are several other nice enhancements to the ASP.NET programming experience. URL Routing with Web Forms gives URLs a clean, logical feel that is much more search engine optimization (SEO)-friendly, as well as more human-readable. You can define routes in your global.asax file, which maps the requests to the appropriate resources. Not only does this help improve SEO, the pages can take on a predictable path for the user, as shown in Figure 8.

Figure 8 URL Routing Improvements in Visual Studio 2010

New URL Routing Format:
Old URL Style:

There are many more Web-related enhancements worth covering, such as starter Web sites, cleaner HTML and smaller configuration files, but I can’t discuss them all here, so I’ll move ahead to the MVC tooling additions.

MVC Integration

The MVC architectural pattern is a popular way to build highly maintainable and testable Web applications with well-defined boundaries and clear categorization of code by function. MVC is a style of ASP.NET programming that takes full advantage of the ASP.NET framework. It’s an alternative to Web Forms, but it is not a replacement; both models work very well for certain scenarios and skill sets. Developers now have a choice of programming models for Web applications, both based on ASP.NET and fully supported in Visual Studio 2010.

Version 2 of MVC and its affiliated tooling—built between releases of Visual Studio—have been integrated into the Visual Studio 2010 IDE with two project templates, as shown in Figure 9.

Figure 9 MVC Project Templates in Visual Studio 2010
Figure 9 MVC Project Templates in Visual Studio 2010

With the Visual Studio 2010 release, the MVC programming model has focused on three primary areas of improvement. The first is a better separation of concerns. This means more maintainable code through things such as a new RenderAction method for composing business logic separation, and Areas, which let you create “sub-applications” to divide up the functionality in your application. The second area of improvement is a better validation story, made easier through Data Annotations and better bubbling up of validation rules to the client. Finally, there are helper 
improvements. There are now strongly typed helpers, as well as templated helpers, which let you automatically generate UI for entities.

How It Works  RenderAction makes it easy to share a piece of logic across multiple Controllers. To call the RenderAction method from within your View, use the following script (which calls the NewEmployee action within the HRController):

<%  Html.RenderAction("NewEmployee" "HRController"); %>

SharePoint Integration

Another significant integration of tooling into Visual Studio 2010 is the addition of templates for SharePoint Foundation (formerly Windows SharePoint Services). Visual Studio 2010 ships with 12 new templates for SharePoint Foundation, plus the SharePoint 2007 Sequential and State Machine Workflow templates from the Visual Studio Tools for Office add-in to Visual Studio 2008. These templates elevate SharePoint development to first-class status, with a focus on productivity and flexible deployment.

SharePoint Foundation itself is shifting in core usage, moving from being a simple portal you can extend, to a platform for building applications from the ground up, using components such as user management, the underlying list infrastructure and site model. There are significant advances in data access, line-of-business application integration and workflow. Also, there is a more flexible deployment model. Many companies now have massive SharePoint installations and are necessarily more careful about ad-hoc deployment of new SharePoint applications. The new flexible deployment model means you can now sandbox your new installations to specific groups, rather than requiring them to be deployed across the full SharePoint ecosystem.

Visual Studio 2010 has vastly improved the tooling options for building SharePoint applications. True, powerful capabilities for this already existed, but the initial learning curve was fairly tough. With this release, you’ll find excellent support for SharePoint built right into the tools. This includes full, integrated debugging, flexible deployment tooling and improved design support for Business Connectivity Services (BCS), Workflow, LINQ to SharePoint and Visual Web Parts. There is also a better bridge for importing items from the SharePoint Designer tool into Visual Studio 2010.

How It Works Building a visual Web part is considerably easier in Visual Studio 2010 with the new design surface. Begin by choosing to start a new project and selecting SharePoint | Visual Web Part, as shown in Figure 10*.*

Figure 10 SharePoint Visual Web Part Template in Visual Studio 2010
Figure 10 SharePoint Visual Web Part Template in Visual Studio 2010

Note that you need to have SharePoint installed on the developer machine for this, but that is not as hard as it used to be. If you are using Windows Vista SP1 (or later) or Windows 7, you can now install SharePoint on that machine directly and not have to worry about installing Windows Server or setting up a VM for it.

You will be prompted to tell Visual Studio 2010 where you want to install the solution for debugging. Once you have the editor open, you can click on the bottom-left Design tab and begin visually constructing your Web part simply by dragging and dropping controls onto the surface. Note that you may need to open the toolbox (View menu | Toolbox) if it is not already displayed.

Windows 7 Development

With the growing popularity of Windows 7, developers may want to begin adding functionality to their applications to take advantage of some of the rich experiences available on the new platform. There are numerous ways developers can add Windows 7-specific functionality. One of the popular new capabilities is the new Taskbar. Given its early acceptance among users and ease of programming, it’s well positioned for use in applications that target Windows 7.

The Taskbar replaces the Quick Launch taskbar in previous versions of Windows. The Taskbar runs along the bottom (by default) of the Windows 7 screen and allows applications to be “pinned” to it. Moreover, it allows applications to incorporate elements such as jump lists, which are sets of quick links you can get by right-clicking the docked icons, and taskbar previews, which are miniature displays of an application’s open windows.  The Taskbar is easily programmable, both from managed (via the Windows 7 API Code Pack) and unmanaged code, and should be squarely in the crosshairs of developers who want to take advantage of building applications to run on Windows 7.

How It Works Users can pin and unpin applications to the Taskbar simply by right-clicking icons, either in the Start Menu, Explorer or the Taskbar itself. To pin an app, right-click the application (not a document, but the application itself) icon and select “Pin to taskbar.” To remove it from the Taskbar, do the same thing but select “Unpin this program from Taskbar.”

The Taskbar offers both cosmetic and functional improvements for your applications. Any program can be pinned to the Taskbar, whether running or not. The pinned icon can either launch the application or serve to represent minimized windows. When you place the cursor over an icon in the taskbar, it causes a nice visual effect called hot-tracking when the application is running. Hot-tracking takes the dominant icon color and uses it to highlight the icon. Of course, you’ll also see a preview of your running instances of the application just above the pinned icon.

The Taskbar also has a feature called aero-peek. To see this, you can place the cursor over a window preview and the window for the selected preview will snap to the front, with the other windows dimmed. This is a great way for users to take a quick peek at a hidden or minimized window without changing focus or pressing a single key.

For tracking apps, instances of running applications are given an application ID and aligned to their application icon in the Taskbar. As a developer, you can use the TaskbarManager and JumpList classes to programmatically interact with the Taskbar from your applications. Note that to use these classes, you will need to download and reference the assemblies in the free Windows 7 API Code Pack from code.msdn.microsoft.com/WindowsAPICodePack.

This code pack is built by the Windows SDK team and lets you programmatically work with the Taskbar. It also contains several sample applications that have Windows 7 enhancements. You actually set a reference to the compiled assemblies (in this example, browsing for the Taskbar project) within your code.

You also have the flexibility to give multiple instances of an application either the same application ID or unique application IDs, so you can either group or separate them on the Taskbar. To give different instances of an application unique IDs, you need to set the application ID prior to calling Application.Run. If you merely want to give child windows their own icon in the Taskbar, you can change their application ID at any time.

How It Works To give a child window its own icon in the Taskbar, use the JumpList class and call the static method CreateJumpListForIndividualWindow, passing in a child window application ID and the window’s handle. The code looks like this:

childWindowJumpList = JumpList.CreateJumpListForIndividualWindow(
childWindowApplicationId, this.Handle);

Azure Integration

Cloud computing is rapidly emerging as a viable alternative to traditional on-premise and Web hosting architectural solutions. In a nutshell, it’s the idea of taking part (or all) of your software solutions and having a company host everything in a massive datacenter, with on-demand scaling and high reliability. Azure is Microsoft’s cloud-computing and services platform.

Azure is the environment for hosting applications; you can think of it as the OS in the cloud. SQL Azure is essentially the database in the cloud. Azure currently includes two services: The Access Control Service (for federated authentication and claims-based authorization) and the 
Service Bus (for connectivity between solutions in the cloud and on-premise solutions).

Visual Studio 2010 includes multiple project templates for building Azure solutions. For both VB.NET and C#, there are four different templates for Web roles and one for a worker role. There is also a worker role project template for F#. The Web role templates for VB.NET and C# include one each for ASP.NET, MVC with ASP.NET, WCF Services and CGI.

One unique aspect of working with Azure projects in Visual Studio 2010 is that you can select multiple roles for your project when you create it. For example, you can create a new project with an ASP.NET MVC Web role in C# and a worker role in VB.NET. This is why the New | Project experience is slightly different for cloud applications; you actually select the roles out of a dialog box rather than via the single selection paradigm you see with most other project templates.

How It Works To create a project that targets Azure in Visual Studio 2010, you select Cloud from the Installed Templates list, as shown in Figure 11*.*

Figure 11 Selecting a Cloud Project Type in Visual Studio 2010
Figure 11 Selecting a Cloud Project Type in Visual Studio 2010

This will pop up a dialog box where you can select the desired roles, with each role potentially being a different type and/or language. Figure 12 shows a new Azure cloud service project with an ASP.NET MVC Web Role, two VB.NET Worker Roles and an F# Worker Role.

Figure 12 Setting up a Cloud Service Project with Multiple Roles and Languages
Figure 12 Setting up a Cloud Service Project with Multiple Roles and Languages


Multi-targeting itself is not actually new to Visual Studio 2010. However, it has a new extensibility feature that’s worth a look. It’s somewhat surprising to see how many people don’t realize the benefits of multi-targeting and how it enables them to use Visual Studio 2010 to build solutions that will run on earlier versions of the .NET Framework. Multi-targeting is there for development teams that want to take advantage of the latest tooling—with its advanced debugging and improved editor features—but are not prepared to move their code (or perhaps customers) to the .NET Framework 4 just yet. With multi-targeting, you have the option of building applications to target the .NET Framework versions 2.0, 3.0, 3.5 or 4.

How It Works When starting a new project, simply select the targeted framework in the dropdown list as shown in Figure 13*.*

Figure 13 Selecting a Target Framework Version Via Multi-Targeting
Figure 13 Selecting a Target Framework Version Via Multi-Targeting

A new option entitled <More Frameworks…> (note the final entry in the circled drop-down box in Figure 13), allows extensibility in the supported target frameworks. This allows the potential addition of future versions of the framework, and perhaps even other .NET Framework profiles further down the road. Such additions would most likely be installed via MSI, but ultimately could be manually added with an XML description file and copying the framework assemblies directly onto the machine.

And More

There are many other new features in Visual Studio 2010, far more than I have been able to cover in this article. It’s hard to overlook the customizable start page, which gives great opportunities for companies to tie in company-specific resources. And then there are the C++/ANSI updates, the constantly updated Help, the new F# programming language, Entity Framework enhancements, code visualizations and many other new features worth learning. These capabilities serve to further position Visual Studio 2010 as a compelling development tool, one that is capable of delivering the kind of software our industry now expects. Hopefully, you now have a better idea of what is available in Visual Studio 2010. If you would like to try it out, download an evaluation copy at microsoft.com/vstudio

Doug Turnure is a program manager with the Visual Studio team at Microsoft, primarily focusing on customer feedback and adoption. At different times in his career he has been a developer, author, trainer, tweeter, marketer and occasional conference speaker. Turnure now enjoys living in Seattle, after vowing for many years he would never move there.

Thanks to the following technical experts for reviewing this article: Miguel Castro, Mark Dunn and Jim Wooley