unit testing and asp.net mvc -...

46
OCTOBER 2010 Volume 20, No. 10 VisualStudioMagazine.com PLUS The Good, the Bad and the Ugly of C# Using the Visual Studio Scrum 1.0 Process Template Reviewed: Dundas Dashboard and ComponentOne LiveLINQ UNIT TESTING and ASP.NET MVC ASP.NET MVC lets you avoid the domino effect and test discrete sections of code—provided you’re smart in working with Views.

Upload: others

Post on 03-Sep-2019

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

OCT

OBE

R 2

010

Vo

lum

e 20

, No.

10

VisualStudioMagazine.com

PLUS The Good, the Bad and the Ugly of C#

Using the Visual Studio Scrum 1.0 Process Template

Reviewed: Dundas Dashboard and ComponentOne LiveLINQ

UNIT TESTING and

ASP.NET MVCASP.NET MVC lets you avoid the domino eff ect and test discrete sections of code—provided you’re smart in working with Views.

Page 2: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Untitled-5 2 3/5/10 10:19 AM

Page 3: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Sure, Visual Studio 2010 has a lot of great functionality—we’re excited that it’s only making our User Interfacecomponents even better! We’re here to help you go

beyond what Visual Studio 2010 gives you so you can createKiller Apps quickly, easily and without breaking a sweat! Go

to infragistics.com/beyondthebox today to expand yourtoolbox with the fastest, best-performing and most powerful

UI controls available. You’ll be surprised by your own strength!

Infragistics Sales 800 231 8588 Infragistics Europe Sales +44 (0) 800 298 9055

Infragistics India +91-80-6785-1111twitter.com/infragistics

Copyright 1996-2010 Infragistics, Inc. All rights reserved. Infragistics and the Infragistics logo and NetAdvantage are registered trademarks of Infragistics, Inc.

Untitled-5 3 3/5/10 10:19 AM

Page 4: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

programmersparadise.com866-719-1528

Your best source for software development tools!

Prices subject to change. Not responsible for typographical errors.

®

programmers.com/theimagingsource

Download a demo today.

NewServicePack!

Professional EditionParadise #

T79 02101A02$1,220.99

• .NET WinForms control for VB.NET and C#• ActiveX for VB6, Delphi, VBScript/HTML, ASP• File formats DOCX, DOC, RTF, HTML, XML, TXT• PDF and PDF/A export, PDF text import• Tables, headers & footers, text frames,

bullets, structured numbered lists, multipleundo/redo, sections, merge fields, columns

• Ready-to-use toolbars and dialog boxes

TX Text Control 15.1Word Processing ComponentsTX Text Control is royalty-free, robust and powerful word processing software in reusable component form.

programmers.com/pragma

“Pragma SSH for Windows”Best SSH/SFTP/SCP Serversand Clients for Windowsby Pragma SystemsGet all in one easy to use high performance package. FIPS Certified and Certified for Windows.• Certified for Windows Server 2008R2• Compatible with Windows 7• High-performance servers with

centralized management• Active Directory & GSSAPI authentication• Supports over 1000 sessions• Hyper-V and PowerShell support• Runs in Windows 2008R2/2008/2003/

7/Vista/XP/2000

Paradise # P35 04201A01 $550.99

Certified for Windows7/2008R2

ActiveReports 6by GrapeCityIntegrate Business Intelligence/Reporting/DataAnalysis into your .NET applications using theNEW ActiveReports 6.

• Fast and Flexible reporting engine

• Data Visualization and Layout Controls suchas Chart, Barcode and Table Cross SectionControls

• Wide range of Export and Preview formatsincluding Windows Forms Viewer, WebViewer, Adobe Flash and PDF

• Royalty-Free Licensing for Web and Windows applications

Professional Ed.Paradise # D03 04301A01 $1,310.99

NEWVERSION

6!

programmers.com/grapecity

programmers.com/LEAD

LEADTOOLS Recognition SDKby LEAD TechnologiesDevelop desktop and server document imagingand ECM applications that require high-speedmulti-threaded forms recognition and process-ing, OCR, ICR, OMR, and barcode technology.• Supports text, OMR, image, and

1D/2D barcode fields• Recognize machine print and constrained

handwritten text• Auto-registration and clean-up to

improve recognition results• Latin character set support is included.

Arabic and Asian support is availableParadise # L05 26301A01 $3,214.99

BUILD ON VMWARE ESXiAND VSPHERE for Centralized Management, Continuous Application Availability, and Maximum Operational Efficiency in Your Virtualized Datacenter.Programmer’s Paradise invites you to take advantageof this webinar series sponsored by our TechXtend solutions division.

FREE VIRTUALIZATION WEBINAR SERIES: REGISTER TODAY! TechXtend.com/Webinars

FREE 30-DAY PROOF OF CONCEPT

Learn more:programmers.com/eliminate-wasteful-license-spend

STOP OVERBUYING SOFTWARE TODAY!Eliminate Wasteful Software License Spend:• Control your software

licensing costs

• Stop paying for licenses you’re not using

• Reduce your license spend by $300+ per desktop user

programmers.com/vSphere

VMware vSphere Essentials Kit BundlevSphere Essentials provides an all-in-onesolution for small offices to virtualize threephysical servers for consolidating and managing applications to reduce hardwareand operating costs with a low up-frontinvestment. vSphere Essentials includes:

• VMware ESXi and VMware ESX (deployment-time choice)

• VMware vStorage VMFS• Four-way virtual SMP• VMware vCenter Server Agent• VMware vStorage APIs/VCB• VMware vCenter Update Manager• VMware vCenter Server for Essentials

for 3 hosts Paradise #

V55 85101A02

$446.99

programmers.com/flexera

InstallShield Professionalfor Windows 2011by Flexera SoftwareIf your software targets Windows®,InstallShield® is your solution. It makes it easy to author high-quality reliable WindowsInstaller (MSI) and InstallScript installationsand App-V™ virtual packages for Windowsplatforms, including Windows 7. InstallShield,the industry standard for MSI installations,also supports the latest Microsoft technologiesincluding Visual Studio 2010, .NETFramework 4.0, IIS7.0, SQL Server 2008SP1, and Windows Server 2008 R2 andWindows Installer 5, keeping your customershappy and your support costs down.

Upg from any Active IS Pro +

IS Pro Silver MtnParadise #

I21H02401B01

$1,384.99

NEW! Intel®Parallel Studio 2011by IntelA comprehensive, all-in-one toolkit for Microsoft Visual Studio® C/C++developers, Intel® Parallel Studio2011 simplifies the analysis, compiling, debugging, error-checking,and tuning of your serial and threaded apps.

With Intel Parallel Studio, get everything you need to optimize legacy serial code, exploit multicore,and scale for manycore.

programmers.com/intel

Single User DVDParadise #

I23 63101E103

$753.99

NEWRELEASE!

NEWRELEASE!

programmers.com/ca

CA ERwin® Data Modeler r7.3 – Product Plus 1 Year Enterprise MaintenanceCA ERwin Data Modeler is a data modeling solution that enables you to create and maintain databases, data warehouses and enterprise data resource models. These models help you visualize data structures so that you can effectively organize, manage and moderate data complexities, database technologies and the deployment environment.

Paradise # P26 04201E01$3,931.99

FREE WEBINAR SERIES: MAXIMIZING DATA QUALITY FOR VALUE AND ROIData is a company’s greatest asset. Enterprises that can harness the power of their data will be strategically posi-tioned for the next business evolution. But too often businesses get bogged down in defining a Data Managementprocess, awaiting some “magic bullet”, while the scope of their task grows larger and their data quality erodes.Regardless of how your eventual data management solution is implemented, there are processes that need tooccur now to facilitate that process. In this new series, with a mixture of slides, demonstrations and Q&A sessions,we will discuss how to use your existing Data Modeling assets to build the foundations of strong data quality.

REGISTER TODAY! programmers.com/CA

programmers.com/microsoft

Microsoft Visual StudioProfessional 2010by MicrosoftMicrosoft Visual Studio 2010 Professional withMSDN Essentials Subscription is an integrated environment that simplifies creating, debuggingand deploying applications. Unleash your creativityand bring your vision to life with powerful designsurfaces and innovative collaboration methods fordevelopers and designers. Work within a personal-ized environment, targeting a growing number ofplatforms, including Microsoft SharePoint and cloudapplications and accelerate the coding process byusing your existing skills. Integrated support forTest-First Development and new debugging toolslet you find and fix bugs quickly and easily toensure high quality solutions.

with MSDNParadise #

M47 40201A02

$1,060.99

Untitled-1 1 9/1/10 11:43 AM

Page 5: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3

14

Michael Desmond, Editor in Chief, Visual Studio Magazine

FEATURES

14 Unit Testing and ASP.NET MVCMaintaining quality and reliability in software products still depends, ultimately, on testing. With test-driven development and the Microsoft ASP.NET MVC pattern, the Model and the Controller can be tested using the Visual Studio Unit Testing Framework. Testing the View, however, is problematic. BY PETER VOGEL

22 Scrum for EveryoneMicrosoft Senior Program Manager Aaron Bjork offers an overview of Redmond’s new Scrum 1.0 process template. Find out how to use it to run a Scrum project in Team Foundation Server 2010 and drive team development. BY AARON BJORK

30 LANGUAGE LAB

C# Corner PAGE 30 The Good, Bad and Ugly of C#

Patrick Steele looks back at a decade of C# and reminisces about what makes the language such a pleasure to use—and some of the things that could mess up your code if you’re not careful. BY PATRICK STEELE

DEPARTMENTS

6 Letters to the Editor

8 DevDisastersFixing Bad Code from a Contractor

10 DevInsight VSTOOLBOX, VSINSIDER

VSToolbox: Dundas Digital Dashboard Offers Dev Hooks PAGE 10Search Collections with ComponentOne LiveLINQ PAGE 12

VSInsider: Discretionary Development at Microsoft PAGE 13

39 Index of Advertisers

COLUMNS

3 Frameworks BY MICHAEL DESMOND

40 Redmond Review BY ANDREW J. BRUST

{ F R A M E W O R K S }

Knowing DevelopersA lot of people regard Apple and Microsoft as two sides of the same, cynical coin. But if you ask me, I think a core diff erence between the two companies is that Microsoft gets developers, and Apple doesn’t. You can look no further than Apple’s decision last month to reverse its ban on AppStore distribution of programs written in non-native, third-party development tools.

Honestly, I was shocked when Apple announced in April that it would prohibit from its AppStore any iPhone and iPad apps not coded in C, C++, Objective C or JavaScript. That decision cast a lot of third-party tool vendors into the void, including a host of Flash developers caught up in the very public spat between Adobe and Apple, as well as the people at the Mono Project at Novell. The Mono Project MonoTouch tooling allows developers to write .NET-compatible applications for the iPhone and iPad platforms. And I can’t help but think that Apple’s edit must have pleased managers in the Developer Division at Microsoft, which has worked overtime to welcome developers to its Windows Phone 7 platform.

So when Apple caved last month and re-opened the doors to non-native development, I suppose I shouldn’t have been surprised. It was clear that the ban had created a fi restorm of ill will among developers and had handed an important competitive advantage to both Microsoft and the fast-growing Android platform. Even with all the advantages Apple owns with its mobile platforms, surely it could not aff ord to anger the dev community this way.

Apple, in announcing the loosened restrictions, said: “We have listened to our developers and taken much of their feedback to heart.”

My question is, how could Apple have not known what developers would say in the fi rst place? Tell me what you think: [email protected].

October 2010 // Volume 20 // No. 10

Page 6: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

4 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

VisualStudioMagazine.com RedDevNews.com ADTmag.com

Get the complete picture —the latest dev news, analysis and how-to content—at VisualStudioMagazine.com and our partner sites in the Redmond Developer Network.

VISUALSTUDIOMAGAZINE.COM

5 Traps to Avoid in C#BY PATRICK STEELEOur C# Corner columnist off ers a heads up on fi ve gotchas that can trip up even veteran C# programmers. Some of these gotchas have been around since C# 1.0 and still manage to catch developers, while others are native to newer versions of C#, including C# 4.

