partition web apps intelligently - 1105 mediapdf.1105media.com/vsmmag/2009/vsm_901dg.pdf · steve...

36
VisualStudioMagazine.com Is Agile Rock or Disco? PLUS Target Multiple .NET Frameworks Windows Workflow Changes Direction JANUARY 2009 Vol. 19, No. 1 ENTERPRISE SOLUTIONS FOR .NET DEVELOPMENT Partition Web Apps Intelligently Microsoft’s MVC framework makes it possible (finally!) to implement “a separation of concerns” in ASP.NET.

Upload: ngoque

Post on 22-Apr-2018

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

VisualStudioMagazine.com

Is Agile Rock or Disco?

PLUS

Target Multiple .NET Frameworks

Windows Workflow Changes Direction

JAN

UA

RY

20

09

• V

ol. 1

9,

No.

1

E N T E R P R I S E S O L U T I O N S F O R . N E T D E V E L O P M E N T

Partition Web AppsIntelligentlyMicrosoft’s MVC framework makes it possible (finally!) to implement “a separation of concerns” in ASP.NET.

0109vsm_C1.v2 12/15/08 11:56 AM Page 1

Page 2: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

BeTheDataGuru

Visual Studio WPF/Silverlight SharePoint SQL Server PowerShellJava COM

Project5 12/11/08 4:42 PM Page 1

Page 3: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

Data visualization for every need, every platform

Our most popular product, Chart FX providescharts, gauges and maps with additional verticalvisualization functionality for business intelligence(OLAP), geographic data, financial technicalanalysis, and statistical studies andformulas. Recognized as the innovatorand leader of the charting componentcategory for the past 15 years, Chart FXdelivers incomparable gallery options,aesthetics and data analysis features.

Grid FX was specifically designed for visual studiodevelopers to take advantage of a powerfuldesign-time experience, integrated Chart FXfunctionality right in the box, and AJAX toprovide robust, run-time functionality in ASP.netapplications. The dynamic aesthetic features for data presentation and analysis allow simpleadaptation to an existing application or to specificcorporate branding guidelines.

PowerGadgets puts powerful IT monitoring on your desktop and in your data sidebar.IT professionals can now create gadgetsthat consume data from WMI, Exchange,SQL Server and even the Windows Registry.PowerGadgets does not require anydevelopment environments, servers orbrowsers to run real-time gadget componentssuch as charts, gauges and maps.

To master the art of data visualization, you must seek out the leader. For almost two decades,Software FX has risen above all others by bringing top-of-the-line data visualization tools toenterprise developers working with diverse markets, platforms and environments. Thiswisdom has evolved into a vast body of products, including a data presentation tool thatprovides a best-of-breed solution for Windows developers seeking enterprise quality andperformance, as well as a professional IT monitoring solution offering incredible features forreporting and monitoring data. For a world of data visualization products that can raise yourwork to a higher level, depend on the source that’s clearly on top.

AchieveAHigherStateOfDataVisualization

Visit softwarefx.com for interactive demos and more information about our latest products.

Project5 12/11/08 4:43 PM Page 2

Page 4: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com2

C# CORNER

21 Target Multiple .NETFrameworksMany developers have the misconception that targeting older versions of the Framework meansyou can’t use any of the new C# language features.It’s time to dispel that myth. BY BILL WAGNER

DEPARTMENTS6 Letters to the Editor

7 Editor’s Note BY PATRICK MEADER

8 First LooksProduct Listings . . . . . . . . . . . . . . . . . . . . . . . . . . . .8Reviews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9

24 Ask KathleenWindows Workflow Changes DirectionLearn how Windows Workflow 4.0 changes every-thing; why using string primary keys is a bad idea;get a data grid for Windows PresentationFoundation; load files at runtime; and how to copyfiles into the executable directory. BY KATHLEEN DOLLARD

28 Special InterviewConnect to the CloudIn this special interview, Microsoft Corporate VicePresident Robert Wahbe discusses the AzureServices Platform and Software plus Services applications with 1105 Media’s Jeffrey Schwartzand Michael Desmond. BY JEFFREY SCHWARTZ AND MICHAEL DESMOND

31 Index of Advertisers

32 The Pragmatic DeveloperIs Agile Rock or Disco? BY BILLY HOLLIS

January 2009 • VOLUME 19 • NO. 1

FEATURES

10 Partition Web Apps IntelligentlyMicrosoft’s Model-View-Controller framework makes it possible to implement “a separation of concerns” in ASP.NET—something that wasdifficult, if not impossible, previously. Learn how to take advantage ofMVC to design better Web apps that separate their architectural elements—the UI, business logic, and code—properly, as well as how to review whatyou create with unit testing. BY STEVE MICHELOTTI

COLUMNS

10

“The MVC framework solves the separation of concerns problems oftraditional web forms by partitioningresponsibilities between Models,Views, and Controllers.”

Steve Michelotti, “Partition Web Apps Intelligently,” p. 10

Contents0109vsm_TOC_02-04.v6 12/15/08 9:39 AM Page 2

Page 5: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

programmersparadise.com800-445-7899

Your best source for software development tools!

Prices subject to change. Not responsible for typographical errors.

®

programmers.com/theimagingsource

Download a demo today.

New Release!

Professional EditionParadise #

T79 02101A01$919.99

programmers.com/altova

Enterprise Edition1 user

Paradise # I0D 03101A02 $1,056.99

New Release!

Altova® MapForce® 2008Visual Data Conversion,Transformation, and Integration Toolby AltovaMapForce: The premier data mapping,conversion, and integration tool from the creators of XMLSpy®. Through its visual interface, users can map seamlessly between any combination of XML, database, flat file, EDI, and/orWeb service, then convert data instantlyor auto-generate an application for recurrent transformations. Languages forcode generation include: XSLT 1.0/2.0,XQuery, Java, C++, and C#.

• .NET WinForms control for VB.NET and C#• ActiveX for VB6, Delphi, VBScript/HTML, ASP• File formats DOCX, DOC, RTF, HTML, XML, TXT• PDF export without additional 3rd party

tools or printer drivers• Nested tables, headers & footers, text

frames, bullets, numbered lists, multipleundo/redo, sections, merge fields

• Ready-to-use toolbars and dialog boxes

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

programmers.com/telerik

Telerik RadControlsby Telerik Add grid, combo, editing, navigation and charting functionality to your AJAX and ASP.NET projects.RadControls for ASP.NET enhances your Web applications by adding AJAX functionality to yourASP.NET projects. The suite takes full advantage of the features included in Visual Studio 2005.RadControls for ASP.NET helps developers deliver feature-rich, standards-compliant (WAI-A, WCAG 1.0, XHTML 1.1) and cross-browser compatible Web applications, while significantly cutting their development time. RadControls for ASP.NET includes: RadEditor, RadTabstrip, RadInput,RadCalendar, RadUpload, RadWindow, RadAjax,RadGrid, RadCombobox, RadMenu, RadSpell,RadChart, RadTreeview and more.

Single DeveloperParadise #

TB3 01101A01$648.99

programmers.com/storagecraft

StorageCraft ShadowProtect IT Edition v3.xby StorageCraftCreate, edit or restore backup images on as many servers, desktops and laptops as needed.Create online or cold state backups in minutes, no software installation required. StorageCraft™

ShadowProtect IT Edition provides complete bare metal recovery in minutes. ShadowProtect IT Edition provides IT Professionals with abootable Windows environment to create andrestore compressed and encrypted backups, no software installation required.Paradise #

SC5 03101A01 $3,252.99

dtSearch Engine for Win & .NETAdd dtSearch‘s “blazing speeds” (CRN Test Center) searching and file format support• dozens of full-text and fielded

data search options• file parsers/converters for hit-highlighted

display of all popular file types• Spider supports dynamic and static web data;

highlights hits with links, images, etc. intact• API supports .NET, C++, Java, SQL and more;

new .NET Spider API

“Bottom line: dtSearch manages a terabyte of text in a single index and returns results in less than a second.” —InfoWorld

programmers.com/dtsearch

Single ServerParadise #

D29 02101A07 $949.99

New64-bit

Version!

programmers.com/sparxsystems

New Release!

Enterprise Architect 7.1Visualize, Document and Control Your Software Projectby Sparx SystemsEnterprise Architect is a comprehensive,integrated UML 2.1 modeling suite providing key benefits at each stage ofsystem development. Enterprise Architect7.1 supports UML, SysML, BPMN andother open standards to analyze, design,test and construct reliable, well under-stood systems. Additional plug-ins arealso available for Zachman Framework,MODAF, DoDAF and TOGAF, and to integrate with Eclipse and Visual Studio2005/2008.

Corporate Edition1-4 Users

Paradise # SP6 0001

$196.99

programmers.com/multiedit

Multi-Edit 2008by Multi Edit SoftwareMulti-Edit 2008 delivers, a powerful IDE,with its speed, depth, and support forover 50 languages. Enhanced searchfunctions include Perl 5 RegularExpressions and definable filters.Supports large DOS/Windows, UNIX,binary and Mac files. File SyncIntegration for: Delphi 6, 7, 2005,C++Builder 6, BDS 2006 and RadStudio2007, VB 6, VC 6, VS 2003 & VS2005. Includes file compare, code beautifying, command maps, and much more.

1-49 UserParadise #

A30 01201A02$161.99

New Release!

programmers.com/lead

LEADTOOLS DocumentImaging v 16:by LEAD TechnologiesLEADTOOLS Document Imaging has every component you need to develop powerfulimage-enabled business applications includingspecialized bi-tonal image display and processing, document clean up, high-speedscanning, advanced compression (CCITTG3/G4, JBIG2, MRC, ABC) and more.• Multi-threaded OCR/ICR/OMR/

MICR/Barcodes (1D/2D)• Forms recognition/processing• PDF and PDF/A• Annotation (Image Mark-up)• C/C++, .NET, WPF - Win32/64

Paradise # L05 03201A01$2,007.99

New Version

16!

programmers.com/nsoftware

/n software Red CarpetSubscriptions by /n software/n software Red Carpet™ Subscriptions giveyou everything in one package: communica-tions components for every major Internet protocol, SSL and SSH security, S/MIMEencryption, Digital Certificates, Credit CardProcessing, ZIP compression, InstantMessaging, and even e-business (EDI) transactions. .NET, Java, COM, C++, Delphi,everything is included, together with per developer licensing, free quarterly update CDsand free upgrades during the subscription term.Paradise #

D77 09101L01 $1,444.99

programmers.com/techexcel

DevTrack Small Team EditionPowerful Defect and Project Trackingby TechExcelTechExcel DevTrack is the most powerful,affordable and easy-to-use defect and projecttracking tool for development organizations.You’ll dramatically transform your developmentprocesses, save significant time and resources,and deliver quality products on-time and on-budget.

• Sophisticated workflow engine

• Point-and-click administration

• Fully configurable user interface 5-User PackParadise # T34 0208 $1,414.99

programmers.com/faircom

c-treeACE™ Professional by FairComThe c-treeACE database engine is a high performancedatabase alternative proven by developers in missioncritical enterprise systems, desktop deployments, andembedded devices for over 25 years. • Complete set of APIs including ADO.NET, LINQ,

C#, C/C++, ODBC, JDBC, VCL, and dbExpress • Graphical productivity tools • Simple deployment • No DBA or ongoing administration • Low deployment licensing costs • Cross-platform support for all major platforms

including Windows, UNIX, Linux, and Mac OS X

Make your applications faster, easier to deploy, and more affordable with c-treeACE.

Paradise # F01 0131

$711.99

programmers.com/vmware

FoundationAcceleration Kit

Paradise # V55 47101A01

$2,504.99

VMware InfrastructureAcceleration KitsVMware Infrastructure 3 offers SMB organizations a scalable and cost-effective way to optimize utilization of technology assets, simplify IT management and protect the data and IT environments that run their businesses. Three new Acceleration Kits are now available, one for each of the three editions of VI3. These new kits offer midsize and smaller organizations and branch offices a cost-effective way to deploy a comprehen-sive virtualization solution that includes centralized management functionality. The ideal organization has a growing IT environment with between 15-60 servers. Call for pricing on the Standard High Availability Acceleration Kit and Midsize Acceleration Kit.

New Release!

Project4 12/11/08 4:04 PM Page 1

Page 6: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com4

