36
 VisualStudioMagazine.com Is Agile Rock or Disco? PLUS T arget Multipl e .NET Frameworks Windows Workflow Changes Direction    J    A    N    U    A    R    Y    2    0    0    9       V    o    l  .    1    9  ,    N    o  .    1 ENTERPRISE SOLUTIONS FOR .NET DEVELOPMENT Partition Web Apps Intelligently Microsoft’s MVC framework makes it possible (finally! ) to impleme nt “a separation of concerns” in ASP.NET.

visual Studio Magazine - 01- 2009

Embed Size (px)

DESCRIPTION

internet html

Citation preview

  • 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 AppsIntelligentlyMicrosofts 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

  • BeTheDataGuru

    Visual Studio WPF/Silverlight SharePoint SQL Server PowerShellJava COM

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

  • 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 thats 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

  • 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 cant use any of the new C# language features.Its time to dispel that myth. BY BILL WAGNER

    DEPARTMENTS6 Letters to the Editor

    7 Editors 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 Medias 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 IntelligentlyMicrosofts Model-View-Controller framework makes it possible to implement a separation of concerns in ASP.NETsomething that wasdifficult, if not impossible, previously. Learn how to take advantage ofMVC to design better Web apps that separate their architectural elementsthe UI, business logic, and codeproperly, 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

  • 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 dtSearchs 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.Youll 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

  • 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 theyve come up with.Whether its Web design, .NET development, or SQL Server programming,weve 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 cant easily visualizeyour branching structure so its difficult to understand the movement ofcode from branch to branch. In this installment of Jeff Levinsons 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 sitesstructure without invalidating your users bookmarks. LOCATOR+ CODE: VS0901PV2

    ONLINE BLOGS

    VSMs Big IssueVisual Studio Magazines 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

  • Brought to you by:

    San Francisco Hyatt Regency EmbarcaderoFebruary 23-27, 2009

    Dont 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. Dont 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 Microsofts 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

  • 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

    Ive 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 Dollards 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 Meaders comments about Office 2007and its detestable, exasperating ribbon with the pared down menu options [Editors 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 theyre all going to ask me for help or even blame meif they get stuck or lost in Vista or Word 2007.

    Its 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 WrightManaging 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 GardnerGraphic Designer Erin Horlacher

    Online/Digital MediaEditor, VisualStudio Becky Nagel

    Magazine.comExecutive Editor, New Media Michael Domingo

    Online News Editor Kurt MackieAssociate Editor, Web Gladys Rama

    Web Producer Shane LeeDirector, Web Development Rita Zurcher

    President Henry AllainVice President, Publishing Matt N. Morollo

    Director of Marketing Michele ImgrundOnline 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. ValentiPresident, 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-0961Irvine Office 949-265-1520; Fax 949-265-1528Corporate 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

  • Editors Note

    BY PATRICK MEADEReditor in chief

    VSMSNEW BIG IDEAIf youre a longtime programmer or merely someone who has followed computers for a while, its possible youve seen the work of VSMs managingeditor before.Guy Wright has been working at computer-related magazines

    since the personal computers 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 Commodores 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 Commodores ill-fated CDTVdevice, putting the first comic books on CD-ROM, and evenspending some time in purgatoryI believe he calls it heavenusing VB3 to create magazine archive CD-ROMs and demodiscs. To put it another way, Guy was programming in VBbefore Id even heard of VB,and Ive been working at this maga-zine for going on 13 years.He notes that he wasnt a professionalprogrammera not-uncommon trait for many people whoinitially picked up VBbut 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 its 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 Guys 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.

    Youve been doing this long enough that your turn-around on these should be minutes, not days! he tells me.

    Hes 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 its so easy, let him do it. And so heshall. Beginning this month, Guy will begin overseeing VSMsnew online blog: VSMs Big Issue. This blog will serve as ajumping-off point for discussing the issues and technologiesof interest to Visual Studio developers, issues that wouldntnormally 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. Well 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 whats new. Guy and I will both be postingto the page, though Guy will be posting a bit more frequentlythan I willhe does have to show me how its 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 dont 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 newVSMs Big Issue blog? Tell me at [email protected] [email protected]

    OT

    O B

    Y P

    AT

    JOH

    NS

    ON

    ST

    UD

    IOS

    VisualStudioMagazine.com January 2009 VISUAL STUDIO MAGAZINE 7

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

  • 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

    Editors Note: Please send product informationto 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 toitincluding thread names and lockedresourcesare displayed in Visual Studiosoutput 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

  • 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 youre building a complex appli-cation or working as part of a team, DevPartner Studio fromCompuware Corp. gives you theability to understand just howgoodor badyour 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 youre working in a team environment, a source code ana-lyzer provides the most effective way to ensure that youandthe rest of the teamare 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 dont like the rules that come with Studio, you can cus-tomize the rules database, though youll 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. Studios PerformanceAnalyzer and Performance Expert lets you monitor your appli-

    cations as they run in Visual Studio and report on which methodsare called, how often theyre executed, and where your appli-cation is spending its time. In addition to a detailed set ofpost-performance reportswhich you can save to reviewlaterStudio 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 doesnt support allapplication types. For example, ASP.NET isnt supported. Providedyou keep most of your codeand all of your performance-criticalcodein middle-tier business objects, you can still use Studio toanalyze your code as long as youre willing to knock togethersome WinForms applications to exercise your objects.

    None of this comes cheap. In addition to the purchasepriceobviously aimed at larger shopsyoull 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 didntwant 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 youre building an application thats too big to hold in yourhead at onceor if youre working in a team environment whereadhering to standards is importantyou 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.Compuwares DevPartner is a comprehensive set of testing and performance analysistools. Depicted here is the live graph generated by the Studios 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

  • 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. Ill 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 MVCnow 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

    Microsofts Model-View-Controller framework makes it possible to implement a separation of concerns in ASP.NETsomething that was difficult, if not impossible, previously.Learn how to take advantage of MVC to design better Web apps that separate their architectural elementsthe UI,business logic, and codeproperly, 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

  • 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 thats 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,lets 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 dont 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 ContactControllers 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 its 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 GetContactList();IEnumerable 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 its 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 cant 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

  • 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

  • Your challenge: over-deliver on features, while

    beating deadlines. Defy it: start with Visual Studio

    Tools for Microsoft Of ce for apps that win the day.

    More tips and tools at defyallchallenges.com

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

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

    VISUAL STUDIO MAGAZINE January 2009 VisualStudioMagazine.com14

    {IEnumerable 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-trollers 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

    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 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 ContactControllers Create()method. You can accomplish this with theActionLink method of the HtmlHelper:

    (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:

    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. Its a common misconceptionto think of the business objects as the Model in the ASP.NET MVCframework. This is sometimes true, but its 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 Controllers Save action method.

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

  • 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 StateList { get; set; }

    public ContactViewData(Contact contact,IEnumerable stateList){

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

    }}

    Using the Create action method isnt 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 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, theres 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-Controllers 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

    c.Create(null), "Add New Contact") %>

    First NameLast NameEmail

    c.Create(contact.ContactID), "Edit")%>

    c.Delete(contact.ContactID), "Delete") %>

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

  • 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

  • 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

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

    VISUAL STUDIO MAGAZINE January 2009 VisualStudioMagazine.com18

    CREATE THE EDIT CONTACTS VIEWC#

    First Name:

    Last Name:

    Email:

    Company:

    Title:

    Street Address:

    City:

    State:

    Zip:

    Save

    c.Index(), "Cancel") %>

    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

  • 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 isnt 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 itseasy 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. Ive 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 ContractControllers Index method. The job ofthe Index method is to retrieve the collection from thedata layer and then pass that collection to the Indexview. However, its important that only the code in theController is tested and not the code in the data layer.Therefore, the data layer will be mockedso that onlythe code in the Controller is being tested. Heres thecomplete unit test for the Index method:

    [TestMethod]public void ContactController_Index_Test(){

    // set upvar contactManager =

    new Mock();IEnumerable

    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;

    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 Microsofts 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 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

  • 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 withSpider

    Web with Spider

    Web with Spider

    Desktop with Spider

    Desktop withSpider

    Network with Spider

    Web with Spider

    Publish for CD/DVDs

    Publish for CD/DVDs

    Publish for CD/DVDs

    Desktop with Spider

    Engine for Linux

    Engine for Linux

    Engine for Linux

    Engine for Win & .NET

    Engine for Win & .NET

    Engine for Win & .NET

    New64-bitNew64-bit

    [TestMethod]public void ContractController_Save_Valid_Test(){

    // set upContact contact = TestUtil.CreateValidContact();var contactManager = new Mock();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 MVCframeworks architecture is that its 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 Guthries Blog: http://tinyurl.com/5d6a6f

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

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

    Scott Hanselmans 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

  • Many developers have the misconception that targeting older versions ofthe Framework means youcant use any of the new C#language features. Its 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 dont 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 doesnt 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 youretargeting an older version of the Framework. Ill walk you through some of these nuances, explainingwhat capabilities are in bounds, which require care, and which ones you cant 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, Im concentrating on the differences between various language features and howyou can make use of the newer language features even though youre targeting an older version of theFramework. Obviously, if youre targeting the 2.0 Framework, none of the 3.0 librariesWindows 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

  • 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 dont access the 3.5 libraries. This is alsotrue when using C# 3.0 when youre targeting the 2.0 Framework:

    var foo = 27;

    Thats 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 sample = new List { 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, theres less you can do with them than you might think.

    Obviously,you cant 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 youve 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.Thats not available in earlier versions of the .NET Framework, soyou cant create extension methods when youre 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 keywordin fact, the entire query-patternsyntaxmaps to specific methods. The compiler then translatesthose keywords into method calls. If a candidate method is in scope,the query will compile, even if youre targeting the 2.0 Framework.

    This is where it gets a bit complicated so lets 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 Select(Func selector)

    {foreach (var peep in storage)

    yield return selector(peep);}// elsewhere:public delegate TResult Func(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 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 Im 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,its 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 Select(Func selector)

    Thats a mouthful of type parameters, so lets start with a concreteexample. The select statement above looks for a method that hasthe form:

    public IEnumerable Select(Func 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 youre 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

  • 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 youre 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 problemfor amultitargeting applicationis that this eventwill compile fine when targeting the 2.0Framework. Its 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,thats the only example of this kind of problemthat Ive encountered so far, but its the kindof problem you will only find by testing on amachine where the target frameworkandonly the target frameworkis installed.

    Ive always viewed multitargeting as ashort-term solution to enable developers tomove forward, while still supporting cus-tomers that arent 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 Documentand 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.NETTake 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.0More Powerful,with Zero-Footprint Imaging, and3 Months of Free Gold Support.

    New

    DotImage 7

    .0

    Release

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

  • 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 Ive been hearing that Windows Workflow 4.0 wasannounced at the Professional Developers Conference(PDC),and that it changes everything.Is this true,and ifso,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 arent 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. Its 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. Youd also have better control overpersistence. Additionally, theres 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 usersand othersto build or modify work-flows with the constrained set of activities youve 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 organizations 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 youll 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, youre 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 arent 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 wont improvetheir design, but rewriting them will.A quick list of significantfeatures Windows Workflow 4.0 doesnt have includes CodeActivity, Data Exchange Service (DES) events, DES methodcalls, a code model (its declarative only), rules as you knowthem now, an Initialize event, and dependency properties.

    If youre 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,Ive collected a set of preliminary guidelines for preparingworkflows to transition (see Write New Workflows with .NET4.0 in Mind,p.26). If youve 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

  • 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 youre writing workflows todayand believe youll need this strategy, consider building in events toinitiate the process. If you have existing work-flows, you might need to alter them later, butits not yet clear whether Microsoft will providea tool to help automate the 3.0/3.5 workflow-modification strategy.

    If you have deployed workflows, itsalmost 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,youllput 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.0and the significantinput Microsoft received in fixing the issuesthat plagued WF 3.0/3.5should result in aproduct with fewer quirks to trip you up.

    If youve deployed workflows and believeyoull have a challenging transition, Id like toknow more about your scenario so we canhelp Microsoft improve the transition experi-ence for you and others.

    QHeres something Ive had a hardtime understanding: why shouldnt 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: $OO LQGXVWU\ VWDQGDUGVLQFOXGLQJ 7,)) (;,) 3') -3(*-3(* ',&203&/':*DQGKXQGUHGVPRUHImage Compression: )URP VWDQGDUG -%,*-%,* $%,& -3(* DQG &&,77 ** WR /($'VVSHFLDOL]HG$%&&03DQG&0:FRPSUHVVLRQDisplay Controls: 6FUROO ]RRP SDQ PDJQLI\JODVVEULJKWQHVVFRQWUDVWJDPPDZLQGRZOHYHOImage Processing: OWHUV WUDQVIRUPV DQGFRORU FRQYHUVLRQ IXQFWLRQV ZLWK H[WHQGHG JUD\VFDOHWRELWVXSSRUWOCR/ICR/OMR:)XOOSDJHRU]RQDOPXOWLWKUHDGHGUHFRJQLWLRQZLWKIRUPDWWHGRXWSXWLQFOXGLQJ3')'2&DQG7;7IRU:LQDQG[Barcode:5HDGZULWHDOOLQGXVWU\VWDQGDUG'DQG'EDUFRGHV'DWD0DWUL[3')0LFUR3')45&RGHDQGPRUHForms Recognition and Processing: $XWRPDWLFDOO\LGHQWLI\IRUPVDQGH[WUDFWXVHUOOHGGDWD Document Cleanup/Preprocessing: 'HVNHZGHVSHFNOH OLQH DQG ERUGHU UHPRYDO UHJLVWUDWLRQPDUNVDQGPRUHPDF and PDF/A: 5HDGZULWH UDVWHU DQG WH[WVHDUFKDEOH3')OHVAnnotations: ,QWHUDFWLYH 8, IRU GRFXPHQWPDUNXS UHGDFWLRQ DQG LPDJH PHDVXUHPHQWLQFOXGLQJVXSSRUWIRU',&20DQQRWDWLRQVGrayscale Imaging: 'LVSOD\ DQG SURFHVVVLJQHGXQVLJQHGELWELWGDWD Medical Web Viewer Framework: 3OXJLQHQDEOHG IUDPHZRUN WR TXLFNO\ EXLOG KLJKTXDOLW\

    IXOOIHDWXUHGZHEEDVHGPHGLFDOLPDJHGHOLYHU\DQGYLHZHUDSSOLFDWLRQV Medical Image Viewer: +LJK OHYHO GLVSOD\FRQWURO ZLWK EXLOWLQ WRROV IRU LPDJH PDUNXSZLQGRZ OHYHO PHDVXUHPHQW]RRPSDQFLQHDQG/87PDQLSXODWLRQDICOM: )XOO VXSSRUW IRU DOO ,2' FODVVHV DQGPRGDOLWLHVGHQHGLQWKH',&20VWDQGDUGLQFOXGLQJ(QFDSVXODWHG3')&'$ DQG 5DZ'DWDDICOM Communications: )XOO VXSSRUW IRU',&20 PHVVDJLQJ DQG VHFXUH FRPPXQLFDWLRQHQDEOLQJ TXLFN LPSOHPHQWDWLRQ RI DQ\ ',&206&8DQG6&3VHUYLFHVWPF (XAML): 9LHZHU ,PDJH /LVW$QQRWDWLRQV7UDQVLWLRQVDQG:,&&RGHFVAJAX:HE)RUP,PDJHFRQWUROVIRUGHYHORSLQJULFKZHEDSSOLFDWLRQVJPIP&OLHQWDQG6HUYHUFRPSRQHQWVIRULQWHUDFWLYHVWUHDPLQJRIODUJHLPDJHVDQGDVVRFLDWHG LPDJH GDWD XVLQJ WKH PLQLPXPSRVVLEOHEDQGZLGWKScanning: 7:$,1 DQG :,$ DQG ELWDXWRGHWHFW RSWLPXP GULYHU VHWWLQJV IRU KLJKVSHHGVFDQQLQJDVD:3OD\FUHDWHFRQYHUWDQGEXUQ'9'LPDJHVMultimedia:&DSWXUHSOD\VWUHDPDQGFRQYHUW03(* $9, :09 03 03 2** ,62 '9' DQGPRUH

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

    800 637-1840

    LEADTOOLS SDKs feature LEADs iCompress Technologies.

    'HYHORS\RXUDSSOLFDWLRQZLWKWKHVDPHUREXVWLPDJLQJWHFKQRORJLHVXVHGE\Microsoft, HP, Sony,Canon, Kodak, GE, Siemens, WKH US Air Force DQGVeterans Affairs Hospitals./($'722/6SURYLGHVGHYHORSHUVHDV\DFFHVVWRGHFDGHVRIH[SHUWLVHLQFRORUJUD\VFDOHGRFXPHQWPHGLFDOYHFWRUDQGPXOWLPHGLDLPDJLQJGHYHORSPHQW,QVWDOO/($'722/6WRHOLPLQDWHPRQWKVRIUHVHDUFKDQGSURJUDPPLQJWLPHZKLOHPDLQWDLQLQJKLJKOHYHOVRITXDOLW\SHUIRUPDQFHDQGIXQFWLRQDOLW\

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

    0DUNXS 0HGLFDO

    )RUPV5HFRJQLWLRQ

    0XOWLPHGLD

    'RFXPHQW %DUFRGH

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

  • 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 doesntinclude a data grid, so what do you suggest I use? AWPF in .NET 3.0 and .NET 3.5 doesnt contain a datagrid. However, Microsoft has released the WPF Toolkit,which includes a data grid, calendar control, and datepicker. This toolkit requires WPF 3.5 Service Pack 1 (SP1). Theincluded data grid is fairly full featured,but doesnt support grouping.If youre working in .NET 3.0 or 3.5, youll 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 Im 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.

    Ive 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. Ifthis doesnt solve your problem, you should ensure that the file is inthe correct location, which is adjacent to the executable. By default,this is at /bin/Debug,where 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 youre trying to accomplish.

    Q I need to copy some files into the executable directory, butthey arent in the project directory so it doesnt make sense totreat them as resources.Weve been trying to do this manually,You can tweak your 3.0/3.5 workflows to make the transition

    to Windows Workflow Foundation (WF) 4.0 a little easier. Theseguidelines limit the scenarios in which theres no correspondingfeature in 4.0.

    1. Create custom activities. Create custom activities instead ofcode-beside logic in a CodeActivity. Theres no CodeActivity in WF4.0. Remember that the custom activity model also changes, so itsbest 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 theres a choice. The Data Exchange Service (DES) modelgoes away in WF 4.0: theres 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 dont yet have WCF in your application or organiza-

    tion, implementing it in WCF 3.5 may be onerous. In this case, useevents, and assume youll 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 theres noActivity.Initialize event. Any setup should be done in the Activi-ty.Execute method.

    5. Use WorkflowInstance.EnqueueOnIdle for queuing. If youredoing 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 youreusing 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 towardsMicrosofts 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

  • but weve 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 its easier to modify the project file. The project fileis an MSBuild script, capable of managing complicatedbuilds. 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 .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:

    -->

    You dont need to understand targets orwhy this works to put your pre- or post-build code into the correct location.Copyis an MSBuild task with the source file loca-tion relative to the project directory:

    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. Shes 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].

    G