VisualStudioMagazine.com/Steele1010

Branch by Release in TFS 2010BY MICKEY GOUSSETThis is the fi rst in a series of Inside TFS columns about branching and merging patterns, and how to implement them using Team Foundation Server 2010.

VisualStudioMagazine.com/Gousset1010

Dev Trends for 2011BY BOLA ROTIBIOur Change Management columnist takes stock of some of the major themes and trends that are likely to shape the development space toward the end of 2010 and into 2011.

VisualStudioMagazine.com/Rotibi1010

REDDEVNEWS.COM

Security Hack Exposes Forms Authentication in ASP.NETBY PETER VOGELTwo security researchers have discovered a bug in the default encryption mechanism used to protect the cookies normally used to implement Forms Authentication in Microsoft ASP.NET.

RedDevNews.com/Vogel1010

Microsoft Gets Philosophical about IE 9 Chakra PainsBY KURT MACKIEInternet Explorer 9 will feature a new Microsoft JavaScript engine called “Chakra.” It turns out the ECMAScript 5 spec (also known as JavaScript) is not always clear, and may ignore some conventional Web-coding practices, according to Microsoft.

RedDevNews.com/MackieA1010

Microsoft Releases Windows Phone 7 to ManufacturersBY KURT MACKIEThe company announced that it has completed its main software-engineering tasks on Windows Phone 7. With RTM, hardware partners can begin integrating the new mobile OS into phone products.

RedDevNews.com/MackieB1010

ADTMAG.COM

VMworld Wrap-UpBY JOHN K. WATERSThe WatersWorks blogger talks about the VMware cloud computing strategy, its cloud application platform called vFabric and other news that came out of the company’s annual conference in San Francisco.

ADTmag.com/Waters1010

Games Claim Most-Popular Mobile App CategoryBY KEITH WARDA wide-ranging survey from The Nielsen Company, which presented the data at its inaugural AppNation Conference, uncovered mobile app usage and advertising trends. The survey found that 59 percent of smartphone owners downloaded an app in the last 30 days, and that 61 percent of those apps were games.

ADTmag.com/Ward1010

Playing ‘Poker’ to Plan Agile Projects BY DAVID RAMELA two-day stint of playing “planning poker” was instrumental in helping a university Web team estimate the complexity of scheduled development projects.

ADTmag.com/Ramel1010

EASY FINDITWhat we once called FindIT codes are now easy URLs. You’ll see these embedded throughout Visual Studio Magazine so you can access any additional information quickly. Simply type in VisualStudioMagazine.com/ followed by the FindIT code into your URL address field. (Note that all URLs do not have any spaces, and they are not case-sensitive.)

Online Contents

Page 7: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Free 60 Day Evaluation!www.leadtools.com/vsm(866) 530-3399

Silverlight: 100% pure Silverlight 3 and 4 Imaging SDK.Image Formats & Compression: Supports 150+ image formats and compressions

including TIFF, EXIF, PDF, JPEG2000, JBIG2 and CCITT G3/G4.Display Controls: ActiveX, COM, Win Forms, Web Forms, WPF and Silverlight.Image Processing:

supporting region of interest and extended grayscale data.OCR/ICR/OMR: Full page or zonal recognition for multithreaded 32 and 64 bit

Forms Recognition & Processing: Automatically identify and classify forms and

Barcode:development.Document Cleanup/Preprocessing: Auto-

and border removal, inverted text correction and more for optimum results in OCR and Barcode recognition.PDF & PDF/A:

annotations.Annotations: Interactive UI for document mark-up, redaction and image measurement

(including support for DICOM annotations).Medical Web Viewer Framework:

PACS Workstation Framework: Set of .NET PACS components that can be used to build a full featured PACS Workstation application.Medical Image Viewer:

DICOM:

PACS Communications: Full support for DICOM messaging and secure communication

3D:methods including MIP, MinIP, MRP, VRT and SSD.Scanning:

speed scanning.DVD: Play, create, convert and burn DVD images.MPEG Transport Stream:Multimedia: Capture, play, stream and convert MPEG, AVI, WMV, MP4, MP3, OGG, ISO,

DVD and more.

Microsoft, HP, Sony, Canon, Kodak, GE, Siemens, the US Air Force and Veterans Affairs Hospitals.

color, grayscale, document, medical, vector and multimedia imaging development.

Vector

DICOM Medical

Form Recognition & Processing

Multimedia

Barcode

DocumentSilverlight, .NET, WPF, WCF, WF, C API, C++ Class Lib, COM & more!

Untitled-2 1 8/11/10 11:23 AM

Page 8: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

6 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

A Question About the Entity FrameworkIs the Entity Framework a good replacement for Store Procedures?

Ray AkkansonOhio

Lennie Lobel, CTO of Sleek Technologies and a consultant at twentysix New York, is an expert on Entity Framework and Microsoft .NET Framework data-access technologies. He provided insight for the recent cover story on the Entity Framework (“Get Ready for the Entity Framework,” September 2010). Here, he offers a response to Akkanson’s question:

That’s a loaded question, so I’ll try to drive the key points. In scenarios where you “own” the back-end and have total control over its tables and permissions (which your question pre-supposes), the Entity Framework can be an excellent alternative to stored procedures, particularly for selects. The T-SQL generated dynamically at runtime is much improved from version 1, and while there’s room for improvement, in most cases the Entity Framework generates perfectly adequate T-SQL. So, you can enjoy the power of the Entity Framework by using LINQ to Entities against the conceptual model and allowing the runtime to handle the exact SQL against the database. Furthermore, you can easily import specialized stored procedures into your model for cases when you need to, so it’s not an all-or-nothing prospect.

Keeping It Not-Too-SimpleIn his Redmond Review blog, Andrew J. Brust wrote about LightSwitch and other simple programming tools recently introduced by Microsoft (“Microsoft’s New Tools: Harmony or Cacophony?” Aug. 13, 2010). He wrote that the challenge now is making these solutions work together. A reader responds:

I’m gratifi ed to see [Brust] commenting on how many versions of SQL Server there are and how diff erent development tools target diff erent SQL Server versions. It’s nothing new. There was ASP.NET 2.0 targeting the SQL Server Developer Edition, which had diff erent connection strings and diff erent project-type support. It caused me a lot of trouble with my Visual Studio 2005 Web projects when I upgraded to SQL Server 2005 Standard Edition. [Brust is] right to point it out and say they should clean that up!

L.G.New England

Praise for C# CornerIn his August C# Corner column, “Inversion of Control Patterns for the Microsoft .NET Framework,” Patrick Steele explored Inversion of Control (IOC) containers and Dependency Injection (DI). A reader responds:

As a noob programmer, this is one of the best articles about IOC and DI that I’ve come upon. It really helped to solidify my fragile understanding of IOC and DI. Thanks!

AlAtlanta, Ga.

Visual Studio Magazine wants to hear from you! Send us your thoughts about recent stories, technology updates or whatever’s on your mind. E-mail us at [email protected] and be sure to include your first and last name, city and state. Please note that letters may be edited for form, fit and style. They express the views of the individual authors, and do not necessarily reflect the views of the VSM editors or 1105 Media Inc.

Letters Check out our events at VSLive.comWe’ll be in Orlando Nov. 14-17

VisualStudioMagazine.comOctober 2010 • Volume 20 • No. 10

Editorial Staff

Vice President, Doug Barney Editorial Director Editor in Chief Michael Desmond Executive Editor Kathleen Richards Managing Editor Wendy Gonchar Associate Managing Editor Katrina Carrasco

Tools Editor Peter Vogel

Contributing Editors

Andrew J. Brust, Ken Cox, Kathleen Dollard,Roger Jennings, Jeff Levinson, Bill McCarthy,

Karl E. Peterson, Keith Pleas, Bill Wagner, Dan Wahlin, John K. Waters

Art Staff

Creative Director Scott Shultz Art Director Joshua Gould

Online/Digital Media

Director, Online Media Becky Nagel Executive Editor, New Media Michael Domingo Site Administrator Shane Lee Designer Rodrigo Muñoz

President Henry Allain Vice President, Publishing Matt Morollo Director of Marketing Michele Imgrund Online Marketing Director Tracy Cook

President & Neal Vitale Chief Executive Offi cer Senior Vice President Richard Vitale & Chief Financial Offi cer Executive Vice President Michael J. Valenti

Senior Vice President, Abraham M. Langer Audience Development & Digital Media Vice President, Christopher M. Coates Finance & Administration Vice President, Erik A. Lindgren Information Technology & Application Development Vice President, Carmel McDonagh Attendee Marketing Vice President, David F. Myers Event Operations

Chairman of the Board Jeff rey S. Klein

REACHING THE STAFFStaff may be reached via e-mail, telephone, fax, or mail. A list of editors and contact information is also available online at VisualStudioMagazine.com.

E-mail: To e-mail any member of the staff , please use the following form: [email protected].

Irvine Offi ce (weekdays, 9:00 a.m. - 5:00 p.m. PT)Telephone 949-265-1520; Fax 949-265-152816261 Laguna Canyon Road, Suite 130, Irvine, CA 92618

Framingham Offi ce (weekdays, 9:00 a.m. - 5:00 p.m. ET)Telephone 508-875-6644; Fax 508-875-6633600 Worcester Road, Suite 204, Framingham, MA 01702

Corporate Offi ce (weekdays, 8:30 a.m. - 5:30 p.m. PT)Telephone 818-814-5200; Fax 818-734-15229201 Oakdale Avenue, Suite 101, Chatsworth, CA 91311

Visual Studio MagazineThe opinions expressed within the articles and other contents herein do not necessarily express those of the publisher.

Page 9: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Project3 12/16/09 11:55 AM Page 1

Page 10: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

8 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

</DevDisasters>

Tell Us Your TaleHave you experienced the darker side of development? We want to publish your story. E-mail your tale to Executive Editor Kathleen Richards at [email protected] and put “DevDisasters” as the subject line.

Brandon hired a software development contractor to create a Web portal using ASP.NET to complete a custom software solution for one of his company’s Software as a Service customers. As the project manager, Brandon had budgeted this portal for no more than four weeks of work. If the project were done in-house, utilizing the company’s custom app framework, it would’ve taken no more than two weeks for the internal team’s slowest developers. The dev group simply didn’t have the resources to assign to the project, so Brandon needed to subcontract.

Brandon trained the independent contractor Mark on how to use the app framework. The dev team would code any server code, so Mark was only responsible for the ASP.NET portion of the project.

After about six weeks, Brandon started to realize that things demonstrated to the team as “Complete” weren’t working properly once the developers got their hands on them and were close to UAT deployment. Features were semi-functional—meaning highly unstable—and it was clear that Mark’s nine-year resume and reputation touted by the placement agency were completely farcical.

Good Cop, Bad CopRegardless, as the project manager, Brandon got more involved with Mark’s code, and so did

RefreshCasedataFromInputScreen was 120 lines of code; Brandon called an already existing function, saving another 120 lines.

All in all, he shrunk 363 lines of code (including the more than 240 lines of merge code) into three lines in about 45 seconds. Brandon shook his head as he explained to his wife that Mark had probably spent two or three days writing code—which didn’t even work properly—when there’s a built-in function included by Microsoft. The worst part: Brandon’s team had shown Mark some examples of how to merge the data from their server into his UI.

Merge DisfunctionBrandon tried not to imagine what would have happened if Mark had tried to implement this type of craziness with allof the schemas and datasets they used in the project. The built-in DataSet.Merge function works with any dataset, while Mark’s function worked only with the specifi c type of dataset for which he had coded. He could have spent weeks or months warping his brain to write merge code—hundreds of lines for each diff erent type of dataset. Had he only known about the merge function!

Mark fi nished by telling Brandon that he was so thankful Brandon could help him clean the code up because he was afraid the CTO would see it and tell him there was a better way. Brandon had to tactfully tell Mark that his code was the worst code—and dumbest thing—he’d seen in years. Mark was let go that week and Brandon’s team had to build the portal in-house. VSM