LEARN FROM THE PROSAs a developer you are constantlyfacing the problem of how to keepup with all the new technologiesbeing released while still gettingyour job done. You keep hearingabout solutions to your program-ming problems but the question is:are they the right solutions for yourparticular needs? You could spendthe hours or even days trying tofind the answers yourself, or youcould let the experts do it for you.Redmond Media Group Events offersa variety of conferences and shows

where you can learn about new technologies and what they might offeryou, attend in-depth workshops that focus on topics specific to yourneeds, ask questions of the experts, and interact with your peers to discuss problems they face and what solutions they’ve come up with.Whether it’s Web design, .NET development, or SQL Server programming,we’ve got an event that matches your needs. Visit the Redmond MediaGroup events page at http://redmondevents.com to learn more aboutupcoming conferences and shows.

ONLINE ARTICLES

Inside VSTS: Branching in Visual Studio 2010One limitation in Team System today is that you can’t easily visualizeyour branching structure so it’s difficult to understand the movement ofcode from branch to branch. In this installment of Jeff Levinson’s InsideVSTS online column, he takes a look into the future and explains howthe new branch visualization feature in VS 2010 will bring order to thechaos of branching and merging. LOCATOR+ CODE: VS0901JL1

Practical ASP.NET: Creating Master/Detailand Update Pages with Entity FrameworkIn previous columns Peter Vogel showed how to build a simple EntityFramework model and used it to drive a series of drop-down lists bothwith and without the AJAX-enabled UpdatePanel. With this column, hemoves on to the next obvious step: Creating a Master/Detail pagewith updating. LOCATOR+ CODE: VS0901PV1

Online Check out these and other exclusive online articles and tutorials on the Visual Studio Magazine Web site at

VisualStudioMagazine.com

ContentPractical ASP.NET: Routing YourASP.NET ApplicationOne of the features added in Service Pack 1 for .NET 3.5is routing (which first appeared in the MVC version ofASP.NET). Routing allows you to disconnect the physicalstructure of your site from the URLs that users invoke toaccess pages on your site. Peter Vogel explains how totake advantage of this feature to rearrange your site’sstructure without invalidating your users’ bookmarks. LOCATOR+ CODE: VS0901PV2

ONLINE BLOGS

VSM’s Big IssueVisual Studio Magazine’s Editor in Chief Patrick Meaderand Managing Editor Guy Wright are kicking off a collab-orative blog where they take a look at some of the biggerissues facing .NET developers these days. The blog willfeature opinions, interviews with industry insiders, andpose questions designed to stimulate discussion. Checkout their new blog. LOCATOR+ CODE: VS0901BI1

ONLINE TUTORIALS

Wahlin on .NET: Adding Style toSilverlight 2 ControlsSilverlight 2 provides a nice set of controls that can beused to capture and display data. While control proper-ties can be set directly on the control in a XAML fileusing attributes, some properties will be duplicatedbetween controls, causing maintenance headaches. Inthis tutorial, Dan Wahlin explains how to avoid duplicatingproperties between controls. LOCATOR+ CODE: VS0901DW1

What Are Locator+ Codes?Locator+ codes give you instant access to a feature on VisualStudio Magazine Online. Simply type the Locator+ code intothe field in the upper-right corner and click on FIND IT.

.NET NEWSLETTER SIGN-UPEvery week, the .NET Insight e-mail newsletter brings you up-to-date news, technical information, opinions,interviews, and analysis on topics and technologies such as Visual Basic .NET, C#, SQL Server and data access,ASP.NET, wireless, Web services, and XML. Sign up for free at visualstudiomagazine.com.

0109vsm_TOC_02-04.v6 12/15/08 9:39 AM Page 4

Page 7: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

Brought to you by:

San Francisco Hyatt Regency EmbarcaderoFebruary 23-27, 2009

Don’t Miss Out On This Special Offer For VS Magazine Readers!

Register for VSLive! And Get a FREE pass to the MSDN Developer Conference!

Software development is changing faster than ever, and Microsoft continues to introduce key new products. Don’t get left behind. Join your fellow developers for:

• Tons of independent, deep-dive content VSLive! is known for.

• Over 80 sessions and workshops —

• Production products including NET 2.0, ADO.NET Entity Framework, SAP.NET, AJAX, Windows Forms, and DataSet.

• New products including WPF, WCF, WF, .NET 3.0/3.5, Silverlight 2.0, VSTO, LINQ, ADO.NET Entity Framework

• Future technology including .NET 4.0, Cloud computing, Rosario, Windows 7, Multi-Touch

• Tech tips from the best minds in the business with information you can use now.

To view the complete agenda and take advantage of your VS Magazine reader discount, go to vslive.com/sf2009. Be

sure to enter priority code NQ9F14.

SAVEUP TO$300

Register for VSLive! San Francisco by Jan. 21 and save an additional $100 over our Early Bird savings. Be sure to use promo code NQ9F14 and save

an additional $100 off of our regular conference packages.

BONUS! FREE pass to Microsoft’s one-day

MSDN Developer Conference on Monday, Feb. 23.

(Space is limited; fi rst come, fi rst served.)

0109vsm_VSLive Ad_p5.indd 10109vsm_VSLive Ad_p5.indd 1 12/15/08 2:15:41 PM12/15/08 2:15:41 PM

Page 8: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com6

Letters to Visual Studio Magazine are welcome. Letters must include yourname, address, and daytime phonenumber to be considered for publica-tion. Letters might be edited for form,fit, and style. Letters express the pointof the individual authors, and do notnecessarily reflect the views of theeditors, VSM, or 1105 Media. Pleasesend them to Letters to the Editor, c/oVisual Studio Magazine, 230 CaliforniaSt., San Francisco, CA 94111; faxthem to 415-814-0961; or e-mailthem to [email protected].

Letters

Reader Likes the Switch