the company’s CTO. The CTO and Brandon decided to do a “good cop, bad cop” routine on him. The CTO, the bad cop, pressured Mark into delivering as he promised or the company wouldn’t be able to aff ord his services.

Brandon got a phone call around 8 p.m. on a Sunday night. The team was supposed to demo the portal for the client the next morning. Mark wanted Brandon to look at his code because he had an “issue.”

Mark explained that the data coming from the server wasn’t matching the data on the front-end. He stated that the data from the server was correct. (And of course it was—Brandon’s team wrote that code for him.) Brandon asked Mark how he was merging the data together and he said that he was using the “merge” function. Brandon logged on and looked at his code and was completely shocked at what he saw!

Simple TaskMark actually wrote more than 240 lines of code to manually merge data from two datasets. Brandon had to mute his microphone to call his wife over to see how pathetic this guy’s code was (see the entire code at VisualStudioMagazine.com/Disaster1010):

btnSave_Click Method was 42 lines; Brandon changed it to four lines.

The method SetCaseRow was 205 lines of completely useless code. Brandon deleted it and replaced the call to SetCase-Row with the DataSet.Merge function: // Merge with the edited data

  casedata.Data.Merge(

RefreshCasedatafromInputScreen(

(CASEDATA)Session["UpdatedCaseData"]

).Data);

Fixing Bad Code from a Contractor

{ S O F T W A R E D E V E L O P M E N T G O N E W R O N G }

Page 11: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Give your users an effective way to visualize and analyze their data

so they can make more informed decisions and solve business problems.

By subscribing to the Esri® Developer Network (EDNSM), you have access to the complete Esri

geographic information system (GIS) software suite for developing and testing applications on

every platform. Whether you’re a desktop, mobile, server, or Web developer, EDN provides the

tools you need to quickly and cost-effectively integrate mapping and GIS into your applications.

Subscribe to EDN and leverage the power of GIS to get more from your data. Visit www.esri.com/edn.

Esri®

Developer Network Integrate Mapping and GIS into Your Applications

Copyright © 2010 Esri. All rights reserved. The Esri globe logo, Esri, EDN, and www.esri.com are trademarks, registered trademarks, or service marks of Esri in the United States, the European Community, or certain other jurisdictions. Other companies and products mentioned herein may be trademarks or registered trademarks of their respective trademark owners.

Untitled-3 1 8/11/10 3:48 PM

Page 12: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

10 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

VSToolbox

BY PETER VOGELBy leveraging its reporting tools and Silverlight, Dundas Dashboard delivers an easily configurable Web-based tool for creating dashboards. The product, from Dundas Data Visualization Inc., comes with a number of components for connecting to data sources and creating dashboards.

Installing Dundas Dashboard was a snap despite the warnings from Dundas that it required expert knowledge. The installation package recognized missing components on my computer and prompted me through downloading and installing them. Once installed, it was easy to open the sample applications and, from my Web browser, customize a Dashboard.

Developer PerspectiveThe ability to create Dashboards is the business story. As a developer, you’re interested in extending the package to your specific needs. Dundas Dashboard does just that by giving you the ability to create custom data connections, new data

visualization and navigation controls—and even create custom security providers if you don’t want to use the Dashboard’s default authorization provider. You can also create new export formats for saving data from a Dashboard into a format compatible with other tools.

To support creating and managing new Dashboard components, Dundas provides three tools: a set of libraries, a C#-like scripting language called DundasScript and a set of utilities for creating and installing plug-in files for Dundas Dashboard. The documentation available on the Web site is complete, but is short on written walkthroughs—though there’s at least one simple sample project for each type of component you’d want to create.

The process for creating a new Data Visualization control is typical of the process for extending a Dashboard, and similar to the process you’d use to add a new feature to SharePoint. All the utilities are provided and it all works the first time.

To create a new control for a Dashboard, you start by creating a Silverlight control, which you compile into a standalone DLL. To integrate your control with the Dashboard, you create a wrapper that inherits from a Dundas class and wire your Silverlight control into three members of the wrapper. You define your control to the Dashboard framework by applying various attributes to the wrapper’s members.

A packager combines your control and its wrapper into a single plug-in for installation. There’s both a GUI and a command-line interface, so you can integrate packaging into your build process. Finally, you copy the plug-in to your server and use the Dundas Dashboard Plugin Manager to install it.

Additional PlusesYou can also integrate a Dashboard into your Silverlight applications with the Dundas Dashboard Viewer. The Viewer honors Dashboard authentication to ensure that users don’t see data for which they’re not approved. You can also add the Viewer to ASP.NET pages and SharePoint sites as a Silverlight control.

Dundas Dashboard is a “call for pricing” kind of product. However, the API is part of the product—so it, effectively, is free. VSM

Peter Vogel ([email protected]) is the tools editor for Visual Studio Magazine and a principal in PH&V Information Services, specializing in ASP.NET development.

Du

nd

as

Das

hb

oard

</DevInsight>

The Plugin Packager (left) allows you to set properties on your package. Using the Plugin Manager (right) you can install or remove plug-ins or view their properties (bottom).

Dundas Dashboard

Dundas Data Visualization Inc.

Web: dundas.com

Phone: 800-463-1492

Price: Call for information

Quick Facts: A flexible, Silverlight-based turnkey package for creating customizable dashboards with an API that allows developers to extend the base package.

Pros: Allows developers to customize virtually all parts of the package, including adding new controls, navigation schemes and customizing security authorization.

Cons: Requires Silverlight programming experience.

Digital Dashboard Offers Dev HooksDundas Dashboard is a turnkey solution for creating customizable dashboards in Silverlight. For developers, the API is most interesting.

Page 13: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Untitled-1 1 7/14/10 10:08 AM

Page 14: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

12 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

Liv

eLIN

Q

BY PETER VOGELComponentOne LLC claims that its LiveLINQ product will speed up queries by orders of magnitude—and, based on my testing, that’s true. The tool works equally well in C# and Visual Basic, though all the provided sample code is in C#.

What the LiveLINQ libraries provide are some new extension methods for LINQ queries, chiefly the AsIndexed method, as used in this example:

var res = from o in nw.Order_Details.

AsIndexed()

where o.Discount.Indexed()

== .05

select o;

Assuming that the collection has more than a few objects in it, the first time you run this query, you’ll get your results back in about half the time as you would without LiveLINQ. Subsequent queries against the Discount method will run in one-tenth the time. Really.

LiveLINQ won’t work with every collection that LINQ will work with. You can’t use the LiveLINQ extensions on a List, for instance. However, LiveLINQ will work

with DataSets and their related objects, the LINQ to XML collections, BindingList (or anything that implements the IBindingList interface), ObservableCollection and others.

LiveLINQ also provides a new collection called IndexedCollection that provides a database-type View. For instance, you can run a LINQ query against an Indexed Collection and bind the result to some Data View. If you later add items to the collection that meet the criteria for the query, the DataView will automatically display the new entries.

Other CaveatsComponentOne says on its Web site that LiveLINQ works with the Entity Framework, but that’s all it says. You should be aware, for instance, that a LiveLINQ View isn’t live relative to data in the database, just to in-memory changes. LiveLINQ doesn’t follow typical component pricing: It costs $1,000 per developer without the Platinum Support package (discounts are available). This is $200 more than the entire ComponentOne ASP.NET AJAX

component package. But, if you need to solve response-time problems with large object collections, or hope to improve scalability by using caching, LiveLINQ looks like an outstanding solution. VSM

Peter Vogel ([email protected]) is the tools editor for VSM and a principal in PH&V Inform- ation Services, specializing in ASP.NET development.

VSToolbox

Search Collections with ComponentOne LiveLINQLiveLINQ speeds up LINQ queries against in-memory collections by an order of magnitude—but before you buy it, make sure you have the problems it solves.

LiveLINQ

ComponentOne LLC

Web: componentone.com

Phone: 800-858-2739

Price: $1,000 (single developer without Platinum Support)

Quick Facts: Extensions to LINQ that speed up queries through indexing and providing database-like views.

Pros: Makes LINQ queries against collections such as DataSets run an order of magnitude faster.

Cons: Doesn’t work with all Microsoft .NET Framework collections; pricing is a little steep.

LiveLINQ comes with an extensive set of examples, including several that demonstrate how to work with DataSets (though not with the Entity Framework).

Documentation ToolsNo one likes creating documentation, but the tools to help you do it keep on coming. EC Software GmbH has just released a new version of its Help & Manual product that lets you create a help system and a user manual from a single source.

The venerable Doc-To-Help (around since the early ’90s) from ComponentOne also allows you to create multiple types of documenta-tion, and the latest version continues to add new features. Doc-To-Help now integrates with SharePoint to simplify content management and version control.

Adobe RoboHelp has been around almost as long as Doc-To-Help and is now in version 8. RoboHelp includes a RoboHelp server with an analytics component that allows you to analyze which parts of your help system are actually being used. —P.V.

ToolTracker

</DevInsight>

Page 15: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

0810vsm_GrapeCity_Insert.indd 1 7/14/10 12:14 PM

Page 16: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

0810vsm_GrapeCity_Insert.indd 2 7/14/10 12:15 PM

Page 17: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 13

Dis

cret

ion

ary

Dev

elop

men

t

Have you ever wondered why the Microsoft Base Class Library (BCL) lacks an IEnumerable<T>.ForEach(…) method? Obviously, Microsoft must be careful when extending any API.

The decision to add a method like IEnumerable<T>.ForEach(…) comes down to five things: demand, precedent, advantages, consistency and cost-effectiveness. Let’s take a look at each.

The first question is, is there explicit customer demand for a new feature? In the case of IEnumerable<T>.ForEach(…), the answer is yes. The Microsoft Connect bug and feature inquiry site shows plenty of requests for this method, and Microsoft has begun investigating the value.

Another factor is precedent. Does the method exist elsewhere and have proven value? There’s already a static implementa-tion of ForEach() on System.Collections. Array and an instance method on System.Coll e ctions.Generic.List<T>. And ForEach() is in the Parallel LINQ (PLINQ) API.

Things get murky when you start talking about explicit advantages. IEnumer able<T>.ForEach(…) offers minimal advantage over a foreach statement. Compare the two examples here; one with foreach and one with IEnumerable<T>.For Each(…), where items is an IEnumerable<string>:

items.ForEach(item=> {Console.WriteLine(item);});

foreach (string item in items)

{ Console.Write(item); }

Yes, if you use a lambda expression (items.ForEach(Console.WriteLine)) rather than a lambda statement, the syntax is more succinct, and still readable. But for a statement block with multiple statements, it’s likely that most developers would prefer the foreach statement.

The next issue is consistency, and here the outlook is less clear. Typically, the exception methods provided by System.Linq.Enumerable return a collection of objects—generally IEnumerable<T>. This is critical because it enables deferred execution, delaying query execution until an explicit call for a result is needed. In the following example, none of the lambda expressions is evaluated until the call to Count(): items = items.Where( item => item == item.ToString());

items = items.Where(

item => item.Length > 0);

items = items.OrderBy(item=>item);

IEnumerable<char> firstLetters =

items.Select(item => item[0]);

int count =

firstLetters.Distinct().Count();

Until the call to Count(), the criteria expressed by each lambda expression is combined together into one big query, rather than executed (or evaluated) piecemeal.

Although having IEnumerable<T>.ForEach(…) return an IEnumerable<T> collection would be consistent with the earlier, well-established pattern, it would also likely lead to runtime coding errors because statements like items.ForEach(Console.WriteLine) wouldn’t write anything out. Rather, the execution of the WriteLine statement would be delayed until the expression was evaluated. Unless the result of ForEach() was assigned, it would never be evaluated, making for a line of code that appeared to be exactly what was needed but, in actuality, did nothing.

In conclusion, it’s likely that consistency with other System.Linq.Enumerable methods should probably be dropped, as it was for List<T>.ForEach(). That means losing support for having a fluent API and its characteristic method chaining.

Last comes the question of cost. Imple-menting IEnumerable<T>.ForEach(…) is fairly trivial, as shown here: public static void ForEach<T>( this IEnumerable<T> collection,

Action<T> action)

{

foreach (T item in collection)

{

action(item);

}

}

However, without testing, it’s likely that the consequence of deferred execution would go unnoticed. The method is small and clear enough that many would naively assume they could write it correctly without unit testing it. And, even when returning IEnumerable<T>, they would. However, once testing was in place to demonstrate that deferred execution would yield very misleading code, it would be discovered that the design needed more thought.

Also, because the method is easy to implement, it is perhaps not as crucial to include in the BCL—a developer could implement it themselves.

IEnumerable<T>.ForEach(…) is an example of a relatively trivial API with several factors in its favor. But Microsoft must evaluate the issues very closely. We should pay similar attention to our own API design and the code we write. Will the company provide IEnumerable<T>.ForEach(…) in the Microsoft .NET Framework 5? No doubt Microsoft is considering it. VSM

Mark Michaelis started IntelliTechture and serves as chief technical architect and trainer. Since 1996, he’s been a Microsoft MVP for C#, Visual Studio Team System and the Windows SDK. In 2007, he was recognized as a Microsoft regional director.

</DevInsight>

VSInsiderDiscretionary Development at Microsoft

BY MARK MICHAELIS

Page 18: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

VSM COVER STORY

UNIT TESTING and

ASP.NET MVCASP.NET MVC and test-driven

development show the future

of delivering reliable applications.

While Visual Studio 2010 enables

you to integrate server-side testing

into ASP.NET development, client-side

testing presents a challenge.

BY PETER VOGEL

14 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

Page 19: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 15

VSM COVER STORY

ASP.NET MVC is important to all Microsoft .NET Framework developers for at least two reasons. First, it reflects the first Microsoft commitment to the Model-View-Controller (MVC) pattern for implementing applications. The MVC pattern supports loose coupling and a better separation of concerns among an application’s components, so the pattern is critical to creating complex apps.

Second, ASP.NET MVC is important because of test-driven development (TDD). Maintaining quality and reliability in software products still depends, ultimately, on inspection (testing). TDD bakes the testing process by converting requirements directly into test code. With TDD, developers build to meet the demands of the tests rather than the requirements.

In addition to these general benefits, ASP.NET MVC provides specific benefits for Web developers. The primary one is a better development platform for JavaScript client-side programming than ASP.NET.

To make all of this magic happen, the MVC pattern breaks an application up into three components. In ASP.NET MVC, the Model (the middle-tier business objects) and the Controller (which controls the Views) can be tested using the Visual Studio Unit Testing Framework. Testing the View, however, is problematic.

View IssuesThe View presents the data to the user. In the MVC pattern, the goal is to create Views so brain-dead simple that they require no testing. If a View builds successfully then any problems that remain are, at worst, “blunders” (such as spelling errors or data in the wrong place) rather than complicated logic errors. Errors in the View are assumed to be trivial—easily spotted and easily fixed.

The problem in Web applications is that the HTML page displayed in the client is the View. But one of the primary benefits provided by ASP.NET MVC is that it provides a platform for client-side pro-gramming. Instead of becoming simpler, thanks to JavaScript and jQuery, the HTML View is becoming increasingly more sophisticated. Taking a comprehensive look at unit testing in ASP.NET MVC requires looking at two currently separate issues: server-side testing (Model and Controller) and client-side testing (View).

Testing ControllersBeause testing middle-tier business objects—the Model—is the same in ASP.NET MVC as in any other application, we’ll ignore it for this article. While there are special objects for testing Controllers, Controllers can be tested using the standard TDD code and following the standard paradigm.

The first step in testing Controllers is to create a typesafe View: a View that’s passed a custom class from the Controller and returns a customer class to the Controller. These objects—effectively, Data Transfer Objects (DTOs)—are property-rich classes that must be added to the site’s Models folder. A typical DTO looks like this:

Namespace Models

Public Class CustomerData

Public Property ContactName As String

End Class

End Namespace

Once the DTO is defined, you create the method in a Controller that will cause the View to be sent to the browser. The simplest possible controller class that uses the CustomerData DTO just defined would look like this:

Namespace Sample_MVC

Public Class CustomerController

Inherits System.Web.Mvc.Controller

Public Function ManageCustomerData(

CustIn As Models.CustomerData) As ActionResult

Return View(Nothing)

End Function

End Class

End Namespace

The final step is to create the associated View by right-clicking on the Controller method and selecting Add View. In the resulting dialog, pick the DTO class to generate a View bound to the DTO. The resulting View is tied to DTO through its Page directive:

<%@ Page Language="VB"

Inherits="System.Web.Mvc.ViewPage(

Of Sample_MVC.Models.CustomerData)" %>

Once the View is created you can use the ASP.NET MVC HTML Helpers to generate the tags and code that make up the View. The goal here is to create a page that passes a DTO back to the Controller method called when the page posts back. To simplify this example, this code returns the same CustomerData object passed to the View when it’s selected:

Figure 1. Unit tests that exercise the Actions in Controllers can be run individually or as a batch, with the results consolidated into a single report.

Page 20: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

16 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

Unit Testing and ASP.NET MVC