I’ve been a VSM reader for more than five years and a Visual Basic user for a few years longerthan that. I wanted to let you know that I especially enjoyed VSM ’s recent twin columns fromKathleen Dollard [Ask Kathleen, “What C# Devs Should Know About VB,” December 2008]

and Bill Wagner [C# Corner, “What VB Devs Should Know About C#,” December 2008] on theissues you face when switching between C# and VB.

Too often, developers and authors turn the differences between languages into argu-ments about why one language is better or worse than the other. These real-world articles toldyou how the languages work and the issues you can expect to encounter if you switch betweenthe two. As a VB user, it was informative for me to read about the potential issues C# devsmight face when they work on projects with me. After reading Dollard’s article, I can under-stand better why my own team has faced some of the issues it has.

I like VSM immensely and have enjoyed reading it these several years, but I love whatyou did with these articles and hope to see more like them in the future. Please keep up thegood work.

Rodney Bryant, received by e-mail

Office and Vista Both ExasperateI agree completely with VSM Editor in Chief Patrick Meader’s comments about Office 2007and its “detestable, exasperating ribbon with the pared down menu options” [Editor’s Note,“Microsoft Opens Up (Even More),” October 2008].

Office 2007 is a daily source of frustration for me at my job. I have had only a little expe-rience with Vista, and I do find the new explorer easy to navigate. Nevertheless, silly omissionslike the Run command on the Start menu really bug me. Mr. Meader is not alone, and certainlynot a “raving nutter.” I suspect the vast majority of users have the same frustrations. As a seasonedWindows user and software architect by trade, I have been consistently advising my colleaguesand relatives who are contemplating buying a new PC to get one with XP pre-installed and tobuy Office 2003. Maybe this is because they’re all going to ask me for help or even blame meif they get stuck or “lost” in Vista or Word 2007.

It’s sad that Microsoft, with its vast resources, has somehow dropped the ball on its coreproducts by trusting its younger generation of product managers without some serioushands-on usage of their own dog food. I suspect that their executives would have found theseproducts just as frustrating as we do had they been using them without handholding or flashydemos from their evangelists.

Norm Katz, San Diego, Calif.

VisualStudioMagazine.comJanuary 2009 • Volume 19 • No. 1

Editorial StaffVice President, Doug Barney

Editorial DirectorEditor in Chief Patrick Meader

Managing Editor Guy Wright

Managing Editor, RMG Wendy Gonchar

Associate Managing Katrina CarrascoEditor, RMG

Contributing Editors

Andrew J. Brust, Ken Cox, John Cronan, Dan Fergus, John Gavilan, Roger Jennings, Don Kiely, Martin Kulov, Jeff Levinson, Bill McCarthy,

John Charles Olamendy Turruellas, Keith Pleas, Peter Varhol, Bill Wagner

Art StaffCreative Director Scott Shultz

Senior Art Director Bruce Gardner

Graphic Designer Erin Horlacher

Online/Digital MediaEditor, VisualStudio Becky Nagel

Magazine.comExecutive Editor, New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor, Web Gladys Rama

Web Producer Shane Lee

Director, Web Development Rita Zurcher

President Henry Allain

Vice President, Publishing Matt N. Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S. Cook

Marketing Programs Manager Videssa Djucich

President & Neal VitaleChief Executive Officer

Senior Vice President Richard Vitale& Chief Financial Officer

Executive Vice President Michael J. Valenti

President, 1105 Events Dick Blouin

Vice President, Finance Christopher M. Coates& Administration

Vice President, Audience Abraham M. LangerMarketing & Web Operations

Vice President, Information Erik A. LindgrenTechnology & Web Operations

Vice President, Carmel McDonaghCirculation

Chairman of the Board Jeffrey S. Klein

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

E-mail: E-mail is routed to individuals’ desktops. Please use thefollowing form: [email protected]. Do not include a middle name or middle initials.

Telephone: The switchboard is open weekdays 8:30 a.m. to 5:30 p.m. Pacific time. After 5:30 p.m. you will be directed to individual extensions.

San Francisco Office 415-814-0950; Fax 415-814-0961

Irvine Office 949-265-1520; Fax 949-265-1528

Corporate Office 818-734-1520; Fax 818-734-1528

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

0109vsm_Letters.6.v5 12/15/08 2:30 PM Page 6

Page 9: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

Editor’s Note

BY PATRICK MEADEReditor in chief

VSM’SNEW BIG IDEAIf you’re a longtime programmer or merely someone who has followed computers for a while, it’s possible you’ve seen the work of VSM’s managingeditor before.Guy Wright has been working at computer-related magazines

since the personal computer’s relative infancy, stretching backto 1983, when he began his publishing career with a two-yearstint as the technical editor and technical manager of RUNMagazine, which served Commodore’s VIC-20 and Com-modore 64 computers. Guy followed that gig up by serving asthe founding editor in chief at AmigaWorld Magazine. Onceupon a time, when the Apple 2 loomed large and the IBM PCjuggernaut had yet to be established, all of the cool kids I knewhad Amigas, and they were always telling me how much theircomputer kicked the ass of every other computer.

Since his time at AmigaWorld Magazine, Guy has beeninvolved in several computing- and B2B-related titles, bothprint- and Web-based.He has worn other hats, as well,workingwith the development team on Commodore’s ill-fated CDTVdevice, putting the first comic books on CD-ROM, and evenspending some time in purgatory—I believe he calls it heaven—using VB3 to create magazine archive CD-ROMs and demodiscs. To put it another way, Guy was programming in VBbefore I’d even heard of VB,and I’ve been working at this maga-zine for going on 13 years.He notes that he wasn’t a professionalprogrammer—a not-uncommon trait for many people whoinitially picked up VB—but he appreciated the way it let smartpeople who knew the business rules implement solutions fortheir domains. One subject Guy and I have chatted aboutextensively is the fact that it’s much harder to pick up VB.NETand be productive in the same way that pre-.NET versions ofVB let you pick up the tool and be productive.

I felt it was a coup for the magazine to score someonewith Guy’s experience when we hired him. I still do. For thepast couple of years, Guy has played policeman on the staff,making sure the process runs smoothly and the articles areedited properly, while also nagging the editor in chief to turnhis articles in.

“You’ve been doing this long enough that your turn-around on these should be minutes, not days!” he tells me.

He’s been writing editorials for years, he reminds me, and itgets easier over time. Maybe, maybe not.

But in the time-honored tradition of bosses everywhere,I sense opportunity here. If it’s so easy, let him do it. And so heshall. Beginning this month, Guy will begin overseeing VSM’snew online blog: “VSM’s Big Issue.” This blog will serve as ajumping-off point for discussing the issues and technologiesof interest to Visual Studio developers, issues that wouldn’tnormally fit neatly into the pages of VSM.

In contrast to many other blogs you can read, where thewriters climb up on their own particular soapboxes to sharetheir takes on the world, we want the VSM blog to be more ofan open forum where we pose questions on topics we thinkare worth discussing and then encourage readers to share theiropinions. (OK, we might occasionally do a little soapboxingwhen the mood strikes.)

We will be inviting many of our friends of the magazineto stop by and chat about these same issues. We’ll includeshort interviews with magazine luminaries and columnists,movers and shakers at Microsoft, and key technology imple-menters at the third-party companies who drive much of theinnovation in Visual Studio.

We will be updating this blog frequently, so be sure tostop by often to see what’s new. Guy and I will both be postingto the page, though Guy will be posting a bit more frequentlythan I will—he does have to show me how it’s done, after all.

One of our main goals with this blog is to make it easierto talk to the editors, to express what you like or don’t likeabout the magazine, and to give you a forum for telling us howwe at VSM can serve you better. We look forward to carryingon this conversation online. VSM

Talk Back: What would you like to see us cover in the newVSM’s Big Issue blog? Tell me at [email protected] [email protected]

HO

TO

BY

PA

T JO

HN

SO

N S

TU

DIO

S

VisualStudioMagazine.com · January 2009 · VISUAL STUDIO MAGAZINE 7

0109vsm_EdNote_07.v6 12/15/08 9:13 AM Page 7

Page 10: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

LooksFirst

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com8

P R O D U C T L I S T I N G S + R E V I E W S

Editor’s Note: Please send product information

to New Products Editor, c/o Visual Studio Magazine,

230 California St., San Francisco, CA 94111;

Phone: 415-814-0950, fax: 415-814-0961;

e-mail [email protected].

DDeveloper Express has released DXperiencev2008 volume 3, a suite of presentation com-ponents, reporting controls, IDE productivitytools, and business application frameworksfor Visual Studio.

Along with numerous major enhancementsto its existing WinForms and WebForms products and the eXpressApp Framework,DXperience v2008 vol 3 offers a set of newASP.NET controls including a new Gauge Con-trol, Filter Editor Control, Data-Bound ImageControl, and Loading Panel Control. Theupgraded suite also includes a new ASP.NETGrid View, a new HTML Editor for SharePoint,and a new WinForms Alert Window Control. AllDeveloper Express .NET technologies can bepurchased separately or as part of theDXperience Subscription program.

For a complete list of the new controls, features, and options that are available, visithttp://tinyurl.com/5wtqxr.

DXperience v2008 vol 3

Developer Express Inc.

Price: DXperience Enterprise Subscription prices

start at $1,299.99

Web: www.devexpress.com

Phone: 702-262-0609

Isolator and RacerTypemock has announced the release of itsnext-generation unit-testing tools, Isolatorand Racer.

Typemock products support MicrosoftVisual Studio 2005, Visual Studio 2008, andVisual Studio Team System 2008, and workwith any test framework.

DXperience v2008 Volume 3; Isolator and Racer; and TeamCity 4.0

The Typemock Isolator mocking frameworkfor .NET unit testing helps agile developerswith .NET unit testing and test-driven develop-ment. Isolator gives the agile developer toolsto isolate, stub, or mock any class in the system.

Features include the ability to mock the.NET Framework; the ability to mock any .NETlanguage; the ability to mock any class, anyinterface, any constructors, and all instancesof a type; the ability to mock a class whilekeeping its original behavior; the ability todynamically choose at runtime whether tokeep the classes’ original behavior; and more.

Typemock Racer helps find possible dead-locks in production code by allowing developersto write threaded tests to detect possibleproblems. Racer provides a framework APIthat can be used in Parallel Computing tests,which allows the code to be tested for dead-locks in multithreaded code. When Racerdetects a deadlock, the events that lead toit—including thread names and lockedresources—are displayed in Visual Studio’soutput window.

Isolator and Racer

Typemock Ltd.

Price: Contact vendor for pricing

Web: www.typemock.com

Phone: +972-3-681-5177

TeamCity 4.0JetBrains has announced the availability of itscontinuous integration server and distributedbuild management tool, TeamCity. TeamCityautomates routine procedures, aids the soft-ware development process, improves team

communication, and helps dev teams imple-ment agile methodology and best practices.

TeamCity 4.0 provides scalability andextensibility via its Java API, and integrateswith multiple IDEs, version control systems,and build tools. With features such as fastfeedback on build progress, pre-tested com-mits, and server-side code analysis with over600 code inspections, TeamCity shortens thetime needed for introducing new featuresand fixes.

The latest version allows developers tobreak down a single build procedure into sev-eral parts that can be run on different buildagents, in sequence or in parallel, using thesame set of sources. Other features includethe ability to redo any build from a particularversion-control revision; improved agents-authentication mechanics, per-agent CPU-benchmarks, and agents overview statistics foran entire project; new integrations, includingFxCop and a dedicated Rake runner, as well asimprovements for old ones such as MSTest;and improved Eclipse integration.

TeamCity 4.0

JetBrains

Price: Professional Edition (up to 20 users) is

free; Enterprise Edition prices start at $1,999

Web: www.jetbrains.com

Phone: 650-378-8571

0109vsm_FirstLooks_08-09.v8 12/15/08 9:30 AM Page 8

Page 11: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

P R O D U C T L I S T I N G S + R E V I E W S

VisualStudioMagazine.com · January 2009 · VISUAL STUDIO MAGAZINE 9

IIf you’re building a complex appli-cation or working as part of a team, DevPartner Studio fromCompuware Corp. gives you theability to understand just howgood—or bad—your applicationreally is. DevPartner Studio inte-grates with Visual Studio to giveyou tools for analyzing applicationperformance, determining mem-ory usage (down to the memoryused by individual objects), scan-ning for security problems, andreviewing source code. Additonally,DevPartner integrates well withVisual Studio 2008 (Visual Studio2005 is also supported), givingyou access to all of its function-ality through a single toolbar.

If you’re working in a team environment, a source code ana-lyzer provides the most effective way to ensure that you—andthe rest of the team—are following organization standards andbest practices. Studio will do a static analysis of your sourcecode, comparing it against a database of more than 600 rules.If you don’t like the rules that come with Studio, you can cus-tomize the rules database, though you’ll need some knowledgeof regular expressions if you want to add new rules. Addition-ally, source code analysis can be time consuming. Analyzing asolution containing several thousand lines of code spreadacross an ASP.NET application, a Windows Service, and severalclass libraries took more than an hour on my computer.

When runtime performance is critical, you need the abilityto identify the bottlenecks in an application and determine theimpact of any enhancements you make. Studio’s PerformanceAnalyzer and Performance Expert lets you monitor your appli-

cations as they run in Visual Studio and report on which methodsare called, how often they’re executed, and where your appli-cation is spending its time. In addition to a detailed set ofpost-performance reports—which you can save to reviewlater—Studio also includes a live runtime graph that tracks keyperformance metrics as your application executes.

The only real limitation on Performance Analyzer is that itrequires a custom runtime manager that doesn’t support allapplication types. For example, ASP.NET isn’t supported. Providedyou keep most of your code—and all of your performance-criticalcode—in middle-tier business objects, you can still use Studio toanalyze your code as long as you’re willing to knock togethersome WinForms applications to exercise your objects.

None of this comes cheap. In addition to the purchaseprice—obviously aimed at larger shops—you’ll need a computerwith sufficient resources to run the tools. When I tried usingPerformance Analyzer in a virtual machine with only onegigabyte of memory, DevPartner failed with a memory cor-ruption problem.

That said, I found DevPartner to be a well-behaved addi-tion to Visual Studio. When working on projects where I didn’twant to use DevPartner, it stayed out of my way. Even whenDevPartner crashed due to memory restrictions, it left VisualStudio running and allowed me to continue working.

If you’re building an application that’s too big to hold in yourhead at once—or if you’re working in a team environment whereadhering to standards is important—you need DevPartner. VSM

Peter Vogel is a .NET consultant, author and instructor living in

Goderich, Ontario.

Understand What Your App Does

DRILL DOWN ON APPS WITH PERFORMANCE ANALYSIS.Compuware’s DevPartner is a comprehensive set of testing and performance analysistools. Depicted here is the live graph generated by the Studio’s Performance Analyzertool; it tracks CPU usage, disk transfers, and network access.

AT A GLANCE

DevPartner Studio Professional Edition 9.0Compuware Corp.Web: www.compuware.comPhone: 800-521-9353Price: $2,400Quick Facts: Suite of tools for static and runtime analysisof applications for both Visual Studio 2005 and 2008.Pros: Highly functional; well integrated into Visual Studio; good product support.Cons: Expensive; no direct support for ASP.NET performance testing; 2GB of memory required.

0109vsm_FirstLooks_08-09.v8 12/15/08 9:30 AM Page 9

Page 12: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

M V C F R A M E W O R K

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com10

perform unit tests of the presentation layer muchmore easily. I’ll show you how to take advantageof both these features, first walking you throughhow to build an MVC application from scratchthat features a true separation of concerns, andthen show you how to perform unit tests againstthat same application.

In any object-oriented application, sepa-ration of concerns is one of the most importantaspects of a clean design. One of the fundamentalobject-oriented concepts is that a class shouldhave a single job. The purpose of a class becomesunclear when it contains too many members ormethods with different responsibilities. The

“Extract class” refactoring (Fowler, 1999) is oneof the most fundamental refactorings that cur-rently exist to address this situation. TheExtract class seeks to break apart the originalbloated classes into multiple classes, each withits own distinct purpose.

Traditional ASP.NET Web forms applica-tions have suffered from this age-old problem of alack of clean separation of concerns because thecode behind class often becomes a dumpingground for both business logic and presentationlogic. The business logic might consist of gettingthe appropriate business objects from the datalayer, executing business rules for validation, or

The new ASP.NET Model-View-Controller (MVC) frameworkfrom Microsoft offers many new features for Web developers,buttwo features stand out above the others.The first is that the MVC

now facilitates “separation of concerns.” The second is that the MVCframework,unlike traditional Web forms,enables the developer to

ILLU

ST

RA

TIO

N B

Y R

YAN

ET

TE

R

TECHNOLOGY TOOLBOX

VB.NET

C#

SQL Server

ASP.NET

XML

Other: MVC Framework

F E AT U R E

Microsoft’s Model-View-Controller framework makes it possible to implement “a separation of concerns” in ASP.NET—something that was difficult, if not impossible, previously.Learn how to take advantage of MVC to design better Web apps that separate their architectural elements—the UI,business logic, and code—properly, as well as how to reviewwhat you create with unit testing. BY STEVE MICHELOTTI

Partition Web Apps Intelligently

0109vsm_F1WebApps_10-20.v8 12/15/08 9:26 AM Page 10

Page 13: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

M V C F R A M E W O R K

VisualStudioMagazine.com · January 2009 · VISUAL STUDIO MAGAZINE 11

ILLU

ST

RA

TIO

N B

Y R

YAN

ET

TE

R

business processing on those objects. The presentation logic mightconsist of populating form controls,handling events for form controls,redirecting users to other Web pages, and so on. All of this code cancause the code behind classes to become bloated,with no clear job.

The MVC framework solves the separation of concerns prob-lems of traditional Web forms by partitioning responsibilitiesbetween Models, Views, and Controllers (see Figure 1). Note thatthe Model is unaware of both the Controller and the View. The pri-mary job of the Model is to contain the state that’s passed to thepresentation layer. The View knows about the Model, but is bliss-fully unaware of the Controller. The sole purpose of the View is tocontain presentation logic. Finally, the responsibility of the Con-troller is to interact with the data layer and provide the appropriateModels to the appropriate Views. The Controller is the key interac-tion point in the MVC framework.

Creating the AppBefore drilling down into the specifics of the MVC implementation,let’s take a step back and consider the details of a sample applicationthat shows off this feature.The app is the Contact module of a personal-information manager such as Outlook. It needs two screens.The firstscreen shows the list of all my contacts (see Figure 2,p.14). It lets youdelete any contact,as well as provide links to edit any contact and addnew contacts. If the user selects a contact or clicks on the link to add anew contact, the application sends the user to the second screen,where the user can add or edit the contact details (see Figure 3 ,p.14).

The MVC framework utilizes a rich routing engine providedby the System.Web.Routing assembly. The routing engine enablesthe ability to use URLs that don’t map to a physical file. In thecontext of MVC, the most common pattern for this is “{con-troller}/{action}/{id}”. For example, an MVC page that invokesthe ContactController’s Create() action method for a given IDmight look like this:

http://somedomain/Contact/Create/21

The routing framework is extremely flexible, and the route map-pings are set up in the Global.asax file.A full discussion of the routingframework is beyond the scope of this article, but it’s important tonote that this basic pattern is used throughout this article.

To implement a Controller class, you must inherit from Sys-tem.Web.Mvc.Controller. Any public method in your Controllerthat returns a derivative of ActionResult is a valid Controller Actionmethod. Based on the first screen defined, you need Controlleractions to display a list of contacts,delete a contact,and send users tothe contact details screen to add or modify a contact.

A Controller action to save the contact is also required for thecontact details screen. This code provides the ContactControllerclass definition:

public class ContactController : Controller

{public ViewResult Index();public ViewResult Create(int? id);public RedirectToRouteResult Delete(int id);public ActionResult Save(Contact contact);

}

The ContactController interacts with the data layer to send andreceive the appropriate objects to the data repository. The data layercontains a class called ContactManager that implements an inter-face called IContactManager:

public interface IContactManager{

IEnumerable<GetContactListResult> GetContactList();IEnumerable<State> GetStates();Contact GetContact(int contactID);void SaveContact(Contact contact);void DeleteContact(int contactID);

}

A detailed discussion of the data layer is beyond the scope of thisarticle, but it’s important to note that the presentation layer workson the IContactManager abstraction of the data layer.Although thedata layer is using LINQ to SQL, the presentation layer is blissfullyunaware of this fact and requires no reference to theSystem.Data.Linq assembly. In fact, the LINQ data context class isinternal to the assembly, and the presentation layer can’t access it.

The next step is to display the list of contacts when the usernavigates to the main contacts screen. The first action method toaccomplish this looks like this:

public ViewResult Index()

FIGURE 1 Model-View-Controller (MVC). The Model is unaware ofboth the View and the Controller. The Controller is the heart of the MVC framework orchestrating the flow. The View is aware of how topresent the Model.

0109vsm_F1WebApps_10-20.v8 12/15/08 9:26 AM Page 11

Page 14: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

UGLY, FIRE-BREATHING SCHEDULE?GET A FLYING START.

UGLY, FIRE-BREATHING SCHEDULE?GET A FLYING START.

Project5 12/11/08 4:26 PM Page 1

Page 15: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

Your challenge: over-deliver on features, while

beating deadlines. Defy it: start with Visual Studio®

Tools for Microsoft® Offi ce for apps that win the day.

More tips and tools at defyallchallenges.com

Project5 12/11/08 4:33 PM Page 2

Page 16: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

M V C F R A M E W O R K

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com14

{IEnumerable<GetContactResult> contactList = contactManager.GetContactList();ViewData.Model = contactList;return View(“Index”);

}

This method is quite simple, but there are some important thingshappening. First, this code is getting the list of contacts from thedata layer. Next, it sets that collection as the Model of the Con-troller’s ViewData. This ViewData is passed to the View. Finally,the returned View is called “Index.”The MVC framework searchesfor a physical file called Index.aspx or Index.ascx in the folder thatcorresponds to the Controller name or the Shared folder. If youomit the Index name parameter to the View method, it looks auto-matically for a View that has the same name as the current actionmethod name (Index, in this case). However, you should avoiddoing this because you want your code to be as explicit and testableas possible.

Now you want to implement the view. Begin by inheritingfrom ViewPage:

public partial class Index : ViewPage<IEnumerable<Contact>>

Note that the Index View page specifies a generictype constraint.This lets you access the Model ina strongly typed manner (see the completeimplementation of the Index View page in Listing1, p. 15). The first aspect that often throws tradi-tional ASP.NET developers is that there are noserver controls in the markup. This is an inten-tional part of the MVC framework. In theMVC framework, there are no ViewState orrunat=“server” attributes. In traditionalASP.NET applications, the server controls pro-vide abstractions over HTML elements. Forexample, an ASP.NET Label server control ren-

ders itself as an HTML <span> tag when sent tothe browser. Alternately, the MVC frameworkgives the developer complete control over therendered HTML with no bloated ViewState.

A link must be available for the user toclick on, so the user can go to the details page tocreate or edit a contact. Specifically, you mustinvoke the ContactController’s Create()method. You can accomplish this with theActionLink method of the HtmlHelper:

<%=Html.ActionLink<ContactsController>(c=> c.Create(contact.ContactID), "Edit")%>

Using a C# 3.0 lambda expression lets you specify the stronglytyped method for invoking the Create. Similarly, you can use aDelete link in the same fashion:

<%=Html.ActionLink<ContactsController>(c=> c.Delete(contact.ContactID), "Delete") %>

Once the user selects a specific contact, they must be sent to the con-tact details screen so that modifications can be made. There are twopieces of data that the screen requires. First, the appropriate contactobject needs to be available.Second, the screen must provide a drop-down list of U.S. states that the user can pick from. How do bothpieces of information get sent to the View as a single Model? Youaccomplish this by creating a simple wrapper class called Con-tactViewData that acts as your Model. It’s a common misconceptionto think of the business objects as the Model in the ASP.NET MVCframework. This is sometimes true, but it’s not always accurate. TheModel is actually whatever abstraction is needed for the presentationlayer to accomplish its objective properly. This is quite often morethan business objects.This code describes the complete implementa-tion of the ContactViewData class:

FIGURE 2 Main Contact Screen. Shows a list of contacts that can be selected for editingor deleting. The screen provides a link to add a new contact. Action Links are utilized on thisscreen for invoking Controller action methods.

FIGURE 3 Contact Details Screen. Detail screen where contacts can be edited and thenpersisted. Validation messages are present for each control based on business object validation. The results are posted to the Controller’s Save action method.

0109vsm_F1WebApps_10-20.v8 12/15/08 9:26 AM Page 14

Page 17: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

VisualStudioMagazine.com · January 2009 · VISUAL STUDIO MAGAZINE 15

M V C F R A M E W O R K

public class ContactViewData{

public Contact Contact { get; set; }public IEnumerable<State> StateList { get; set; }

public ContactViewData(Contact contact,IEnumerable<State> stateList){

this.Contact = contact;this.StateList = stateList;

}}

Using the Create action method isn’t complicated if you takeadvantage of the ContactViewData:

[AcceptVerbs(HttpVerbs.Get)]public ViewResult Create(int? id)

{if (id.HasValue){

Contact contact = contactManager.GetContact(id.Value);

IEnumerable<State> stateList = contactManager.GetStates();

this.ViewData.Model = new ContactViewData(contact, stateList);

return View(“Create”);}else{

return View(“Create”, new ContactViewData(new Contact(), contactManager.GetStates()));

}}

Again, the markup in the View is simple and straightfor-ward. Additionally, there’s no code required in the codebehind. (See Listing 2, p. 18, for the complete code forthe Create.aspx page.)

One thing of note in Listing 2 is the Contact-Controller’s Save action method. There are variousways to save form data in the MVC framework. Oneof the most elegant methods is to utilize ModelBinders. Using Model Binders, which implement theSystem.Web.Mvc.IModelBinder interface, means theact of creating an object from form parameters can beencapsulated in the binders and abstracted awayfrom the Controller actions methods. This allows theController action methods to save objects stronglytyped for that method. That is, the resulting objectfrom the binder will be passed in to the appropriateController method for saving.You can find the com-

plete code for the ContactBinder in the code download for thisarticle (see Go Online, p. 18, for download details).

In this scenario, the first job of the Save method is to validate theobject by invoking the validation rules defined in the business layer. Ifthe object is valid, you send it to the data layer for persistence andthen redirect the user back to the main screen. Otherwise, you needto show the user the form again, so they can fix the invalid data.

Best practices dictate that validation of business objectsshould occur in the business layer. Too often, developers imple-ment the validation only in the presentation layer,or worse,duplicatethe validation of their business objects in the presentation layer. Agreat framework to validate business objects declaratively is theMicrosoft Enterprise Library Validation Application Block (VAB).The VAB allows you to validate your business objects on the objectsthemselves. Another great aspect of MVC is that it provides a flexi-ble framework to hook the UI validations into already existingobject validations. The VAB is simply one of the many frameworks

LISTING 1 This is the complete mark up for the contact list screen.

C# CREATE THE CONTACT LIST SCREEN

<%@ Page Title="Contacts" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Pim.Web.Views.Contacts.Index" %>

<%@ Import Namespace="Pim.Web" %><%@ Import Namespace="Pim.Web.Controllers" %><%@ Import Namespace="Pim.BusinessLayer" %>

<asp:Content ID="Content2" ContentPlaceHolderID="mainContent" runat="server"><%=Html.ActionLink<ContactsController>(c => c.Create(null), "Add New Contact") %>

<table cellspacing="0" cellpadding="4" border="1"><tr>

<th scope="col">First Name</th><th scope="col">Last Name</th><th scope="col">Email</th><th scope="col">&nbsp;</th>

</tr>

<%foreach(GetContactListResult contact in this.ViewData.Model) { %><tr>

<td><%=contact.FirstName %></td><td><%=contact.LastName %></td><td><%=contact.Email%>&nbsp;</td><td>

<%=Html.ActionLink<ContactsController>(c => c.Create(contact.ContactID), "Edit")%>

<%=Html.ActionLink<ContactsController>(c => c.Delete(contact.ContactID), "Delete") %>

</td></tr>

<% } %></table>

</asp:Content>

0109vsm_F1WebApps_10-20.v8 12/15/08 9:27 AM Page 15

Page 18: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

Grids • Char t ing • Repor t ing • S chedul ing • Menus and Toolbars • R ibbon • Data Input • Editors • PDF

1.800.858.2739 or 1.412.681.4343ComponentOne Sales © 1987-2009 ComponentOne. All rights reserved.

iPhone is a trademark of Apple Inc. All other product and brand names are trademarks and/or registered

trademarks of their respective holders.

NEW Studio for ASP.NETCOMPLETELY RE-ENGINEERED

• Fully exploits the AJAX Framework

• Rich client-side object model

• 3x smaller footprint

• 10x faster performance

• Cross-browser support

• Built-in visual styles and animation effects

Coming Soon Studio for iPhoneFIRST SUITE OF IPHONE-ENHANCED WEB CONTROLS

• The first and only ASP.NET component suite that enables you to build iPhoneWeb apps that look and feel like the native UI

• Includes design elements for menus, UI buttons, content controls, sliders, and more

NEW Studio for SilverlightNOW INCLUDES 30+ SILVERLIGHT CONTROLS

• Display rich, interactive geographical informationusing C1Maps

• Create full-featured, animated data visuals withC1Chart

• Develop complex dashboards easily withC1LinearGauge and C1RadialGauge

• Cross-browser support

• Incorporate powerful, data-bound grids to yourapplications with C1DataGrid

Project7 12/15/08 1:21 PM Page 1

Page 19: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

ved.duct ered ders.

componentone.com/amazingwebDOWNLOAD YOUR FREE TRIAL @

WinForms • WPF • ASP.NET • Silverlight • iPhone • Mobile • ActiveX

It's here and supercharged for the Web: Studio Enterprise 2008 v3.This new release delivers exactly what you need to produce next-generation UIs for the Web.

Project7 12/15/08 1:21 PM Page 2

Page 20: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

M V C F R A M E W O R K

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com18

CREATE THE EDIT CONTACTS VIEWC#

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Create.aspx.cs" Inherits="Pim.Web.Views.Contacts.Edit" %>

<%@ Import Namespace="Pim.Web" %><%@ Import Namespace="Pim.Web.Controllers" %><%@ Import Namespace="Pim.Mvc.Web.Models.Home" %>

<asp:Content ID="Content2" ContentPlaceHolderID="mainContent" runat="server">

<form id="mainForm" name="mainForm" action="<%=Url.Action("Create") %>" method="post"><table><tr><td><table><tr>

<td>First Name:</td><td>

<%=Html.TextBox("Contact.FirstName")%><%=Html.ValidationMessage("Contact.

FirstName") %></td>

</tr><tr>

<td>Last Name:</td><td>

<%=Html.TextBox("Contact.LastName") %><%=Html.ValidationMessage(

"Contact.LastName")%></td>

</tr><tr>

<td>Email:</td><td>

<%=Html.TextBox("Contact.Email")%><%=Html.ValidationMessage(

"Contact.Email")%></td>

</tr><tr>

<td>Company:</td><td>

<%=Html.TextBox("Contact.Company")%><%=Html.ValidationMessage(

"Contact.Company")%></td>

</tr><tr>

<td>Title:</td><td>

<%=Html.TextBox("Contact.Title")%><%=Html.ValidationMessage(

"Contact.Title")%></td>

</tr></table></td>

<td valign="top"><table><tr>

<td>Street Address:</td><td>

<%=Html.TextBox("Contact.Address.StreetAddress")%>

<%=Html.ValidationMessage("Contact.Address.StreetAddress")%>

</td></tr><tr>

<td>City:</td><td>

<%=Html.TextBox("Contact.Address.City")%><%=Html.ValidationMessage(

"Contact.Address.City")%></td>

</tr><tr>

<td>State:</td><td>

<%=Html.DropDownList("(Select)", "Contact.Address.StateID", new SelectList(this.ViewData.Model.StateList, "StateID", "StateDesc", ViewData.Model.Contact.Address.StateID)) %>

<%=Html.ValidationMessage("Contact.Address.StateID")%>

</td></tr><tr>

<td>Zip:</td><td>

<%=Html.TextBox("Contact.Address.Zip")%>

<%=Html.ValidationMessage("Contact.Address.Zip")%></td>

</tr></table></td>

</tr></table>

<a href="javascript:document.mainForm.submit();">Save</a>

<%=Html.ActionLink<ContactsController>(c => c.Index(), "Cancel") %>

<%=Html.Hidden("Contact.ContactID") %><%=Html.Hidden("Contact.LastUpdated",

ViewData.Model.Contact.LastUpdated.ToString("MM/dd/yyyy HH:mm:ss.fff"))%>

</form></asp:Content>

LISTING 2 The code for the edit contacts view is simple and straightforward.

0109vsm_F1WebApps_10-20.v8 12/15/08 9:27 AM Page 18

Page 21: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

VisualStudioMagazine.com · January 2009 · VISUAL STUDIO MAGAZINE 19

M V C F R A M E W O R K

that can be used to integrate with MVC validation; validating withthe VAB and redisplaying the view with all appropriate messages isstraightforward (see Listing 3).

Implement Unit TestingOne of the most problematic areas of traditional ASP.NET Webforms is their lack of “testability.” Among these issues is a lack ofHttpContext when a Web server isn’t present. Fortunately, theMVC framework provides an HttpContextBase class that lendsitself well to mocking in the context of unit-testing frameworks.Additionally, quality unit tests ensure that only small units oflogic are tested in each test. However, the lack of separation ofconcerns in traditional ASP.NET Web forms makes this quite dif-ficult. The MVC architecture is based on a pluggable model, so it’seasy to utilize Dependency Injection to facilitate more granularunit tests.

Proper Test-Driven Development (TDD) principles state thatunit tests should be written before actual application code. I’ve vio-lated that principle in this article solely for the purpose of introducingthe MVC framework.The beauty of MVC is that it allows unit tests tobe written first in accordance with true TDD best practices.

This article uses MSTest for unit testing, but you could useany unit-testing framework, including NUnit, xUnit, or MBUnit.I highly recommend you select the unit-testing framework thatyou and your development team are most comfort-able with.

This article also uses Moq for a mocking frame-work, but again, you could use any mocking framework,including Rhyno Mocks or TypeMock. MVC puts noconstraints on the personal preference of a developerwith respect to using their preferred tools.

The first unit test you create is for the mainscreen. Specifically, the unit test must verify the logicin the ContractController’s Index method. The job ofthe Index method is to retrieve the collection from thedata layer and then pass that collection to the Indexview. However, it’s important that only the code in theController is tested and not the code in the data layer.Therefore, the data layer will be “mocked”so that onlythe code in the Controller is being tested. Here’s thecomplete unit test for the Index method:

[TestMethod]public void ContactController_Index_Test(){

// set upvar contactManager =

new Mock<IContactManager>();IEnumerable<GetContactListResult>

contactList = TestUtil.CreateContactList();

contactManager.Expect(c => c.GetContactList()).Returns(contactList);

// execute

ContactsController controller = new ContactsController(contactManager.Object);

ViewResult result = controller.Index();// verifyIEnumerable< GetContactListResult >

viewDataModel = result.ViewData.Model as IEnumerable<GetContactListResult>;

Assert.IsNotNull(viewDataModel, "ViewData should not be null.");

Assert.AreEqual(4, viewDataModel.Count(), "View data must have items.");

contactManager.VerifyAll();}

The Controller contains a reference to the IContactManager inter-face rather than the concrete ContactManager itself, so you can usedependency injection to pass in a mock contact manager.

Taking a slightly more complex example, a unit test is requiredto test the Save functionality.Specifically, if a valid object is passed intothe Save method,the unit test must verify that the data persistence wasinvoked and the user was redirected back to the main screen. Simi-larly, a separate unit test must verify that, if an invalid object is passedin, the validation messages are added and the screen is redisplayed.This code shows you how to test for saving a valid contact:

LISTING 3 Microsoft’s Microsoft Enterprise Library Validation Application Block (VAB)gives you a great way to validate business objects. This code shows you how to usethe VBA to redisplay the page with error messages.

C# VALIDATE OBJECTS WITH VAB

[AcceptVerbs(HttpVerb.Post)][ActionName(Actions.Create)]public ActionResult Save(Contact contact){

ValidationResults validationResults = Validation.Validate(contact);

if (validationResults.IsValid){

contactManager.SaveContact(contact);return RedirectToAction(Actions.Index);

}else{

foreach (ValidationResult validationResult in validationResults)

{string mvcKey = GetMvcKey(validationResult);this.ViewData.ModelState.AddModelError(

mvcKey, validationResult.Message);}IEnumerable<State> stateList = contactManager.GetStates();

this.ViewData.Model = new ContactViewData(contact, stateList);

return View(Actions.Create);}

0109vsm_F1WebApps_10-20.v8 12/15/08 9:27 AM Page 19

Page 22: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

� dozens of indexed, unindexed, fielded data and full-text search options (including Unicode support for hundreds of international languages)

� file parsers / converters for hit-highlighted display of all popular file types

� Spider supports static and dynamic web data; highlights hits while displaying links, formatting andimages intact

� API supports .NET, C++, Java, databases, etc. New .NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrieval®

since 1991

1-800-IT-FINDS • www.dtsearch.com

� “Bottom line: dtSearch manages a terabyte of text in a single index and returns results in less than a second” – InfoWorld

� “For combing through large amounts of data,” dtSearch “leads the market” – Network Computing

� dtSearch “covers all data sources ... powerful Web-based engines” – eWEEK

� dtSearch “searches at blazing speeds” – Computer Reseller News Test Center

See www.dtsearch.com for hundreds more reviews, and hundreds of developer case studies

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CD/DVDsPublish for CD/DVDsPublish for CD/DVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win & .NETEngine for Win & .NETEngine for Win & .NET

New64-bitNew64-bit

[TestMethod]public void ContractController_Save_Valid_Test(){

// set upContact contact = TestUtil.CreateValidContact();var contactManager = new Mock<IContactManager>();var mockedHttpContext =

MoqMvcMockHelpers.FakeHttpContext();ContactsController controller = new

ContactsController(contactManager.Object);controller.ControllerContext = new

ControllerContext(mockedHttpContext, new RouteData(), controller);

contactManager.Expect(c => c.SaveContact(contact));

// executevar result = controller.Save(contact) as Redirect-

ToRouteResult// verifyAssert.AreEqual("Index", result.Values["action"],

"ViewName is not correct.");contactManager.VerifyAll();

}

You can find the complete unit-testing implementation for theentire application in the accompanying code download for thisarticle (see Go Online for details). One nice aspect of the MVCframework’s architecture is that it’s completely pluggable, with sep-aration of concerns implemented elegantly. It was designed withtestability in mind throughout.This in turn lets you to write higher-quality code. VSM

Steve Michelotti, MCSD, MCPD, MCT, is a principal software engineer at Applied Information Sciences.You can reach him [email protected].

ADDITIONAL RESOURCES:

Stephen Walther on ASP.NET MVC: http://tinyurl.com/57d9ba

Scott Guthrie’s Blog: http://tinyurl.com/5d6a6f

ASP.NET MVC: www.asp.net/mvc

MVC on CodePlex: http://tinyurl.com/6ky4vp

Scott Hanselman’s Blog: http://tinyurl.com/6gk2qh

ASP.NET MVC Session at Mix08, TDD and MvcMockHelpers. Blog post byScott Hanselman: http://tinyurl.com/39qpnp

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to go directly to theserelated resources.

READ & DOWNLOAD

VS0901SM Read this article online and download a sample MVC applicationthat shows separation of concerns implemented properly.

M V C F R A M E W O R K

0109vsm_F1WebApps_10-20.v8 12/15/08 9:27 AM Page 20

Page 23: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

Many developers have the misconception that targeting older versions ofthe Framework means youcan’t use any of the new C#language features. It’s timeto dispel that myth.BY BILL WAGNER

Targeting multiple .NET platforms is a subject that confuses many developers.For example,many developers mistakenly believe that if you target older versions of the platform,you must forego all the new language features.Yes, you must accept some limitations,but you don’t have to give up all the new language features you like. Targeting multipleversions of the Framework is a great way to ensure that you and your peer developers

can use Visual Studio 2008 even when one of your target environments must support an older version ofthe Framework. More than that, it doesn’t stop you from using the features in the C# 3.0 language. Onthe downside, there are some nuances that can crop up when using the newer language features if you’retargeting an older version of the Framework. I’ll walk you through some of these nuances, explainingwhat capabilities are in bounds, which require care, and which ones you can’t use when you have to targetan older version of the Framework.

Multitargeting is a project-level feature. To select your target version of the Framework, right clickon the project node and select properties.You can pick any of the 2.0, 3.0, or 3.5 versions of the Frame-work. In this article, I’m concentrating on the differences between various language features and howyou can make use of the newer language features even though you’re targeting an older version of theFramework. Obviously, if you’re targeting the 2.0 Framework, none of the 3.0 libraries—Windows Presentation Foundation (WPF),Windows Communication Foundation (WCF),or Windows WorkflowFoundation (WF)—are available to use. In general, other libraries that rely on .NET 2.0 and 3.0 sharethe same limitations. (Space considerations prevent me from exhaustively discussing the differencesbetween the 2.0 and 3.0 Frameworks.)

C # CO R N E R TA R G E T M U LT I P L E F R A M E W O R K S

Target Multiple.NET Frameworks

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com 21

ILLU

ST

RA

TIO

N B

Y B

RU

CE

GA

RD

NE

R

TECHNOLOGY TOOLBOX

VB.NET

C#

SQL Server

ASP.NET

XML

0109vsm_C#Corner_21-23.v8 12/15/08 9:09 AM Page 21

Page 24: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

C # C O R N E R » TA R G E T M U LT I P L E F R A M E W O R K S

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com22

The most important consideration when multitargeting is touse straight language features versus the library features. Of course,there are some subtleties.You can use any of the language featuresin C# 3.0, provided they don’t access the 3.5 libraries. This is alsotrue when using C# 3.0 when you’re targeting the 2.0 Framework:

var foo = 27;

That’s really no big deal,but it might lead you to try more.Object andCollection initializers work even when you target the 2.0 Framework:

List<int> sample = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

You can even use lambda expressions:

sample.RemoveAll(n => n % 3 == 0);

Lambda expressions mean you can apply those techniques to yourown methods. You can create any of your own methods that takedelegates, knowing that clients can take advantage of the easierlambda expression syntax to use your types.

You can create and use Anonymous types,though without LINQsupport, there’s less you can do with them than you might think.

Obviously,you can’t use LINQ libraries.LINQ to SQL,LINQ toXML, and Entity Framework are all part of the .NET 3.5 library, sothose are off limits if you’ve targeted an older version of the Framework.

Extension methods are decorated with the System.Compil-erServices.Extension attribute,which is declared in System.Core.dll.That’s not available in earlier versions of the .NET Framework, soyou can’t create extension methods when you’re targeting an earlierversion of the Framework.

I mentioned there are some nuances that you need to keep inmind when you target earlier versions of the Framework. Take amoment and consider what would happen if you tried to executethis code snippet:

People folks = new People() {new Person {FirstName = "Joe", LastName = "Smith"},new Person {FirstName = "Bob", LastName = "Jones"},

};var foo = from f in folks

select f.FirstName;

What would happen depends on what methods are defined in thePeople class. The select keyword—in fact, the entire query-patternsyntax—maps to specific methods. The compiler then translatesthose keywords into method calls. If a candidate method is in scope,the query will compile, even if you’re targeting the 2.0 Framework.

This is where it gets a bit complicated so let’s take a close lookat another example. The select clause in the snippet just describedlooks for a Select method in scope. The People class contains a pos-sible Select method:

public IEnumerable<TResult> Select<TResult>(Func<TResult> selector)

{foreach (var peep in storage)

yield return selector(peep);}// elsewhere:public delegate TResult Func<TResult>(Person id);

The select member method in People satisfies the query-expressionpattern for the case where the sequence is of type People so therange variable must be of type Person. I had to define a new versionof Func, because Func<TResult> is not available in the .NET 2.0 Framework.

I intentionally chose a simple example because implementingthe entire query-expression pattern is a large exercise, and I’m notadvocating it if you still have to support the 2.0 Framework. Thisamount of work would dwarf the amount of work necessary torollout the 3.5 Framework in almost any customer base. However,it’s important to understand that the query expression syntax isshorthand for method calls.

According to the C# spec, the Select method should have a sig-nature of the form:

public C<T> Select<U>(Func<T,U> selector)

That’s a mouthful of type parameters, so let’s start with a concreteexample. The select statement above looks for a method that hasthe form:

public IEnumerable<string> Select(Func<string, Person> selector);

The Select method in People does match that pattern. Therefore,the select compiles. The compiler translates it into this method call,which makes the method call a little easier to understand:

var foo = folks.Select(person => person.FirstName);

What you want to remember from this discussion is that the queryexpressions are nothing more than shorthand for method calls.Where those method calls are present, the query syntax will workfine when targeting the .NET 2.0 Framework. However, to writecode like this in a general way is to create far more work for yourselfthan would normally be justified.

Changes in BehaviorYour development box must have .NET 3.5 if you’re runningVisual Studio 2008, as well as the C# 3.0 compiler. This combina-tion can lull you into a false sense of security.Your testing on yourdevelopment machine will not uncover any incompatibilitiesbetween the 2.0 and 3.5 Frameworks. The Visual Studio IDE willhelp you with almost all of those issues, because the IDE will tell

0109vsm_C#Corner_21-23.v8 12/15/08 9:09 AM Page 22

Page 25: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

C # C O R N E R » TA R G E T M U LT I P L E F R A M E W O R K S

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com 23

you if you’re trying to include any assemblies that were added in anewer version of the .NET Framework. Microsoft tried hard toensure that there were no breaking changes, but a few things stillsnuck in.

You can find one example of this partic-ular issue in the INotifyPropertyChanginginterface. In .NET 3.5, the System.Compo-nentModel namespace added the INoti-fyPropertyChanging interface. This interfaceis new and corresponds to the INotifyProp-ertyChanged event. The problem—for amultitargeting application—is that this eventwill compile fine when targeting the 2.0Framework. It’s in an existing namespace andan existing assembly. In fact, it will run onyour development machine, but it will failwhen you move to a machine where only the2.0 Framework is available. Fortunately,that’s the only example of this kind of problemthat I’ve encountered so far, but it’s the kindof problem you will only find by testing on amachine where the target framework—andonly the target framework—is installed.

I’ve always viewed multitargeting as ashort-term solution to enable developers tomove forward, while still supporting cus-tomers that aren’t ready to move to the latestdistributions. If you view it in this light, youcan safely move development staff to the latestversion of Visual Studio and take advantage ofsome of the newer language features while stillsupporting those customers that must run onolder legacy systems. The goal of such a moveshould be to get customers and developerslooking at the higher productivity available inthe newer versions of the .NET Frameworkand to ultimately drive toward targeting thenewest Framework. VSM

Bill Wagner brings more than 20 years experi-ence to his roles as co-founder of SRT Solutionsand Microsoft Michigan regional director. Billis an internationally recognized author on theC# language evolution, Smart Clients, andenterprise design. Bill has written two books,“Effective C#” (Addison-Wesley Professional,2004) and “More Effective C#” (Addison-Wesley Professional,2008).He also annotated the3rd edition of the “C# Language Specification.”

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.comto go directly to these related resources.

READ & DOWNLOAD

VS0901CS Read this article online and download the sample code, which illustrates many of the concepts discussed in this article.

The .NExT Step In Document

and Photo Imaging

www.atalasoft.com

New features to our already powerful imaging toolkit include PDF/A

support, AJAX Vector Annotations including FreeHand, WPF annota-

tions, and more. Use templates in our AJAX Wizard to create zero-

footprint web applications in C# and VB.NET—Take document and

photographic imaging to the .NExT step.

Visit Atalasoft.com for web demos, video tutorials, and a free trial.

Atalasoft, Your .NET Imaging PartnerCall us toll free at 866-568-0129

DotImage 7.0—More Powerful,

with Zero-Footprint Imaging, and

3 Months of Free Gold Support.

New

DotImage 7.0

Release

0109vsm_C#Corner_21-23.v8 12/15/08 9:09 AM Page 23

Page 26: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com24

BY KATHLEEN DOLLARDWINDOWS WORKFLOWCHANGES DIRECTION

Technologies mentioned in this article include VisualBasic, Windows Workflow Foundation (WF); WindowsPresentation Foundation (WPF), reflection, and C#.

Q I’ve been hearing that Windows Workflow 4.0 wasannounced at the Professional Developers Conference(PDC),and that it “changes everything.”Is this true,and if

so,what does this mean to those of us that have existing workflows?

AWindows Workflow Foundation (WF) 4.0 wasunveiled at PDC and is available now as part of thecurrent .NET 4.0 Community Technology Preview

(CTP). As such, details aren’t complete, so remember that myanswer is based on these preliminary announcements.

WF 4.0 represents a bottom-up rewrite with entirely newthinking.The gains are enormous: custom activities take centerstage, and authoring them is much simpler; workflows areentirely declarative; and there are three workflow flow stylesthat you can combine seamlessly. It’s possible that you couldsee a 10-fold improvement in the time required to create anddebug workflows, in addition to 10- to 100-fold runtime per-formance improvements. You’d also have better control overpersistence. Additionally, there’s support for partial trust, acompletely rewritten designer, and a better debugging experi-ence. One of the most important improvements is in the re-hosting experience. This allows you to create activities andto allow power users—and others—to build or modify work-flows with the constrained set of activities you’ve created.Yes,this is possible in WF 3.0/3.5, but the necessary code is chal-lenging, not to mention exceedingly difficult to debug.

The improvements to WF 4.0 come at a cost. Microsoftdeveloped two inter-op strategies to help you over this hurdle.

WF 3.0/3.5 will remain part of the framework and will runside by side with WF 4.0. This lets you manage the transition ata time that fits your organization’s broader goals. The otherinter-op strategy is an inter-op activity that allows you to useWF 3.0/3.5 activities in a WF 4.0 workflow. Workflows are aspecialization of activities, so you’ll probably be able to runentire 3.0/3.5 workflows inside WF 4.0 workflows.

While side-by-side running is essential for timing yourconversion, you’re likely to skip the inter-op activity in favor ofcreating consistent WF 4.0 workflows. Outside of the inter-opactivity, your workflows, activities, and rules aren’t going totransition to WF 4.0 unless Microsoft creates a transition tool.A transition tool that can fully transform your workflows andactivities seems unlikely. One of the prime benefits of WF 4.0is a better strategy for breaking workflows into discrete func-tional units. Transitioning workflows directly won’t improvetheir design, but rewriting them will.A quick list of significantfeatures Windows Workflow 4.0 doesn’t have includes CodeActivity, Data Exchange Service (DES) events, DES methodcalls, a code model (it’s declarative only), rules as you knowthem now, an Initialize event, and dependency properties.

If you’re contemplating using WF and can wait until .NET4.0 is released, I suggest waiting. This is particularly true if youhave an existing state-based solution you can nurse along foranother year or two.If you do write new workflows in the interim,I’ve collected a set of preliminary guidelines for preparingworkflows to transition (see “Write New Workflows with .NET4.0 in Mind,”p.26). If you’ve worked with WF 3.0 or 3.5, this is ajaw-dropping list; many of the primary elements you mightthink of as WF disappear in the transition to WF 4.0.

Another important aspect of your transition strategyconcerns long-running workflows. The simplest transition

Learn how Windows Workflow Foundation (WF) 4.0 changes everythingyou thought you knew about workflow.Also, learn why using string primary keys is a bad idea; find out where to get a data grid for WindowsPresentation Foundation (WPF); overcome the annoying issue of files notloading at runtime; and copy files into the executable directory.

Ask Kathleen

0109vsm_AskKat.24-27.v6 12/15/08 9:06 AM Page 24

Page 27: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

A S K K AT H L E E N » W I N D O W S W O R K F L O W 4 . 0

VisualStudioMagazine.com · January 2009 · VISUAL STUDIO MAGAZINE 25

strategy is to allow all workflows to complete in 3.0/3.5 but to beginnew workflows in 4.0. If you have aggregate information or if youhave long-running workflows,this might not be an acceptable strategy.In this case, you need a strategy to bring down existing workflowsand bring them back up in WF 4.0. If you’re writing workflows todayand believe you’ll need this strategy, consider building in events toinitiate the process. If you have existing work-flows, you might need to alter them later, butit’s not yet clear whether Microsoft will providea tool to help automate the 3.0/3.5 workflow-modification strategy.

If you have deployed workflows, it’salmost certain you invested most of your timein understanding and engineering the busi-ness process in order to know what workflowsto write,and in working through the dozens ofquirks and challenges of 3.0/3.5 workflows.Creating the workflows themselves probablytook a smaller chunk of time.Certainly,you’llput effort into transitioning your currentworkflows and redesigning aspects of them totake advantage of new features.But your busi-ness engineering work will survive and thesimpler model of WF 4.0—and the significantinput Microsoft received in fixing the issuesthat plagued WF 3.0/3.5—should result in aproduct with fewer quirks to trip you up.

If you’ve deployed workflows and believeyou’ll have a challenging transition, I’d like toknow more about your scenario so we canhelp Microsoft improve the transition experi-ence for you and others.

QHere’s something I’ve had a hardtime understanding: why shouldn’t Iuse string primary keys?

A String primary keys present problems in database integrity,maintainability, and performance.

From a maintainability point of view, stringprimary keys almost always have meaning.Database values with meaning will eventuallychange and wreak havoc on foreign-keyusage. At the least, they change when a data-entry mistake must be corrected. When youmake these kinds of changes, you must alsoupdate all foreign keys.

Few string columns that have a meaningare truly unique. Social Security numbers aretheoretically unique,but data-entry errors andfraudulent usage results in redundant values.This prohibits entry of the second record,regardless of whether the second occurrence isthe legal use of the number. Also, federal law

restricts usage of Social Security numbers, and many applicationscannot legally require submission of a valid Social Security number.

Strings present performance issues because of the inefficiencyof string comparisons and clustering issues. Comparing twostrings is significantly slower than comparing two integers. Withina database index, there are a large number of comparisons, and pri-

Image Formats:

Image Compression:

Display Controls:

Image Processing:

OCR/ICR/OMR:

Barcode:

Forms Recognition and Processing:

Document Cleanup/Preprocessing:

PDF and PDF/A:

Annotations:

Grayscale Imaging:

Medical Web Viewer Framework:

Medical Image Viewer:

DICOM:

DICOM Communications:

WPF (XAML):

AJAX

JPIP

Scanning:

DVD:

Multimedia:

Free 60 Day Evaluation! www.leadtools.com/msdn

800 637-1840

LEADTOOLS SDKs feature LEAD’s iCompress™ Technologies.

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

LEADTOOLS v.16 – .NET, WPF, C API, C++ Class Lib, COM & more!

0109vsm_AskKat.24-27.v6 12/15/08 9:06 AM Page 25

Page 28: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

A S K K AT H L E E N » W I N D O W S W O R K F L O W 4 . 0

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com26

mary key indices are used extensively during normal databaseoperations. Slowing down these comparisons hurts overall data-base performance.

Clustered indexes allow physical organization of an index toimprove performance. Successful clustering relies on intrinsicordering of data and a relatively even spread. Integers provide thisordering and distribution; strings and globally unique identifiers(GUIDs) do not. In the case of GUIDs, just turn off clustering. Inthe case of strings, replace them with a meaningless integer orGUID primary key and add a secondary index on the meaningfulkey. The secondary index can be a unique index and allows rapidretrieval on your meaningful string values while still retainingdatabase maintainability, integrity, and performance.

Q I want to switch to Windows Presentation Foundation(WPF), but I need a data grid. I understand WPF doesn’tinclude a data grid, so what do you suggest I use?

AWPF in .NET 3.0 and .NET 3.5 doesn’t contain a datagrid. However, Microsoft has released the WPF Toolkit,which includes a data grid, calendar control, and date

picker. This toolkit requires WPF 3.5 Service Pack 1 (SP1). Theincluded data grid is fairly full featured,but doesn’t support grouping.If you’re working in .NET 3.0 or 3.5, you’ll need to either performinter-op on the Winforms data grid or use a third-party control.This is another good reason to upgrade to .NET 3.5 SP1.

Q I’m frustrated trying to load an assembly at runtime. Eventhough IO.File.Exists returns true, I get the error:

System.IO.FileNotFoundException: Could not load file orassembly 'RuntimeLoad.dll' or one of its dependencies. Thesystem cannot find the file specified.

I’ve simplified my test code to:

Dim dllName = "RuntimeLoad.dll"Dim assem As Reflection.Assembly = NothingTryassem = Reflection.Assembly.Load(dllName)

Catch ex As ExceptionConsole.WriteLine( _"Assembly failed to load: " & dllName)

ThrowEnd Try

AReflection.Assembly.Load requires the assembly namewithout the DLL extension. Remove this extension fromthe string you pass to the Load method, and test again. If

this doesn’t solve your problem, you should ensure that the file is inthe correct location, which is adjacent to the executable. By default,this is at <project directory>/bin/Debug,where <project directory>is the directory containing your project file (.vbproj).

You can also handle loading assemblies at runtime using System.AddIn.The System.AddIn approach is important in some sce-narios,but it might be overkill for what you’re trying to accomplish.

Q I need to copy some files into the executable directory, butthey aren’t in the project directory so it doesn’t make sense totreat them as resources.We’ve been trying to do this manually,

You can tweak your 3.0/3.5 workflows to make the transitionto Windows Workflow Foundation (WF) 4.0 a little easier. Theseguidelines limit the scenarios in which there’s no correspondingfeature in 4.0.

1. Create custom activities. Create custom activities instead ofcode-beside logic in a CodeActivity. There’s no CodeActivity in WF4.0. Remember that the custom activity model also changes, so it’sbest to move complex code out of the activity into utility librariesor services.

2. Scope tightly. 4.0 variables are more constrained than 3.0dependency properties. They no longer use the propertybag/dependency property approach but instead are scoped ver-tically. Choose a variable in a parent activity set retrieved bychild activities rather than directly retrieving data from a sibling activity.

3. Use Windows Communication Foundation (WCF) messagingwhen there’s a choice. The Data Exchange Service (DES) modelgoes away in WF 4.0: there’s no external event model; externalcommunications is through WCF; and WCF interactions will be con-siderably easier in WF 4.0. For workflows that might transition to4.0, write them in WF 3.5, and use the Send and Receive activities.However, if you don’t yet have WCF in your application or organiza-

tion, implementing it in WCF 3.5 may be onerous. In this case, useevents, and assume you’ll rewrite around the new communica-tions approach.

4. Perform initialization logic in the Activity.Execute method.The signaling model changes in WF 4.0, and there’s noActivity.Initialize event. Any setup should be done in the Activi-ty.Execute method.

5. Use WorkflowInstance.EnqueueOnIdle for queuing. If you’redoing manual queuing, which is relatively uncommon, you shoulduse the EnqueueOnIdle method, as this will be the only queuingmodel supported going forward.

6. Be careful with data. The tracking and persistence databasesare likely to change significantly between 3.5 and 4.0. Holdingdata only in tracking is hazardous, unless you prepare a strategyfor extracting data, such as when a workflow completes. If you’reusing rules for simple data retrieval for values that should be setoutside the workflow, consider holding this data in a configurationfile or database.

Note that these are preliminary suggestions. Check out myblog (http://msmvps.com/blogs/kathleen) for pointers towardsMicrosoft’s formal guidance, as well as tools (as they become avail-able) that will help you transition workflows.

Write New Workflows with .NET 4.0 in Mind

0109vsm_AskKat.24-27.v6 12/15/08 9:07 AM Page 26

Page 29: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

but we’ve made many mistakes related to not copying the updated filesproperly. Is there a way to automate this?

AVisual Studio supports pre- and post-build events, but Ithink it’s easier to modify the project file. The project fileis an MSBuild script, capable of managing complicated

builds. It also makes it easy to handlestraightforward scenarios, such as copyingyour files.

You can edit project files (.csproj and.vbproj) in Notepad or another editor, butediting them within Visual Studio suppliesXML syntax checking and IntelliSense. Toopen your project file in Visual Studio, rightclick on the project, and select “Unload Pro-ject.” Once it is unloaded, right click on itagain, and select “Edit <project file name>.”The only downside of opening projects thisway is that Visual Studio loses its marker tothe startup project if you unload that project.

Scroll to the bottom to find the locationfor one of several well-known targets:

<Target Name="BeforeBuild"></Target><Target Name="AfterBuild"></Target>-->

You don’t need to understand targets orwhy this works to put your pre- or post-build code into the correct location.“Copy”is an MSBuild task with the source file loca-tion relative to the project directory:

<Target Name="BeforeBuild"><Copy SourceFiles="..\RuntimeLoad\bin\Debug\RuntimeLoad.dll" DestinationFolder="$(TargetDir)" />

</Target>

TargetDir is one of many predefined MSBuildproperties. You can see some of the mostcommon properties as macros for the pre-and post-build events by typing $( in Help.VSM

Kathleen Dollard is a consultant, author,trainer, and speaker. She’s been a MicrosoftMVP for 10 years and is an active member ofthe INETA Speakers Bureau. Her blog ishttp://msmvps.com/blogs/kathleen. You canreach her at [email protected].

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to go directly to theserelated resources.

READ MORE

VS0901AK Read this article online.

A S K K AT H L E E N » W I N D O W S W O R K F L O W 4 . 0

VisualStudioMagazine.com · January 2009 · VISUAL STUDIO MAGAZINE 27

0109vsm_AskKat.24-27.v6 12/15/08 9:07 AM Page 27

Page 30: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com28

In this special interview, Microsoft Corporate Vice President Robert Wahbe discusses the Azure ServicesPlatform and Software plus Services applications with1105 Media’s Jeffrey Schwartz and Michael Desmond.

BY JEFFREY SCHWARTZ AND MICHAEL DESMOND

Connect to the Cloud

QTo what extent is Windows Azure based onHyper-V, and to what extent are we looking at awhole new set of technologies?

AWindows Azure is a natural evolution of our plat-form. We think it’s going to have a long-term radicalimpact with customers,partners, and developers,but it’sa natural evolution. It takes what we have today—fromthe phone to the desktop to the server—and brings thatto the cloud. It’s built foundationally on top of WindowsServer 2008 and .NET Framework. We have millions ofdevelopers on top of Visual Studio and on top of .NETFramework, and they can take the vast majority of theirskill set and build apps the way they have been today.They can deploy those on the premises.

Now that Microsoft has rolled out itscloud-computing strategy, the com-pany is hoping developers will start to

explore the Azure Services Platform and thinkabout how to build applications that live in theSoftware plus Services (S+S) world.

A key evangelist on that front is RobertWahbe, corporate vice president of Microsoft’sConnected Systems Division. Wahbe runs thecompany’s engineering teams that are chargedwith delivering its Web services and modelingplatforms. The editors of VSM’s sister publica-tion Redmond Developer News sat down withWahbe at the recent Microsoft ProfessionalDevelopers Conference 2008 (PDC) to discussAzure and what impact it will have on theMicrosoft developer ecosystem.

I N T E R V I E W

Microsoft Corporate Vice President Robert Wahbe

0109vsm_QandA_28-30.v4 12/15/08 9:35 AM Page 28

Page 31: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com 29

C O N N E C T T O T H E C L O U D

Q. So you’re saying developers can write to the Windows cloud, other-wise known as Azure apps, and they’ll run on Windows Server on-premises? That logic can be redeployed to Azure?

AThe key thing—and Ray [Ozzie, Microsoft’s chief software archi-tect] did mention this [during his PDC keynote]—right now, manyapplications aren’t built with the scale-out in mind from the begin-ning. The notion of stateless front-ends being able to scale out, bothacross the data center and across data centers requires that you makesure you have the right architectural model. Microsoft will be tryinghard to make sure we have the patterns and practices available todevelopers to get those models [so that they] can be brought onto thepremises. As you write your applications in a scale-out model fromthe premises, they can be brought into Windows Azure.

The example we showed was a situation where you can takeVisual Studio and .NET Framework and build an ASP.NET app,and then you can decide to deploy that locally, or you can decide todeploy that to Windows Azure. The only thing you have to do whenyou go to Windows Azure is to specify some additional metadata.You have to specify how many instances you’re going to run on, andwhat kind of SLA you’re looking for—that kind of metadata. ThenWindows Azure can take that and implement that correctly.

QHow do they specify that metadata?

ARight now—to the core—it’s in an .XML file. That’s a greatexample of an executable model, and Windows Azure understandsthat model to its toes. So it’s a model, and it delivers that. You canwrite those models in “Oslo”using the DSL written in “M,” target-ing Windows Azure in those models.

QSo there’s a natural fit here for apps developed in Oslo?

AYes, because Oslo is about helping you write apps more produc-tively. You can write any kind of application, including cloud apps.You can also write server applications and client applications. Butwe’re definitely working hard on the models for the cloud as well.

Q What challenges might be awaiting dev shops? What sort of skills dothey need to either discover or refine as they move to a services-aware,cloud-aware application?

A A lot of your existing skill set and a lot of your practices—whether it be the development methodology you use around ALMor using TFS [Team Foundation Server]—will just carry forward.

At the end of the day, you’re just writing code, and you’re deployingthat code. Windows Azure provides a new deployment target at afundamental level, so there’s a lot that’s similar.

A couple of things are new. There are a lot of new services thatdevelopers are going to need to learn in order to see if they makesense for their solutions. One example: If you were going to hookup two businesses together with some sort of business-to-businessmessaging application, we have a lot of technology that makes thateasy—Windows Communication Foundation, these kinds ofthings. But now you need to ask yourself: “Does it make sense forme to use the Azure platform and the service bus, which is a part of.NET services?”And you’re going have to learn what the pros andcons are if you’re adding it to your solutions.

Every developer has a unique set of needs, and they need tochoose differently between how much they’re doing in the cloudand how much they’re doing on the premises. So depending onregulatory, compliance, or whatever assets they have and their scalerequirements, it might be an opportunity to learn something new.

Q Are we looking at plug-ins to Visual Studio or new developmentinterfaces to service-enable some of these things? Are we bringingmore development resources to the table?

A You’re going to see some very natural extensions to what’s inVisual Studio today. For example, you’ll see new project types. Iwouldn’t call that a new tool; rather, I’d call it a fairly natural exten-sion to the existing tools.You’ll see new properties in the propertydescriptions of solutions. So you can say things like: “How muchscale-out do I want? Do I want this to run in multiple data centers?”

If you look at the portals for Windows Azure and the Azure Ser-vices Platform,there are new kinds of tools that are great for IT pros tolook at utilization,at what the load is on their applications,and so on.

Q What can we expect in terms of Oslo uptake and some of the stuffthat developers are going to have to grasp as they start developing intothe Azure space?A We want to get bits into the hands of developers as early as we pos-sibly can.We don’t take the attitude that we’re going to wait until we’rebasically close to shipping, and then spring it on people.We want toget a CTP [community technology preview] out early and engage inthat conversation.Now we can get this thing out broadly,get the feed-back, and I think for me, that’s the most powerful way to develop aplatform. If you’re going to build a platform in a vacuum, it’s veryhard to get it right. You need to have developers pounding on it,telling you what you’re doing right and what you’re doing wrong.

You can take Visual Studio and .NET Framework and build anASP.NET app, and then you can decide to deploy that locally, oryou can decide to deploy that to Windows Azure.

0109vsm_QandA_28-30.v4 12/15/08 9:35 AM Page 29

Page 32: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

C O N N E C T T O T H E C L O U D

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com30

Q Given the uncertain time frame of Azure, are some of your rivals likeAmazon and Google gaining a lot of early share? How will you dealwith the competitive landscape?

A The place to start with Amazon is [that] they’re a partner. Sothey’ve licensed Windows, they’ve licensed SQL, and we haveshared partners. What Amazon is doing, like traditional hosters, isthey’re taking a lot of the complexity out for our mutual customersaround hardware. The heavy lifting that a developer has to do totake that and then build a scale-out service in the cloud and acrossdata centers—that’s left to the developer.

We have base compute and base storage, which is the foundationof everything we’re doing with Windows Azure, but then we havethese higher-level services like the database in the cloud. We havethese user services for photos, contacts, and blogs, and these kindsof things with the live services. We have Internet-scale building-block services with .NET services, and we’ll be rolling out CRMServices and SharePoint Services.We have these higher-level thingsso that now developers can stand on the backs of thousands ofengineering years as they’re building the solution. They don’t haveto build an Internet-scale pub-sub system. They don’t have to havea new way to do social networking and contacts. They don’t have tohave reporting services that they have to build up themselves.

Google is a very limited offering. It’s a single programming lan-guage. It’s a particular part of the Web application.You can’t do theback-end processing.You don’t have a full database back there.Youdon’t have a lot of the things you might need to build an end-to-endapplication. You can’t even take too long to respond to the Webrequest or they’ll shut you down. It’s a hobby.

Q Obviously you have the Microsoft-hosted monoliths in play here.Will an enterprise be able to host its own cloud? Will there be third-party partners doing that as well?

A I want to be very clear on this.We built Azure on top of WindowsServer and on top of .NET Framework. As we learn, we’re going totake that innovation and bring it back to Windows Server.And thenas we innovate in Windows Server, we’ll bring that back to Azure.And we absolutely support the choice, depending on whether it’syour data center, your cloud, your personal enterprise cloud, or theMicrosoft Azure cloud. But the way you’ll get your cloud is thatyou’ll buy Windows Server, you’ll buy SQL Server, you’ll buy theexisting premises platform, and we’ll continue to move that inno-vation unilaterally.Q But in terms of the actual physical hosting of machines, if I’m anenterprise and I want to provide these cloud-based Azure services tomy users or business partners, I can have my own private cloud?

A With Windows Server, not with Azure. The Azure Services Platform,SQL Services,Live Services—those are hosted exclusively inthe Microsoft data center. You get at them on Microsoft’s platform and other platforms,because they’re all exposed on Internetstandards.

Q Other platforms meaning?

A Other operating systems, other computing platforms, otherhosters that are exposed to Internet standards—REST, SOAP,and XML.

Q So only Microsoft will be hosting Azure?

A Only Microsoft is hosting Azure, but anybody can host our coreapp platform, which is Windows Server and SQL Server.And again,the innovations are going to flow in both directions. We’re going toinnovate in Windows Server—that will move up to Azure—andwe’ll innovate in Azure.

Q We talk about the cost of computing, but what impact will all thishave on the cost of development and the management of dev processes?

A We think we’re removing complexities out of all layers of the stackby doing this in the cloud for you.For example,we’ll automatically doall of the configuration so you can get load balancing across all of yourinstances.We’ll make sure that the data is replicated both for efficien-cy and also for reliability, both across an individual data center andacross multiple data centers. So we think that by doing that you cannow focus much more on what your app is and less on all that appinfrastructure.My guess is that, to the extent that the cloud is appro-priate, it will make it much simpler for you to build your applicationsas a developer,and then you can also use premises as well.

Q What’s your advice for preparation now going though 2010?

A I think the call to action is to start engaging in a conversationabout the cloud and about Azure. Download the SDKs, get freeaccounts, start playing with it, and start giving us feedback. Thatway we can make sure that what we deliver is what [developmentmanagers] need. Also, you need to start thinking about what’sappropriate for a hosted solution, and what’s appropriate forpremises. Start getting those kinds of development practices inplace so as these roll out there’s an easier way to take advantage ofthe new services. These represent new patterns and practices—new best practices. VSM

Jeffrey Schwartz ([email protected]) is executive editor,features, and Michael Desmond ([email protected]) is editor in chief of RDN.

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to go directly to theserelated resources.

READ MORE

VS0901RW Read this article online.

0109vsm_QandA_28-30.v4 12/15/08 9:35 AM Page 30

Page 33: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

VisualStudioMagazine.com · January 2009 · VISUAL STUDIO MAGAZINE 31

Andrew MintzNational Sales ManagerPhone: [email protected]

Chris KourtoglouRegional Sales ManagerPhone: [email protected]

National Accounts DirectorWilliam SmithPhone: [email protected]

Microsoft Account ManagerDanna VedderPhone: [email protected]

West

East

Director, Print ProductionJenny Hernandez-AsandasPhone: 818-734-1520 ext 101Fax: [email protected]

Production CoordinatorCatharine WoodPhone: 818-734-1520 ext [email protected]@1105media.com

Advertising Sales Ad Index

Atalasoft, Inc. pg. 23www.atalasoft.com

ComponentOne pg. 16, 17www.componentone.com

dtSearch pg. 20www.dtsearch.com

Intel Corporation pg. C4www.intel.com

LEAD Technologies, Inc. pg. 25www.leadtools.com

Microsoft Corporation pg. 12, 13www.microsoft.com

Pegasus Imaging Corporation pg. 27www.pegasusimaging.com

Software FX, Inc. pg. C2, 1www.softwarefx.com

Visual Studio Magazine pg. C3www.visualstudiomagazine.com

VSLive! Events pg. 5Vslive.com/sf2009

Wayside Technology Group, Inc. pg. 3www.waysidetechnology.com

Edit Ad IndexCompuware 9www.compuware.com

Developer Express 8www.devexpress.com

JetBrains 8www.jetbrains.com

Typemock 8www.typmock.com

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media, Inc., 9121 Oakdale Avenue, Ste. 101,Chatsworth, CA 91311. Periodicals postage paid atChatsworth, CA 91311-9998, and at additional mailingoffices. Complimentary subscriptions are sent to qualifyingsubscribers. Annual subscription rates for non-qualified sub-scribers are: U.S. $34.97, Canada $52.97 (U.S. funds);International $78.97 (U.S. funds). Subscription inquiries,back issue requests, and address changes: Mail to: VisualStudio Magazine, P.O. Box 1164, Skokie, IL 60076-8164,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 VisualStudio Magazine, P.O. Box 1164, Skokie, IL 60076-8164.Canada Publications Mail Agreement No: 40612608. ReturnUndeliverable Canadian Addresses to Circulation Dept. orBleuchip International, P.O. Box 25542, London, ON N6C 6B2.

Copyright Statement© Copyright 2009 by 1105 Media, Inc. All rights reserved.Printed in the U.S.A. Reproductions in whole or part prohib-ited except by written permission. Mail requests to"Permissions Editor," c/o Visual Studio Magazine, 2600 ElCamino Real, Ste 300, San Mateo, CA 94403.

Legal DisclaimerThe information in this magazine has not undergone anyformal testing by 1105 Media, Inc. and is distributed with-out any warranty expressed or implied. Implementation oruse of any information contained herein is the reader's soleresponsibility. While the information has been reviewed for

accuracy, there is no guarantee that the same or similarresults may be achieved in all environments. Technical inac-curacies may result from printing errors and/or new develop-ments in the industry.

Corporate AddressCorporate Headquarters: 1105 Media9121 Oakdale Ave. Ste 101, Chatsworth, CA 91311www.1105media.com

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

ReprintsReprints: For single article reprints (in minimum quantities of250-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 from1105 Media, Inc., is available for rental. For more informa-tion, please contact our list manager, Merit Direct. Phone:914-368-1000; E-mail: [email protected];Web: www.meritdirect.com.

Go toVisualStudioMagazine.comto access the stories in thisissue, plus read exclusiveonline-only content.

0109vsm_AdIndex_31 12/15/08 2:27 PM Page 31

Page 34: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

VISUAL STUDIO MAGAZINE · January 2009 · VisualStudioMagazine.com32

IS AGILE ROCK OR DISCO?

and David Bowie did songs with heavy disco influences. Butyou don’t find that many disco songs on “Guitar Hero” or“Rock Band,”while you do find many vintage rock songs froma score of sixties rock icons.

Will agile methodologies fare as well as rock? Will we stillbe doing agile software development 20 or 30 years from now?Or will agile be the disco of this software era, fading in favor ofsomething else in the next few years?

I don’t know. I don’t think anyone knows.Agile has some interesting strengths. I think agile propo-

nents are right on the money about a rapid feedback loop andhaving clear accountability for developers. I believe there areplaces where agile methodologies have dramatically improvedthe outcomes of software development efforts. But I don’tthink agile is perfect, nor do I think it’s best for everyone.

Agile means different things to different people. I’mwriting a short column and not a book, so I must, out ofnecessity, paint with a broad brush. I hope agile proponentswill keep that in mind.

My first criticism of agile is the fanatic mentality of someproponents. In one of the first books about Scrum,“Agile Soft-ware Development with Scrum”(Prentice Hall, 2001) by KenSchwaber and Mike Beedle, the authors claim: “Industrialprocess control theory is a proven body of knowledge thatdescribes why Scrum works and other approaches are difficultand finally untenable.” In short they’re saying Scrum worksand nothing else does. That’s a sweeping and ridiculous claim.No matter how good Scrum is, circumstances vary far toomuch to make such an argument. Projects range in size andcomplexity, and developers vary in talent and temperament.

Let me say again that I think agile has many fine qualitiesand can lead to successful development projects. But thatdoesn’t mean agile is perfect, or that it’s the right choice for allprojects. Here’s what I mean:

The Patterns and Practices group at Microsoft is heavilyinto agile development. Don Smith is in that group, and, at a

conference last May, he said,“It’s hard to do agile without reallygood developers.” I’ve heard variations of the same thing saidfrom others.

But not all developers are that good. Therefore, if Don isright, then agile isn’t for everyone.

I also think agile development still has areas where it canimprove. For example, agile teams have a tendency to require ahigh level of experience and professionalism just to join theteam. What about talented, but inexperienced, developers?Richard Campbell, of the Internet audio talk show “.NETRocks,”wonders if agile is compromising our supply of devel-opment talent by ignoring such developers. I wonder if agile issowing the seeds of its own destruction by alienating a broadswath of new talent. I think agile practices could improve byformalizing mentoring beyond pair programming, which Iconsider a highly inefficient way of mentoring.

Finally, I wonder how much of agile development existssimply to make developers more comfortable.Most developerslove to write code,and agile does a pretty good job of rationalizingwhy developers don’t need to do anything else. Design? Code itwith test-driven development. Requirements gathering? I’veheard proponents of agile development say that the user doesn’tknow what they want until they see something, so you might aswell get straight to coding. I’m sorry, but that’s a cop-out. Userscan tell you what they need if you know how to ask them.

Like everything else in technology,agile development mustevolve. I hope it succeeds as rock music has; with many differentstyles that suit different tastes and circumstances.And I hope itsheds the elitism and fanaticism that I see in some proponents.Otherwise, it’s more likely to share the destiny of disco. VSM

Billy Hollis is an author, consultant,and veteran software developeron Microsoft technologies. He’s currently developing Software as aService applications with Windows Presentation Foundation andSilverlight and training others on those technologies. He speaksregularly at VSLive! events. Reach him at [email protected].

The Pragmatic Developer

BY BILLY HOLLIS

When I was a teen, listening to 30-year-old music was distinctly uncool.Yettoday’s teens listen happily to music more than 30 years old. A bit after rockcame the disco wave.For a while, it was wildly popular. The Rolling Stones

0109vsm_GuestOp.32.v4 12/15/08 9:32 AM Page 32

Page 35: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

PUREVISUAL STUDIO AND .NET

PUREVISUAL STUDIO AND .NET

OPTIMIZED FOR

PRINT ✱ ONLINE ✱ EVENTS

For more information visit:www.VisualStudioMagazine.comwww.RedDevNews.comwww.VSLive.com

M A G A Z I N E . C O M

POWERING THE WINDOWS SOFTWARE REVOLUTION

E N T E R P R I S E S O L U T I O N S F O R . N E T D E V E L O P M E N T

0208vsm_VSMPureAd.final 1/18/08 11:46 AM Page 32

Page 36: Partition Web Apps Intelligently - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_901DG.pdf · Steve Michelotti, “Partition Web Apps Intelligently,” p. 10 Contents ... Telerik RadControls

EVOLVE YOUR CODE.Parallelism breakthrough.

www.intel.com/go/parallel

Project1 12/15/08 11:45 AM Page 1