<% using (Html.BeginForm()) {%>

<fieldset>

<legend>Edit Customer</legend>

<%: Html.EditorFor(model => model.CustomerData,

new { ContactName = model.CustomerData}) %>

<p>

<input type="submit" value="Save" />

</p>

</fieldset>

With that in the View, the Controller method—now accepting a CustomerData object—would look like this:

Public Function ManageCustomerData(

CustIn As Models.CustomerData) As ActionResult

Return View(Nothing)

End Function

The Controller class is, in many ways, a class like any other class. For instance, in TDD, the first test for any class is always to see if the class can be instantiated:

<TestMethod()> _

Public Sub CreateCustomerController()

Dim cdc As CustomerController =

New CustomerController

Assert.IsNotNull(cdc,"Unable to create controller")

End Sub

The second test in the TDD paradigm is to determine if the class’ first method can be called and if it will accept parameters. No Assert is required for this test: If the test runs to completion, it’s a success, and if the code blows up … well, that’s not a good sign:

<TestMethod()> _

Public Sub CallGetCustomerData()

Dim cdc As CustomerController =

New CustomerController

Dim cd As New Models.CustomerData With

{.ContactName = "Peter Vogel"}

cdc.GetCustomerData(cd)

End Sub

The third test is to determine if a result can be returned from a minimal implementation of the Controller method. The minimal implementation for this Controller method would be to return the CustomerData object passed to the method, as this code does:

Public Function GetCustomerData(

ByVal CustIn As Models.CustomerData) As ActionResult

Return View(CustIn)

End Function

A Controller method always returns a result of type ActionResult, so the third test looks like this:

<TestMethod()> _

Public Sub ReturnGetCustomerData ()

Dim cdc As CustomerController =

New CustomerController

Dim cd As New Models.CustomerData With

{.ContactName = "Peter Vogel"}

Assert.IsNotNull(cdc,"Unable to get result ")

End Sub

The fourth test is to see if the result returned from the method contains the cor-rect values. This is the point at which testing a Controller requires some special consid-eration. While the Controller method returns an ActionResult object, the test needs to access the DTO that will, eventually, be passed to the View. To access the DTO, first check to see if the return result can be converted to a ViewResult. If it can, then extract the DTO and check to see if the DTO has the expected data in its properties: <TestMethod()> _

Public Sub CheckReturnGetCustomerData()

Dim cdc As CustomerController =

New CustomerController

Dim cd As New Models.CustomerData With

{.ContactName = "Peter Vogel"}

Dim ar As ActionResult

ar = cdc.GetCustomerData(cd)

Assert.IsInstanceOfType(

ar, GetType(ViewResult))

Dim vr As ViewResult = CType(

ar, ViewResult)

In the MVC pattern, the goal is to create Views so brain-dead simple

that they require no testing.

COVER STORY

Figure 2. A QUnit test runner page. A test runner page isn’t subtle when an error is found: The failed test is displayed with its message and the test is highlighted in red.

Page 21: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Untitled-1 1 9/15/10 12:08 PM

Page 22: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

18 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

cd = CType(vr.ViewData.Model, Models.CustomerData)

Assert.AreEqual("Peter Vogel", cd.ContactName)

End Sub

The next set of tests would support testing the functionality coded into the Controller by providing different inputs to the Controller. As this progression shows, even one of the components that’s special to ASP.NET MVC—the Controller—is compatible with the TDD process. Even ASP.NET MVC routing can be tested using the Visual Studio Unit Testing Framework.

Unit Testing in the ClientYou can do TDD with client-side code, but it’s a different world from the server-side experience. To begin with, there’s no testing framework baked into Visual Studio and, instead, you’ll have to choose from several different competing JavaScript-based tools. The closest that any of these packages comes to being the “approved” framework is QUnit, which is used by the jQuery team.

JavaScript functions can be divided into two groups. First, there are the business/processing functions. These include AJAX calls to the server to retrieve data from the server or send data to the server

for processing. Integrating AJAX calls is even easier in the upcoming ASP.NET MVC 3 (see “Looking to ASP.NET MVC 3,” this page).

Then there’s the UI code that interacts with the View by retrieving data for the business functions, updating the View with retrieved data or just modifying the View based on the user’s input. These changes can include modifying either the View’s structure or its appearance.

It’s easy to intermix this client-side code: A single function might include the code to retrieve data from the View (UI logic), send that data to a service on the client (business logic), and update the View (UI logic again) to report success or failure. Testing, therefore, not only means understanding the testing framework—it helps structure your code to enable you to test as much of your code as possible. The first step, for instance, is to move as much of your JavaScript code as possible out of your View and into .JS files.

Setting up and Executing Client-Side TestingTo implement QUnit testing, create a Web site with subfolders for Scripts, Stylesheets and Tests. To the Scripts and Stylesheets folder add the two components that make up QUnit: qunit.js and qunit.css (you can get these files and read about QUnit at docs.jquery.com/qunit). In my Tests subfolder, I’ll place the JavaScript files with the code that will check my View’s JavaScript code.

To check my JavaScript code I use the QUnit test function, which accepts two parameters: A name for the test and a function that executes my tests. The test function calls my View’s JavaScript functions and then uses a QUnit assertion to check the result. This example calls a getCustomerData function and then uses the QUnit equals assertion to see if the correct customer was retrieved:

test('getCustomerData',

function () {

getCustomerData("ALFKI");

equals(custData.Name, "ALFKI",

'Customer data retrieved');}

)

With a test written, add an HTML test runner page to your test Web site. The test runner page needs to reference the QUnit stylesheet and include several heading/div tags that QUnit will update to display test results. It must also reference the qunit.js file, the file with the test code (Tests.js in this case) and the JavaScript file containing the View func-tions to test (UI.js for this example). Here’s a typical test runner page:

<!DOCTYPE html>

<html>

<head>

<title>UI Tests</title>

<link rel="stylesheet"

href="../ViewTests/StyleSheets/qunit.css"

type="text/css" media="screen"/>

<script type="text/javascript"

src="../ViewTests/Scripts/qunit.js"></script>

<script type="text/javascript"

src="../ViewTests/Tests/Tests.js"></script>

<script type="text/javascript"

src="http://MySite/Scripts/Project/UI.js"></script>

</head>

<body>

ASP.NET MVC makes TDD easier to do on the server. However, while

client-side testing is possible, it’s not as convenient or as easy.

Looking to ASP.NET MVC 3ASP.NET MVC 3 is currently in beta, and many of the enhancements are aimed at making developers more productive when creating Views. With ASP.NET MVC 3, developers get more flexibility in what engine will be used to convert a View into HTML. There are several engines available for generating templates in HTML—including Django and Nhaml—any of which can be used with ASP.NET MVC 3.

The goal of all of these engines is to reduce the amount of typing required to create a UI, while generating sophisticated HTML. One of the side effects of the “less typing” goal is a clearer View file: less code but more HTML. Microsoft has its own entry in this arena with Razor, which directly addresses test-driven development (TDD). One of the Razor goals is to enable unit testing of a Razor View without having to display the page in a browser.

Controllers also gain a ViewModel property that can be used to pass data to the View in a typesafe way, but with late binding. Unlike the ViewData (which uses a collection of named values) or a Model object (which is typesafe but must be defined in advance), a ViewModel is dynamic. You can add new properties to the ViewModel simply by typing the name of the property and setting it to a value.

As Views get “smarter,” support for JavaScript in ASP.NET MVC is also being enhanced. You can, for instance, add a method to your controller that can be invoked from JavaScript as a Web service using jQuery. The method will automatically decode the JSON objects passed by the jQuery request and bind it to server-side Microsoft .NET Framework object types.

Microsoft is also committing to improving its support for “Unobtrusive JavaScript,” which includes a cleaner separation between JavaScript libraries and Views. As it becomes easier to separate JavaScript from HTML, it becomes easier to test JavaScript code independently. —P.V.

Unit Testing and ASP.NET MVCCOVER STORY

Page 23: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Untitled-1 1 9/15/10 12:10 PM

Page 24: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

20 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

Unit Testing and ASP.NET MVC

<h1 id="qunit-header">UI Tests</h1>

<h2 id="qunit-banner"></h2>

<div id="qunit-testrunner-toolbar"></div>

<h2 id="qunit-userAgent"></h2>

<ol id="qunit-tests"></ol>

</body>

</html>

To run the tests, just display the test runner page. QUnit takes care of executing all the tests in any script libraries and updating the test runner page with the results (see Figure 2, p. 16). This test, however, won’t work because the getCustomerData function calls a Web service asynchronously. A test written like this will run the assertion before any data is returned from the Web Service.

Fortunately, asynchronous testing is supported in QUnit. To test asynchronously, use the QUnit stop function to pause your test func-tion. Then call your assertions from the QUnit setTimeout function that will restart your tests. The second parameter to the setTimeout function specifies how long you’ll wait before running your assertion.

This example of an asynchronous test waits one second before checking the results of GetCustomerData:

test('getCustomerData',

function() {

getCustomerData("ALFKI");

stop();

setTimeout(function (){

equals(custData.Name, "ALFKI",

'Customer data retrieved');

start();},

1000)

}

)

Refactoring for TestingWhile there’s more to QUnit than I’ve covered here, the product’s capabilities aren’t the real issue: Structuring your code to support testing is. For instance, while the test proves that the function can retrieve the data for a specified customer name, it doesn’t prove that the code will interact successfully with the View. These interactions would include using jQuery selectors to pull the customer name from the View and to update the View with the results retrieved from the Web service.

To support TDD, the code that uses jQuery selectors to find elements in the View must be factored into functions separate from both the business and UI logic. Those “selector functions” are called by the functions with the business and UI logic—which can now be tested independently of the View. The jQuery selector functions may be difficult to test but will, hopefully, be so simple that testing isn’t required. For instance, code that would bind a call to the getCustomer Data function to a View element might look like this:

$("#customerList").bind("click",

function (e) {

getCustomerData(

this.value, customerRetrieved, genericFailure);

}

);

The customerRetrieved function called here would update the View with the data returned from the Web service. The customer-Retrieved function should be structured so that it first calls a “selector function” that finds the element in the View that is to be updated and returns it to customerRetrieved. After customerRetrieved updates the retrieved element, the function would pass it to a second

function that finds the appropriate part of the View and inserts the results. The customerRetrieved function would look like this:

function customerRetrieved(button) {

var divElm = getDataTable();

…update divElm…

updateDataTable(divElm);

}

During testing, the selector function that finds the element would be replaced with a stub that returns a dummy element, as this code does:

function getDataTabel() {

return $("<div>");

}

In the “real” View, updateDataTable would find the appropriate element in the View, delete all of its contents and insert the version created in customerRetrieved. For testing, the updateDataTable stub that accepts the updated element would contain the assertions which check that the element was modified correctly.

To support testing, three JavaScript files are required: one to hold the View’s functions, one to hold the selector functions used in the real View, and a file to hold the stub functions used in testing (this file would be part of the test Web site). The production View would use the first two files, while the test runner would use the first and third.

A New ParadigmASP.NET MVC makes TDD easier to do on the server. However, while client-side testing is possible, it’s not as convenient or as easy. Part of the issue is built into the environment: For security reasons, to test calls to a Web service, the test code may have to be part of the production site rather than being in a separate site. While this article has only discussed loading the test runner page into a single browser, for Internet (rather than intranet) applications, the View tests would need be executed in several browsers and the results consolidated into a single report.

Frameworks do exist for this, but are not yet part of Visual Studio. The good news here is that ASP.NET MVC 3 and Razor are intended to facilitate testing outside of a Web page. Looking at the issues involved from the point of view of a server-side developer, client-side testing still remains the next frontier for the Visual Studio Unit Testing Framework.

What’s needed isn’t new technology so much as a reassessment that no longer thinks of “everything in the Web pages” as a View but, instead, thinks of it as a client with its own implementation of the MVC pattern.

In this paradigm, the browser has a relatively simple Model that grabs DTO when the View is selected on the server and from Web services on the client. There would also be a JavaScript Controller that would be called from the View as the user interacts with the View. The Controller would make all changes and would call simple functions to integrate those changes into the View. The refactorings required for testing purposes are the start of that paradigm.

After all, if MVC makes sense on the server, then it also makes sense to use it for the increasingly more sophisticated clients that users—and employers—expect. VSM

Peter Vogel ([email protected]) is the tools editor for VSM and a principal in PH&V Information Services, specializing in ASP.NET development.

GO ONLINE

Go to VisualStudioMagazine.com/MVC1010 to read more about leveraging the Visual Studio Unit Testing Framework.

COVER STORY

Page 25: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Untitled-1 1 9/15/10 12:07 PM

Page 26: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

FEATURE

Microsoft Visual Studio Scrum 1.0 is a new Team Foundation Server (TFS) process template for teams prac-ticing Scrum. Scrum has become a dominant methodology in the software industry in recent years, and teams are in search of tooling to help support their processes and practices. In this article, we’ll take a brief look at what it looks like to run a Scrum project using the Microsoft Visual Studio Scrum 1.0 process template on TFS 2010.

Getting StartedAs your team gets started, the first thing to do is make a decision about the length of your Sprints. Sprints are time-boxed iterations of work in which your team produces a potentially shippable incre-ment of the product being developed. Your team can decide the appropriate length for you, but most teams choose a length of time between a week and 30 days. The actual length is less important (every team has to find the sprint cadence that works for them), but what is important is that items pulled from the Product Backlog can be delivered within the sprint boundaries.

Once your iteration length has been chosen, you can enter the dates into the Sprint work items in your project. After creating a new project with the Microsoft Visual Studio Scrum 1.0 template, your project is pre-populated with 24 sprints (six sprints across four releases). This can easily be modified—

you may have 10 sprints in your first release, for instance—but for the purposes of this article we’ll use the default sprints as our example.

In Visual Studio, open up Team Explorer and navigate to the All Sprints query. Each Sprint work item returned in this query is mapped directly to an iteration value in TFS. Open the first few sprint work items and enter the dates for your first few sprints. It’s not important to enter all the sprint dates at this time, but it’s good to add what you know so that your team and Product Owner can begin to get a feel for the product schedule.

Building Your Product BacklogYou likely already have a list of requirements for your project. The next step is to turn these into a list

of Product Backlog Item (PBI) work items in your Product Backlog. The Product Backlog is a priori-tized list of requirements for your project. Each item on the Product Backlog is represented as a work item called a PBI.

To create a new PBI, click the New Work Item drop-down list from the toolbar and select Product Backlog Item. Your Product Owner will fill out the work item form in detail, including the Title, Backlog Priority, Description and Business Value. These fields are the core of the work item as they describe the item, its relative priority compared to other work on the backlog, and a value that represents the amount of business value it will provide once imple-mented. After saving the new work item, it will be displayed in the results of the Product Backlog query. The Product Backlog query is defined as all PBIs and Bugs assigned to the root iteration path of your project that haven’t been completed.

22 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

Working with the Microsoft Visual Studio Scrum 1.0 process template.

BY AARON BJORK

Page 27: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Untitled-1 1 9/15/10 12:10 PM

Page 28: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

24 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

Each PBI moves through a series of state transi-tions that track the lifecycle of requirement: New, Approved, Committed and Done.New: This state is the starting point for all items on the Product Backlog. As new PBIs are entered by your Product Owner they start in the New state and are assigned a default Backlog Priority of 1,000. This is done to ensure that new PBIs are pushed to the bottom of your Product Backlog.Approved: Your Product Owner moves a PBI to the Approved state when the PBI has been suffi-ciently detailed and is ready to be brought to the team to be estimated. Most of the time, items near the top of the Product Backlog are in the Approved state, while items toward the middle and bottom are in the New state.Committed: When the team commits to imple-menting a PBI during the Sprint Planning Meeting, the state of the PBI is changed to Committed. This state transition indicates that the team will complete the PBI in a sprint.Done: Finally, a PBI is moved to the Done state when the team has completed all the Tasks asso-ciated and the Product Owner has agreed that the PBI has been implemented according to the Acceptance Criteria.

When your Product Owner adds new items to the Product Backlog, it’s critical that each item be prioritized appropriately. As the team begins to tackle work sprint by sprint, they work through the items on the Product Backlog in priority order. So, what determines the priority of an item on the backlog? The answer to that question is unique to each situation, but some general rules and guidelines can help a Product Owner make good decisions about priority.

The goal for each sprint is to deliver value to the customer. This goal is grounded in the notion that delivering value early and often will help drive better decision making later in the project cycle. With that in mind, it’s important for the Product Owner to consider which items on the Product Backlog will deliver the most value to the customer as compared to the amount of effort required to complete the items. Both the PBI and Bug work item forms have a Business Value field to track this value. Your Product Owner should use this value and the effort field to make good decisions about the relative priority of the work on the Product Backlog.

Acceptance CriteriaAs a Product Owner, one of the most important things you can do with each of your PBIs is to detail the Acceptance Criteria for each item. What is Acceptance Criteria? Put simply, it’s the criteria that defines what “Done” means for each PBI. Acceptance Criteria is critical to the success of a Scrum team, as it becomes the handshake between the Product Owner and the team—it helps define what the team is committing to.

Some of the best interactions on the team happen as the Product Owner and the team review the Acceptance Criteria for each item on the backlog. What emerges is a shared under-standing of what “Done” means for each item.

“Done” in the Agile world means that something is ready to be shipped to customers. There’s no outstanding work, including testing, documentation, setup and so on. Remember that the goal with every sprint is to produce a “potentially shippable increment of work.” In order for something to be shippable, all the work needs to be “Done.” There are many good formats for writing Acceptance Criteria, but in the end, each criteria should be simple to read and understandable by everyone involved.

Planning Your First SprintAfter your Product Owner has created and prioritized the Product Backlog, your team is ready to get started on its first sprint. The team gathers for the Sprint Planning Meeting, where the team agrees on a

Figure 1. A look at the Product Backlog query.

Figure 2. Well-defined Acceptance Criteria is vital to a successful process.

FEATURE Scrum for Everyone

Page 29: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Untitled-1 1 9/15/10 12:09 PM

Page 30: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

26 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

FEATURE Scrum for Everyone

goal for the sprint. The goal for the sprint is captured in the Goal field on the sprint work item. The Product Owner then begins to describe the highest-priority PBIs and Bugs on the Product Backlog by reading to the team each item along with its associated Accep-tance Criteria. During this part of the meeting, the team is learning about each item on the backlog and gaining an understanding of what it’s being asked to build.

After the team has had adequate discussion about the items being considered, it’s time to estimate each item. A common practice for Agile teams today is to use an estimation technique like Planning Poker. During Planning Poker each team member has a deck of cards with values representing the amount of effort needed to complete a backlog item. Most Planning Poker cards use the Fibonacci sequence (1, 2, 3, 5, 8, 13 and so on), as it reflects that the team doesn’t expect perfect estimates. For example, what’s the difference between an estimate of 11 versus 12 when discussing something on the backlog? In truth, there isn’t much difference, because estimating at that level of detail is inherently flawed. However, it’s easier to compare the differences between an estimate of 8 versus 13, or even 5 versus 13.

By limiting the available choices, the team can have more pro-ductive discussions about the work involved. After each member of the team reveals their estimate—simultaneously—the team mem-bers that have high or low estimates are given a chance to explain why they chose their values. Again, the goal of the exercise is not to arrive at a precise estimate; rather, it’s to spark conversations that lead to a shared understanding of what “Done” means for each item being discussed. The team can vote again after discussion and will eventually arri ve at a consensus estimate. That value is entered into the Effort field of the PBI or Bug work item being estimated.

This process repeats for each of the items presented by the Product Owner until the team believes they have enough work to achieve the sprint goal. The next step is for the team to break down each item into Task work items. Tasks represent the actual work that the team will perform and should encompass all the work involved including testing, docu-mentation, interface design and so on.

Remember, an item isn’t “Done” until every-thing is done. For this reason it’s important that the team collaborate through this part of the meeting to record all the necessary work. Each task work item is then estimated by the team. As the team details the tasks for each item, it may find that an item is bigger than originally thought. In this case, the team negotiates with the Product Owner to move the item back to the Product Backlog.

To add a Task to a PBI or Bug, switch to the Tasks tab on the work item itself and click the New Linked Work Item icon. Tasks are added as children of their parent PBI or

Bug and begin in the To Do state. They can be tracked on the Tasks tab of both PBIs and Bugs.

After all the Tasks have been created, the final step is for the team to make a commitment to the work. This is done by setting each PBI or Bug work item to the Committed state, indicating that the team is committing to complete the item during the upcoming sprint.

The result of the Sprint Planning Meeting is: 1. An agreement between the Product Owner and the team on

what items from the Product Backlog are to be accomplished during the sprint.

2. A list of all the Tasks necessary to complete the items selected by the Product Owner and the team.

The ultimate success of the sprint will be determined at the end of the sprint during the Sprint Review Meeting.

Tracking Your First SprintNow that the sprint is planned, the team is ready to get started on the work. It’s important that the team doesn’t start work on too many back-log items at once. Ideally, the team works together on a backlog item until all the Tasks are completed before moving on to the next item. This helps minimize the risk of reaching the end of the sprint with everything 90 percent completed but nothing actually being “Done.”

Members of the team begin by selecting the Tasks that they’ll work on first. This is accomplished by changing the Assigned To field on a Task work item and setting the State field to In Progress. Team members record daily the number of remaining hours left for each Task they’re working on by updating the Remaining Work

Ideally, the team works together on a backlog item until all the Tasks

are completed before moving on to the next item.

Figure 3. The Burndown chart offers a glance at sprint progress.

Page 31: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Untitled-1 1 9/15/10 12:09 PM

Page 32: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

28 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

field. Ideally, each team member only has one In Progress task at a time, so as to mini-mize the risk of work being left unfinished or partially completed. As team members complete Tasks, the state of each Task is changed from In Progress to Done, and progress is reported at the daily standup.

During the sprint, the team tracks prog-ress toward completing all the work using the Sprint Burndown chart. The chart clearly indicates the team’s progress toward burning down the hours committed to the sprint, as well as tracking the amount of work the team has In Progress. In the example pro-vided in Figure 3 (p. 26), you can see the team has 20 hours of work to complete before the last day of this sprint. The Sprint Burndown can be displayed during the daily standup so that each team member under-stands how the team is progressing toward meeting its commitment.

Additionally, the team can use the Unfin-ished Work query to track all the remaining work in the sprint. The results from this query exclude completed work, making it a powerful tool to track and monitor remaining work.

Sprint Review and RetrospectiveAt the end of the sprint, the team holds a Sprint Review meeting to show what they accomplished during the sprint. A demo is held and stakeholders beyond the Product Owner are invited to participate. Sprint Review meetings should be informal and should feel like a natural end to the sprint.

The final step is for the team to hold a Sprint Retrospective, where they meet to discuss what worked during the sprint and what they want to improve in the next sprint. The retrospective is an opportunity for the team to improve, to take a hard look at places they might have stumbled, and to have an honest conversation about what they can do differently to improve in the next sprint.

Remember that one of the four value statements from the Agile Manifesto is “Responding to change over following a plan.” The team made a plan for the sprint when they started, but it’s impor-tant to look back at that plan and understand how to improve going forward. The plan at this point is irrelevant. What’s important is how the team responds and improves going forward. The data from the retrospective is recorded on the Retrospective tab of the sprint work item.

Using VelocityAfter the team has completed its first few sprints, it will start to better understand its velocity. What is velocity? Quite simply, it’s the amount of effort the team completed in the last sprint. This is often referred to as yesterday’s weather and can be used when planning for future sprints. If the team completed 15 units of effort in the last sprint, it’s natural for the team to commit to a similar amount of

effort in the next sprint. Obviously this is not an exact science, but it’s a useful metric when the team is planning a sprint or trying to understand when it will be ready to release the product.

Microsoft Visual Studio Scrum 1.0 doesn’t prescribe a unit of effort on PBI and Bug work items (story points, ideal days, days and so on). The reason is that the unit itself is irrelevant. What is important is how the actual number is used during planning. Whether your team decides on story points, ideal days or some other metric, be sure that you stay consistent and learn to use velocity to help the team plan both sprints and releases.

The Microsoft Visual Studio Scrum 1.0 process template includes a velocity report that shows the amount of effort the team has com-pleted in each sprint. The parameters on the report allow you to choose which sprints to include as well as filters on area path, which are helpful when looking at the velocity of different teams.

There’s obviously more that goes into running a Scrum project, but hopefully this article has provided you with some insight into how the Microsoft Visual Studio Scrum 1.0 process template and TFS 2010 support the Scrum process. For more information on the Microsoft Visual Studio Scrum 1.0 template, see the process guid-ance on MSDN at tinyurl.com/342t9fk. VSM

Aaron Bjork is a senior program manager at Microsoft working on Agile experiences and tooling within Team Foundation Server (TFS). Prior to joining TFS in 2008, Bjork worked as a software engineer and development lead in Visual Studio. He is passionate about Application Lifecycle Management solutions and has a strong desire to see teams improve their software engineering practices. Follow Bjork on his blog at blogs.msdn.com/aaronbjork.

What is velocity? Quite simply, it’s the amount of eff ort the team

completed in the last sprint.

Figure 4. The Velocity report shows the amount of effort completed in each sprint.

FEATURE Scrum for Everyone

Page 33: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Copyright 1996-2010 Infragistics, Inc. All rights reserved. Infragistics and the Infragistics logo and NetAdvantage are registered trademarks of Infragistics, Inc.

At Infragistics, we make sure our NetAdvantage for .NETcontrols make every part of your User Interface the verybest it can be. That’s why we’ve tested and re-tested tomake sure our Data Grids are the very fastest grids onthe market and our Data Charts outperform any you’veever experienced. Use our controls and not only will youget the fastest load times, but your apps will always lookgood too. Fast and good-looking…that’s a killer app. Trythem for yourself at infragistics.com/wow.

Infragistics Sales 800 231 8588 Infragistics Europe Sales +44 (0) 800 298 9055 Infragistics India +91-80-6785-1111twitter.com/infragistics

Fast Data Chart

WPF Grid

Silverlight Grid

ASP.NET Grid

Untitled-12 1 4/9/10 1:54 PM

Page 34: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

30 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

Th

e F

irst

D

ecad

e of

C#

</Language Lab>YO U R CO D E S O U RC E

IN THIS SECTION: C# Corner · 30 ///////////////////////////////////////

{ C # C O R N E R }

The Good, Bad and Ugly of C#A look back at the fi rst decade of C#. BY PATRICK STEELE

It’s almost 2011. The Microsoft .NET Framework and C# have been publicly available for almost 10 years—longer if you count the early betas. In this article, I’ll look at some of the things I love about C#, some things I could do without and those things that really should be avoided!

With apologies to Sergio Leone, I’m going to approach this in reverse order. First the ugly, then the bad—and I’ll conclude with the good.

The UglyHere are some really nasty things you can do in C#; they should be avoided if at all possible.

lock(this): If you’ve got a public class, using lock(this) is an invitation for a deadlock. Locking the current object instance seems like the easy thing to do to get thread safety, but what if other code in your class further down the stack also does lock(this)? Maybe this will only happen in a few places, but once you get your first report of a deadlock, you’ve got to find every lock(this) in the class and investigate call hierarchies to see where the deadlock might be occurring.

Or, what if you’ve got lock(this) inside your class, and one of the consumers in your class does a lock(the_instance_variable) before calling one of your methods? The consumer will have locked you out of your own code! Locking should always be done on a private object specifically used for locking.

Finalizers: I debated putting finalizers under the “bad” section instead of ugly, but I really think they should be avoided. Use the Dispose pattern instead.

What’s wrong with finalizers? First off, they’re non-deterministic. You never know when the Garbage Collector (GC) will call them. In fact, calling finalizers isn’t even guaranteed by the Microsoft .NET Framework. Second, finalizers put added pressure on the GC—objects that define a finalizer are processed in a separate queue and therefore stay around longer.

If you absolutely feel you must use a finalizer to make sure some unmanaged resource is released—which, as I just noted, you really can’t ensure—you should implement the IDisposable interface. In your Dispose method, release your unmanaged resources and call GC.SuppressFinalize(this) to make sure your object never gets to the finalization queue.

Finally (if you’ll pardon the pun), remove any finalizer as soon as they’re deemed unnecessary. As long as a finalizer exists in your class—even if it’s empty—you’ll still pay the GC cost of a “finalizable” object.

catch(Exception): The try/catch/finally construct is a great tool for handling issues that may arise in certain areas of code. One all-too-common abuse of the try/catch block is catching every possible exception type. Catch blocks are only meant to catch exceptions you can handle.

As an example, let’s say your code is polling a document via an HTTP-based URL, someserver.net/SomeResource. You start getting errors because the site is used heavily and sometimes generates a 500. Because this isn’t a super-critical error (your application can just wait for the next polling interval and try again), you wrap it in a try/catch block:

try

{

// Perform an HTTP GET on some url

}

catch (Exception e)

{

// Probably a 500. Ignore it and continue

}

By catching Exception, you’re catching every possible exception the Microsoft .NET Framework could throw. Suppose the provider of the resource changes the URL and doesn’t provide a redirect. Now your requests start returning a 404. With the catch block I just showed, your code would ignore it. Or maybe there’s a bug somewhere else in your app that isn’t disposing of TCP/IP connections properly and you’re running out of connections, thus generating a different type of exception. All of these will be ignored because your code catches the general Exception class.

Always catch the most specific exception possible. In the previous scenario, if you decided that a 500 wasn’t a reason to abort the call, you should look for that condition only:

try

{

// Perform an HTTP GET on some url

}

catch (WebException e)

{

var response = (HttpWebResponse)e.Response;

if( response.StatusCode ==

HttpStatusCode.InternalServerError)

{

// We'll try again on the next poll

}

else

{

// Handle the issue!

}

}

Page 35: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

You’ve got the data, but time, budget and staffconstraints can make it hard to present that valuableinformation in a way that will impress. With Infragistics’NetAdvantage for Silverlight Data Visualization andNetAdvantage for WPF Data Visualization, you cancreate Web-based data visualizations and dashboard-driven applications on Microsoft Silverlight and WPFthat will not only impress decision makers, it actuallyempowers them. Go to infragistics.com/sldv today andget inspired to create killer apps.

Infragistics Sales 800 231 8588 Infragistics Europe Sales +44 (0) 800 298 9055 Infragistics India +91-80-6785-1111twitter.com/infragistics Copyright 1996-2010 Infragistics, Inc. All rights reserved. Infragistics and the Infragistics logo and NetAdvantage are registered trademarks of Infragistics, Inc.

GeospatialMaps

SilverlightPivotGrids

FastDataCharts

Untitled-1 1 8/3/10 10:41 AM

Page 36: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

{ C # C O R N E R }

This clearly indicates that you expect possible HTTP 500 errors and want to ignore them. Likewise, if you think the URL might change without reason, you could capture the 404 status (HttpStatus-Code.NotFound) and alert the system administrator accordingly.

Catching the general Exception type says “I can handle any exception.” That’s utterly impossible to do, so coding for it is a really ugly thing to do.

The BadLet’s look at a few things that can mess up your code.

Not Rethrowing Exceptions Properly: Exceptions let you know when things didn’t go as planned. Exception handling in the .NET Framework is very robust, but you need to understand how the exception-throwing process works or you may not get all of its benefits. Everyone knows how to throw exceptions:

public void Deposit(decimal amount)

{

if( amount < 0)

{

throw new ArgumentException(

"amount to deposit can not be negative", "amount");

}

// ...

}

In this example, the stack trace would indicate the exact line where the “throw” was found as the location of the error. You’d jump right there and see that someone passed the Deposit method a negative value.

But what about catching an exception and re-throwing it for the consumer to handle? If you don’t do it the right way, you can lose important stack-trace information. Consider the following class which will (obviously) throw a DivideByZeroException:

public class RethrowProperly

{

public void DoSomething()

{

var d = 0;

var n = 15;

var result = n/d;

}

}

DoSomething is dividing and doesn’t always check the denominator for zero, so you wrap the call to DoSomething in a try/catch block:

try

{

var r = new RethrowProperly();

r.DoSomething();

}

catch (DivideByZeroException ex)

{

throw ex;

}

When this code is run and the exception is thrown, the line number in the stack trace will point right to the “throw ex” line as the source of the error. But the error actually happened back in DoSomething when executing the “n/d” calculation. Because you’re passing an exception to “throw,” you lose the previous stack trace and start a new stack trace for the exception.

Page 37: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Untitled-4 1 8/31/10 4:03 PM

Page 38: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

34 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

</Language Lab>

Th

e F

irst

D

ecad

e of

C#

{ C # C O R N E R }

Instead, simply call “throw,” and the exception is re-thrown with the stack trace intact:

try

{

var r = new RethrowProperly();

r.DoSomething();

}

catch (DivideByZeroException ex)

{

throw;

}

It’s a small but subtle difference. Now the call stack points directly at the line of code in DoSomething where the calculation is done. It’s much easier to debug when you know exactly where an error is happening.

Public Fields: Public fields are just plain bad. Non-public fields allow classes and structures to store and encapsulate data, while public fields expose the data without any restrictions or checks (a public delegate can lose its entire invocation list by simply setting it to null). Publicly accessible data should always be exposed through properties.

With the separate get/set semantics of properties, you have control over how the data is stored and retrieved. And with the ability to define a different accessibility level for the “getter” and the “setter,” you have even more control over how the data is exposed and manipulated.

Properties are an important aspect of the way data is exposed; WinForms data binding—along with other utilities and libraries in the .NET Framework—actually requires properties. Its reflection-based binding only looks for properties; it won’t even look at public fields.

The GoodNow let’s explore the stuff that makes C# such a pleasure to use. As I started writing this article, this list was the easiest to write.

Delegates: Explaining a delegate as simply a “type-safe function pointer” seems to do it such a disservice. Not only do delegates restrict available call sites to a specific signature, they also represent a complete invocation list that supports any number of subscribers. Another departure from function pointers is that delegates can represent instance methods as well as static methods (function pointers are limited to static methods). Finally, delegates automatically support asynchronous calling via the BeginInvoke/EndInvoke methods that are automatically generated for all delegates. Take that, function pointers!

Yield Keyword: The young whippersnappers who started using C# with the 2.0 release probably have no idea what the old folks used to have to do to create an object support for a custom enumerator. With the yield keyword, the C# compiler does all the heavy lifting of generating a little state machine behind-the-scenes. The yield keyword allows you to easily expose any set of data as an enumerable list that’s processed with a simple foreach loop.

I crack a smile every time I think about all the work the compiler does on my behalf with the yield keyword.

Using Keyword: I mentioned finalizers in the “ugly” portion of this article. Dealing with unmanaged resources is something developers must deal with until we get a fully managed OS. The IDisposable pattern is the accepted way of handling and disposing of unmanaged resources. But the burden is still on the developer to call Dispose when finished with an IDisposable object.

That’s where the “using” keyword comes in. Instead of writing a bunch of try/finally blocks to ensure your object’s Dispose method was called, you simply wrap it in a using block. I never liked relying on try/finally blocks for resource management—they’re supposed to be used for exception handling—so I welcomed the using block when it was introduced.

Lambdas: I left lambdas for last because they make delegates more fun to use.

Back in the .NET Framework 1.x, when you needed to use a delegate you had to create an instance of a specific delegate pointing to some method somewhere else (in the same class, in a different class—it didn’t matter). With the .NET Framework 2.0, you got anonymous delegates. These allowed you to, in a way, inline the method code. You no longer had to create a separate method—the compiler would do that for you.

With the .NET Framework 3.x, we have lambdas. These are the abbreviated version of anonymous methods. Code that used to look like this in the .NET Framework 2.0 (converting each element of a double array to its string equivalent):

public void ChangeData(double[] data)

{

string[] genericSA = Array.ConvertAll(data,

new Converter<double, string>(DoubleToStringConverter));

// Do something with genericSA

}

private static string DoubleToStringConverter(double d)

{

return d.ToString();

}

Is now reduced to a mere one-liner: string[] genericSA = Array.ConvertAll(data, d => d.ToString());

The anonymous method—d.ToString()—is converted to a real method when compiled to IL. The delegate type, along with the parameter types, is inferred automatically by the compiler. You get to write more of the “what” of the code, and the compiler does more of the “how.”

This is in no way an exhaustive list, but just a few things that stuck in my head when I was asked how I would describe the good, the bad and the ugly of C#. Thanks to the efforts of Microsoft and its language designers, it was rather difficult to create the ugly list.

I’m sure I’ve missed something you would’ve included in one of the lists. Do you have a good, bad or ugly C# list you’d like to share? E-mail me at [email protected]. VSM

Patrick Steele is a senior software consultant with SRT Solutions. A recognized expert on the Microsoft .NET Framework, he is a Microsoft MVP award winner and a presenter at conferences and user group meetings.

Page 39: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

You have the vision, but time, budget and staffconstraints prevent you from seeing it through. With rich user interface controls like Gantt Charts that Infragistics NetAdvantage® for .NET adds to yourVisual Studio 2010 toolbox, you can go to marketfaster with extreme functionality, complete usabilityand the “Wow-factor!” Go to infragistics.com/sparknow to get innovative controls for creating Killer Apps.

Infragistics Sales 800 231 8588 Infragistics Europe Sales +44 (0) 800 298 9055 Infragistics India +91-80-6785-1111twitter.com/infragistics

Copyright 1996-2010 Infragistics, Inc. All rights reserved. Infragistics, the Infragistics logo and NetAdvantage are registered trademarks of Infragistics, Inc. All other trademarks or registered trademarks are the property of their respective owner(s).

Gantt Chart

Untitled-12 1 4/9/10 1:55 PM

Page 40: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Supported by:Platinum Sponsor:

VISUAL STUDIO LIVE! FOCUS TOPICS:

Silverlight/WPF Web Visual Studio 2010 /.NET 4 SharePoint Cloud Computing Data Management

VISUAL STUDIO LIVE! PRE-CONFERENCE WORKSHOPS: SUNDAY, NOVEMBER 14, 2010 (SEPARATE ENTRY FEE REQUIRED)

Making Effective Use of Silverlight and WPF Billy Hollis & Rockford Lhotka

SQL Server 2008 and 2008 R2 for Developer Andrew Brust & Leonard Lobel

Better Process and Tools with TFS 2010 Brian Randell

VISUAL STUDIO LIVE! DAY 1: MONDAY, NOVEMBER 15, 2010Getting started in Silverlight – A Jumpstart to Productivity Tim Huckaby

What’s new in ASP.NET 4 WebForms - Wallace McClure

So Many Choices, So Little Time: Understanding Your .NET 4.0 Data Access Options Leonard Lobel

Building Business Applications with Visual Studio LightSwitch Orville McDonald

Transitioning from Windows Forms to WPF Miguel Castro

ASP.NET MVC Quick Primer Gus Emery

Best Kept Secrets in Visual Studio 2010 and .NET 4.0 Deborah Kurata

Overview of .NET 4

WPF & Silverlight: Data Visualization, NUI, and Next Generation of User Experience Tim Huckaby

What’s this WebMatrix anyway? Gus Emery

What’s New in the .NET 4.0 BCL Jason Bock

C# 4.0 Language Features Alexandru Ghiondea

Easing into Windows Phone 7 Development Walt Ritscher

ASP.NET “Razor” Miguel Castro

What’s New in Visual Studio 2010 Debugging Brian Peek

Tips & Tricks: Visual Studio 2010 IDE & Extensions Chris Granger

DINE AROUND ORLANDO

VISUAL STUDIO LIVE! DAY 2: TUESDAY, NOVEMBER 16, 2010CSLA 4, Silverlight and WPF Rockford Lhotka

AJAX with the UpdatePanel, WebForms, and the AJAX Control ToolkitX Wallace McClure

New IDE and Languages Features in VS 2010 using VB and C# Ken Getz

Visual Basic 2010 Overview

Silverlight, WCF RIA Services, and Your Business Objects Deborah Kurata

Leveraging Client Capabilities with jQuery in Visual Studio and ASP.NET Robert Boedigheimer

Windows Server AppFabric Caching Jon Flanders

Designing & Developing for the Rich Mobile WebJoe Marini

Digging Deeper into Windows Phone 7 Walt Ritscher

JQuery for ASP.NET Developers - Part 1 Jeffrey McManus

Building RESTful Services Using Windows Communication Foundation Jon Flanders

Pragmatic .NET Development with CodeFluent Entities Omid Bayani

Bind Anything to Anything in Silverlight and WPF Ken Getz

jJQuery for ASP.NET Developers - Part 2 Jeffrey McManus

Building RESTful Applications with the Open Data Protocol Todd Anglin

Windows Phone 7 and Azure: Enhancing the User Experience with the Cloud Danilo Diaz

Gentle Introduction to 2D Animation in SL/WPF Ken Getz

ASP.NET Request Processing Robert Boedigheimer

Can you use MEF too much? Hint - NO! Jon Flanders

Sensors, Locations, Notifications Oh My; Advance Topic in Windows Phone 7 Danilo Diaz

VISUAL STUDIO LIVE! AFTER DARK WITH DEVOPALOOZA

VISUAL STUDIO LIVE! DAY 3: WEDNESDAY, NOVEMBER 17, 2010Generating Dynamic UI in WPF 4 and Silverlight 4 Billy Hollis

Azure Platform Overview Vishwas Lele

Why Software Sucks David Platt

Introduction to SharePoint Development with Visual Studio 2010 Paul Yuknewicz

Design, Don’t Decorate Billy Hollis

Architecting for Azure Vishwas Lele

Building a Testable Data Access Layer Todd Anglin

Creating Extensions for the Visual Studio 2010 SharePoint Tools Jon Flanders

Using Microsoft Prism – Loose Coupling for Application Development David Platt

Developing an Azure based Monte Carlo Simulator Vishwas Lele

What’s New in VS 2010 for TFS? Brian Randell

PowerPivot and Excel Services Andrew Brust

Multi-touch Madness! Brian Peek

What is Microsoft Dallas? Michael Stiefel

Reserved for Late-Breaking Content Application Lifecycle Management for Developers in SharePoint 2010 Paul Yuknewicz

Using WPF for Good and Not Evil David Platt

How do you decide between Relational Database or Table Storage in the Cloud? Michael Stiefel

VS10 ALM Features Brian Randell

SharePoint for ASP.NET Developers Jon Flanders

VISIT US ONLINE AT VSLIVE.COM/ORLANDO FOR DETAILS ON SESSIONS, SPEAKERS, AND MORE!

Untitled-2 2 9/20/10 1:21 PM

Page 41: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

REGISTER BY OCTOBER 20TH AND SAVE $200!

USE PRIORITY CODE VSMOCTVSLIVE.COM/ORLANDO

ARE YOU READY to take your code to the next level? Expand your skillset and maximize the development capabilities of Visual Studio and .NET 4 during the four action-packed days of Visual Studio Live! Orlando!

Hard-hitting, real-world training on:

• VISUAL STUDIO 2010/.NET 4

• SILVERLIGHT/WPF

• SHAREPOINT

• WEB

• CLOUD COMPUTING

• DATA MANAGEMENT

FOUR DAYS THAT WILL ROCK YOUR CODE

NOVEMBER 14–17, 2010ORLANDO FLORIDA HILTON IN THE WALT DISNEY WORLD RESORT

Untitled-2 3 9/20/10 1:22 PM

Page 42: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

DynamicPDF Generator v6.0 for .NET

ceTe Software has been delivering quality software applications and components to our customers for over 10 years. Our DynamicPDF product line has proven our commitment to delivering innovative software components and our ability to respond to the changing needs of software developers. We back our products with a first class support team trained to provide timely, accurate and thorough responses to any support needs.

Easy-to-use Highly efficient Industry leading support Huge feature set

DynamicPDF…Proven .NET Components for Real-Time PDFs

Layout reports in DynamicPDF Designer with its Visual Studio look and feel.

.

Untitled-1 1 3/15/10 11:50 AM

Page 43: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 39

ID StatementVisual Studio Magazine (ISSN 1537-002X) is published monthly by 1105 Media, Inc., 9201 Oakdale Avenue, Ste. 101, Chatsworth, CA 91311. Periodicals postage paid at Chatsworth, CA 91311-9998, and at additional mailing offi ces. Complimentary subscriptions are sent to qualifying subscribers. Annual subscription rates payable in U.S. funds for non-qualifi ed subscribers are: U.S. $35.00, International $60.00. Annual digital sub-scription rates payable in U.S. funds for non-qualifi ed subscribers are: U.S. $25.00, International $25.00. Subscription inquiries, back issue requests, and address changes: Mail to: Visual Studio Magazine, P.O. Box 2166, Skokie, IL 60076-7866, email [email protected] or call toll free (888) 768-8759, fax number 847-763-9564. International calls 847-763-9135. POSTMASTER: Send address changes to Visual Studio Magazine, P.O. Box 2166, Skokie, IL 60076-7866. Canada Publications Mail Agreement No: 40612608. Return Undeliverable Canadian Addresses to Circulation Dept. or IMS/NJ. Attn: Returns, 310 Paterson Plank Road, Carlstadt, NJ 07072.

Copyright Statment© Copyright 2010 by 1105 Media, Inc. All rights reserved. Printed in the U.S.A. Reproductions in whole or part prohibited except by written permission. Mail requests to “Permissions Editor,” c/o Visual Studio Magazine, 230 California St. Suite 302, San Francisco, CA 94111.

Legal DisclaimerThe information in this magazine has not under-gone any formal testing by 1105 Media, Inc. and is distributed without any warranty expressed or implied. Implementation or use of any information contained herein is the reader’s sole responsibility. While the information has been reviewed for accuracy, there is no guarantee that the same or similar results may be achieved in all environments. Technical inaccuracies may result from printing errors and/or new develop-ments in the industry.

Corporate Address1105 Media9201 Oakdale Ave. Ste 101, Chatsworth, CA 91311www.1105media.com

Media KitsDirect your Media Kit requests to Matt Morollo, VP Publishing, 508-532-1418 (phone), 508-875-6622 (fax), [email protected]

ReprintsFor single article reprints (in minimum quantities of 250-500), e-prints, plaques and posters contact:PARS InternationalPhone: 212-221-9595E-mail: [email protected]/QuickQuote.asp

List RentalThis publication’s subscriber list, as well as other lists from 1105 Media, Inc., is available for rental. For more information, please contact our list manager, Merit Direct. Phone: 914-368-1000; E-mail: [email protected]; Web: www.meritdirect.com.

Advertiser Page

/n Software Inc. 7www.nsoftware.com

Altova C4www.altova.com

Aspose 11www.aspose.com

ceTe Software 38www.cete.com

Developer Express 17, 19, 21, 23, 25, 27www.devexpress.com

dtSearch 32www.dtsearch.com

ESRI, Inc. 9www.esri.com

GrapeCity FarPoint 12 A-B, C3www.fpoint.com

Infragistics C2, 1, 29, 31, 35www.infragistics.com

LEAD Technologies, Inc. 5www.leadtools.com

Programmer’s Paradise 2www.programmersparadise.com

TechExcel, Inc. 33www.techexcel.com

VSLive! 36, 37http://vslive.com/orlando

Editorial IndexAdobe Systems Inc. 12www.adobe.com

Amazon.com Inc. 40www.amazon.com

ComponentOne LLC 12www.componentone.com

Dundas Data Visualization Inc. 10www.dundas.com

EC Software GmbH 12www.ec-software.com

Advertising Sales Ad Index

EastMatt Morollo VP, Publishing Phone: [email protected]

WestChris KourtoglouRegional Sales ManagerPhone: [email protected]

National Accounts DirectorWilliam SmithPhone: [email protected]

Microsoft Account ManagerDanna VedderPhone: 253-514-8015dvedder@11 05media.com

Director, Print ProductionJenny Hernandez-AsandasPhone: 818-814-5289Fax: [email protected]

Production CoordinatorSerena BarnesPhone: [email protected]@1105media.com

GO TO VisualStudioMagazine.comto access the stories in this issue, plus read exclusive online-only content.

Media KitsDirect your Media Kit requests to Matt Morollo, VP Publishing, 508-532-1418 (phone), 508-875-6622 (fax), [email protected]

1192w

MDPu(f

RFo25PAPhE-w

L

Page 44: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

40 VISUAL STUDIO MAGAZINE · October 2010 · VisualStudioMagazine.com

In a Redmond Review column last year (“What’s Old Is New Again,” April 2009), I discussed a move by Microsoft to reform its then-named SQL Data Services (SDS). At the time, Microsoft decided to make SDS (now SQL Azure) a true cloud-based SQL Server off ering, rather than a structured data entity store that merely used SQL Server behind the scenes. I thought that was the right decision. It marked the point where Microsoft decided to base its cloud on a core strength—its server products—rather than off er a pale imitation of Amazon Web Services.

Now, 18 months later, Microsoft has replicated that approach across its cloud off ering. SharePoint 2010 was written with the cloud in mind. The forthcoming Dynamics CRM 5 will be released as a cloud product before the on-premises version becomes available. This isn’t Microsoft trying to be trendy. Quite the contrary: As I talk to people at Microsoft, the cloud commitment appears to have become a fully integrated part of doing business. I see this as quite signifi cant; perhaps some more examples will help me convey why.

Windows Azure, PervasiveRecently, I was part of a group e-mail discussion with a Microsoft product team member. Someone else on the thread had a question about a particular feature. In response, the Redmond offi cial said Microsoft would be implementing the feature “in the next version of SQL Server and SQL Azure.” This was very matter-of-fact, and the feature in question wasn’t even especially cloud-oriented. The point is that the two products were one, and their product development anticipated the on-premises and cloud versions on equal terms.

Another example is Visual Studio LightSwitch, the product I wrote about in my last column. The line-of-business apps that LightSwitch produces can be deployed to the desktop, the corporate server or to a combination of Windows Azure and SQL Azure. The LightSwitch team, while proud of this capability, hasn’t even presented it with a lot of fanfare. To do so would betray the philosophy that the cloud should be just another deployment option, and that it’s the job of LightSwitch to abstract away its diff erences.

There’s more to this: The Windows Azure appliance; the OData features of SQL Azure and Microsoft Codename “Dallas” that equalize the two with WCF Data Services on a corporate server; Windows

Azure services in MSDN subscriptions and corporate Enterprise Agreements. Over and over, Microsoft is integrating the cloud with its other products and services

Microsoft has clearly decided to move to the cloud on its own terms. Many in the industry see this as a fl awed strategy; they reason that Microsoft is approaching something that’s completely new and attacking it with a playbook that’s completely old. In eff ect, they cast Microsoft as naïve, arrogant or both, and claim the company is following a path that will meander toward failure. A lot of people accept this argument on authority.

Obsolete or Classic?That authority is weak, though, and the position is unsupported and dogmatic. No one really knows how the cloud will turn out, or who will dominate it. The prediction of failure may still turn out to be correct, but the argument itself is prejudiced. Microsoft fi tting the cloud to its own stack means it’s attempting to fi t the cloud to its customers’ businesses as well. Maybe that won’t work, but it sure seems worth a try. The startup customers of Amazon may acquiesce to a fundamentally new computing model in the cloud—but the corporate customers of Microsoft may not fi nd that so suitable.

What Microsoft has always done well is take something hard, make it relatively easy and let customers invest their own hard work on top of the resulting platform. Graphical apps in DOS were hard, so Microsoft built a GUI into the OS with Windows. The Windows API model was hard, so Microsoft gave us Visual Basic to abstract those diffi culties away. The Web was hard, so Microsoft gave us ASP and Web Forms. Datacenters are hard—and expensive, too—so Microsoft is off ering its Platform as a Service cloud to abstract away those challenges as well.

The stack-integration approach is working for product teams and gaining momentum continuously. It’s starting to resonate with partners and customers, too. It’s hard to see that as a bad sign. Fidelity and consistency should not be mistaken for stubbornness and inertia. Microsoft is not just going through the motions; it’s being true to its roots. That’s usually the right way to go. VSM

Andrew J. Brust is a Microsoft regional director and MVP, and coauthor of “Programming Microsoft SQL Server 2008” (Microsoft Press, 2008). A

frequent speaker at developer industry events, Brust is also co-chair of the VSLive! family of conferences and a contributing editor to Visual Studio Magazine. Brust has been a participant in the Microsoft ecosystem for 15 years, and has worked closely with both the Microsoft Redmond-based corporate team and its field organization for the last six years.

A Well-Grounded Cloud

BY ANDREW J. BRUST

</Redmond Review>

Microsoft has clearly decided to move to the cloud on its own terms.

Page 45: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Untitled-2 1 7/14/10 11:22 AM

Page 46: UNIT TESTING and ASP.NET MVC - pdf.1105media.compdf.1105media.com/VSMMag/2010/700870153/VSM_1010DGD.pdf · VisualStudioMagazine.com · October 2010 · VISUAL STUDIO MAGAZINE 3 14

Experience how the Altova MissionKit®, the

integrated suite of XML, database, and data

integration tools, can simplify even the most

advanced XML development projects.

Bring your

XML development

projects to light

with the complete set

of tools from Altova®

The Altova MissionKit includes multiple intelligent

XML tools – now with cutting edge chart and

report generation:

Download a 30 day free trial!

Try before you buy with a free,

fully functional, trial from

www.altova.com

XMLSpy® – industry-leading XML editor

• Support for all XML-based technologies

• Graphical editing views, powerful debuggers,

code generation, & more

MapForce® – graphical data mapping tool

• Drag-and-drop data conversion with code generation

• Support for XML, DBs, EDI, Excel® 2007+,

XBRL, flat files & Web services

StyleVision® – visual stylesheet & report designer

• Graphical stylesheet and report design for

XML, XBRL & databases

• Report designer with chart creation

• Output to HTML, PDF, Word & e-Forms

Plus up to five additional tools…

XBRL, fla

Sty

New in

Version 2011:

• Instant chart generation for

XML, XBRL, and databases

• Exporting charts to XSLT,

XQuery, or image files

• Schema flattener &

schema subset creation

• Report generation in MapForce

via StyleVision integration

• Chained data mapping

tra

nsformations

Untitled-4 1 8/31/10 4:02 PM