Quick viewing(Text Mode)

Build Big-Data Apps in SQL Azure with Federation

VisualStudioMagazine.com

Build Big Data Apps in SQL Azure

Get ready to scale out your cloud databases beyond today’s 50GB limit.

PLUS Delve into ASP.NET MVC 3 vsInsider: Why Does Microsoft Duplicate Open Source Functionality? MARCH 2011 Volume 21, No. 3 Volume ...

...... Using Quince™, you and your team can collaborate on the user interface using wireframes, designs and examples.

...... Then use NetAdvantage® UI controls, like the map control used here, to bring the application to life quickly & easily.

Untitled-7 2 11/10/10 10:59 AM ...... From start to finish, Infragistics gives you the tools to create impressive user experiences that'll make end users happy!

...

SEE HOW WE USE THE TOOLS TO CREATE THIS KILLER APP AT INFRAGISTICS.COM/IMPRESS

Infragistics Sales 800 231 8588 • Infragistics Europe Sales +44 (0) 800 298 9055 • Infragistics India +91 80 4151 8042 • @infragistics

Untitled-7 3 11/10/10 10:59 AM Your best source for software development tools! ®

LEADTOOLS Document UltraEdit VMware vSphere Imaging SDK v17.0 The #1 Best Selling Text Editor Essentials Kit Bundle by LEAD Technologies in the World vSphere Essentials provides an all-in-one solution for small offices to virtualize three LEADTOOLS Document Imaging has every compo- by IDM nent you need to develop powerful image-enabled physical servers for consolidating and UltraEdit is the world’s standard in text business applications including specialized bi-tonal managing applications to reduce hardware editors. Millions use UltraEdit as the image processing, document clean up, annota- and operating costs with a low up-front ideal text/hex/ editor tions, high-speed scanning, advanced compression investment. vSphere Essentials includes: on any platform — Windows, Mac, (CCITT G3/G4, JBIG2, MRC, ABC), and • VMware ESXi and VMware ESX or ! Win32/64 binaries for /C++, .NET, Silverlight, (deployment-time choice) Named User WPF, WCF, & WF. Available add-ons include: Features include • VMware vStorage VMFS • Multi-threaded OCR/ICR/OMR/MICR/ for nearly any ; 1-24 Users for 3 hosts • Four-way virtual SMP Barcodes (1D/2D) powerful Find, Replace, Find in Files, Paradise # Paradise # and Replace in Files; FTP support, sort, • VMware vCenter Server Agent V55 85101C02 Paradise # • Forms Recognition/Processing I84 01201A01 column mode, hex, macros/scripting, L05 03301A01 • Print Capture and Document Writers $ 95 • VMware vStorage APIs/VCB $ 99 large file handling (4+ GB), projects, • PDF, PDF/A and XPS 59. • VMware vCenter Update Manager 446. $ 99 templates, Unicode, and more. 2,007. programmers.com/LEAD programmers.com/idm • VMware vCenter Server for Essentials programmers.com/vSphere Embarcadero RAD Studio XE Enterprise Architect VMware Workstation 7 by Embarcadero Corporate Edition VMware Workstation 7 is the gold-standard ® virtualization software for desktop and laptop Embarcadero RAD Studio XE is a comprehen- Visualize, Document and computers, with the richest feature set and sive application development suite and the Control Your Software Project broadest platform support available. VMware fastest way to visually build GUI-intensive, by Sparx Systems Workstation enables users to create and host data-driven applications for Windows, .NET, Enterprise Architect is a comprehensive, multiple virtual machines on a single desktop, PHP and the Web. RAD Studio includes ®, ® ™ ™ integrated UML 2.1 modeling suite expanding the power of desktop systems for C++Builder , Delphi Prism , and RadPHP . The providing key benefits at each stage of IT administrators; software development and suite provides powerful compiled, managed system development. Enterprise Architect test engineers; technical sales, training and and dynamic language support, heterogeneous NEW 7.5 supports UML, SysML, BPMN and support staff; and PC enthusiasts. for Linux & database connectivity, rich visual component other open standards to analyze, design, RELEASE! VMware Workstation transforms the way Windows frameworks and a vast third-party ecosystem test and construct reliable, well under- 1-4 Licenses technical professionals develop, test, demo, Paradise # that enable you to deliver applications up to stood systems. Additional plug-ins are Paradise # 5x faster across multiple Windows, Web, and and deploy software. Workstation’s innovative V55 22301A04 Paradise # also available for Zachman Framework, SP6 03101A02 database platforms! features for VMware environments help to CGI 15401A01 MODAF, DoDAF and TOGAF, and to $ 99 reduce hardware cost, save time, minimize $ 99 integrate with and Visual Studio 182. 153. $ 99 risk, and streamline tasks that save time 1,383. programmers.com/embarcadero 2005/2008. programmers.com/sparxsystems and improve productivity. programmers.com/vmware

Spread for Windows Forms 5 Mindjet® MindManager TX Text Control 16.0 by GrapeCity version 9 for Windows® Word Processing Components • World’s best selling .NET Spreadsheet TX Text Control is royalty-free, robust and • Import/export native Microsoft Excel files Every Successful Project Starts powerful word processing software with full formatting with a Good Plan. in reusable component form. New ® Version • Extremely flexible printing and export options by Mindjet • .NET WinForms and WPF rich Released! including PDF Mindjet MindManager® is information text box for VB.NET and C# • Extensible formula support, including mapping software that gives business • ActiveX for VB6, Delphi, VBScript/HTML, ASP Microsoft Excel functions professionals a better way to conquer • Hundreds of chart styles for enhanced data information overload, brainstorm • File formats DOCX, DOC, RTF, HTML, Professional Edition visualization concepts, develop strategies, simplify XML, TXT Paradise # • Powerful user interface and flexible data project planning, and communicate 1 User • PDF and PDF/A export, PDF text import T79 12101A01 connectivity results. MindManager® maps provide Upgrade Paradise # • Tables, headers & footers, text frames, $ 99 • WYSIWYG spreadsheet designers, quick-start an intuitive visual framework for Paradise # F15 17401A01 bullets, structured numbered lists, multiple 1,109. wizard and chart designers planning successful projects. F02 01101A01 undo/redo, sections, merge fields, columns • Royalty-free licensing $ 98 Download a demo today. $ 99 293. • Ready-to-use toolbars and dialog boxes 936. programmers.com/grapecity programmers.com/textcontrol programmers.com/mindjet New Intel Visual Microsoft SQL Server Compiler Developer Edition 2008 R2 Win an iPad! by Intel by Microsoft Place an Order for Software Intel® Visual Fortran XE SQL Server 2008 Developer enables 2011 includes the latest generation of Intel® developers to build and test applications (or Hardware) with Fortran compilers, Intel® Visual Fortran Compiler that run on SQL Server on 32-bit, ia64, and ’s Paradise ® XE 12.0 for Windows. Intel Fortran Composer x64 platforms. SQL Server 2008 Developer and You’ll be Entered XE is available for Linux and Mac OS X. This includes all of the functionality of Enterprise NEW package delivers advanced capabilities for Edition, but is licensed only for development, for a Drawing to Win RELEASE! development of application parallelism and test, and demo use. The license for SQL 2-bit/x64 an iPad Wi-Fi 32GB. ® Server 2008 Developer entitles one developer winning performance for the full range of Intel IA64 DVD for Windows processor-based platforms and other compatible to use the software on as many systems Paradise # Single (SSR) platforms. It includes the compiler’s breadth of as necessary. For rapid deployment into M47 31101A04 Just Use the Offer Code TRWD03 Paradise # advanced optimization, multithreading, and production, instances of SQL Server 2008 When You Place Your Order Online or with I23 86101E03 processor support, as well as automatic proces- Developer can easily be upgraded to SQL $ 99 Server 2008 Enterprise without reinstallation. 41. $ 99 sor dispatch, vectorization, and loop unrolling. Your Programmer’s Paradise Representative. 263. programmers.com/intel programmers.com/microsoft 866-719-1528 programmersparadise.com Prices subject to change. Not responsible for typographical errors.

Untitled-11 1 2/2/11 3:43 PM { FRAMEWORKS }

14

Michael Desmond, Editor in Chief, Visual Studio Magazine Who We Are Every year we survey our readership to better who we’re serving, and set the direction of our coverage in VSM and on the VisualStudioMagazine.com Web site. What did we learn this year? We already knew that our readers are experienced working programmers (79 percent with 10-plus years on the job) engaged with a March 2011 // Volume 21 // No. 3 wide range of programming platforms, languages and frameworks. On the FEATURES language front, 46 percent of surveyed readers reported working primarily in C#, 14 Build Big-Data Apps in SQL Azure with Federation Get ready to scale out SQL Azure databases beyond today’s 50GB limit with the while 26 percent said their fi rst language is Transact-SQL and ADO.NET elastic sharding features, which are coming in the VB.NET. Nine percent rely most on C/C++, 2011 SQL Azure Federation Community Technology Previews. BY ROGER JENNINGS while only 4 percent work mainly with native 6 (or earlier). 22 Take Unit Testing to the Next Level When it comes to tools and platforms, How to map unit tests to requirements in Visual Studio 2010 to get an overall view of the requirements coverage—as opposed to code coverage—that the tests provide. some interesting things came to light. For BY JEFF LEVINSON instance, 64 percent of respondents reported already working with Visual 32 LANGUAGE LAB Studio 2010—more than those who use Visual Studio 2008 or Visual Studio 2005. ON VB PAGE 32 Also interesting was the prevalence of Web Get Started with Visual Basic Development for Windows Phone 7 development: 66 percent of respondents Dive into Windows Phone 7 development and app design with sample code work with ASP.NET. However, only 34 for a Windows Phone Pivot application. percent reported working with Silverlight. BY JOE KUNK We also asked readers to tell us what ASK KATHLEEN PAGE 42 specifi c topic interested them most in Delve into ASP.NET MVC 3 2011. Two topics drew higher levels of Kathleen Dollard answers your questions about the new Razor view engine, interest than all others: Microsoft dependency injection and extending parts of the framework. development tools/frameworks and BY KATHLEEN DOLLARD programming languages. Behind those we found a second tier of interest in Web DEPARTMENTS development and data-access technolo- 6 Letters to the Editor gies, followed by a third tier of interest in programming methodologies (including 8 DevDisasters Agile), mobile development and Epoch Billing System BY MARK BOWYTZ (THEDAILYWTF.COM) third-party development tools. Was it a surprise that hot-button topics VSTOOLBOX, VSINSIDER 9 DevInsights like Windows Phone 7 and Windows Azure/ VSToolbox: ComponentOne Studio for ASP.NET PAGE 9 cloud-based development didn’t score VSToolbox: Agile Development with Telerik TeamPulse PAGE 10 higher? Not entirely. I expect these nascent VSInsider: Copy and Paste PAGE 12 platforms will gain importance over time. What issues and topics would you most COLUMNS like to see covered in Visual Studio Magazine? E-mail me at [email protected]. 3 Frameworks BY MICHAEL DESMOND 48 Redmond Review BY ANDREW J. BRUST

VisualStudioMagazine.com · March 2011 · VISUAL STUDIO MAGAZINE 3 Online Contents

Get the complete picture —the latest dev , analysis and how-to content—at REDDEVNEWS.COM ADTMAG.COM VisualStudioMagazine.com Amazon Beanstalk Obscuring Azure Skies? NetBeans Dumps Ruby on Rails and our partner sites BY ANDREW J. BRUST BY JOHN K. WATERS With the release of Amazon Beanstalk, VSM Version 7.0 of the NetBeans IDE won’t in the Redmond columnist Brust fi nds that the cloud offerings support Ruby on Rails, the NetBeans Developer Network. from Amazon and Microsoft are moving into community announced. The move has each others’ territory. He breaks down the industry watchers questioning the future of competitive position of Windows Azure. NetBeans under Oracle Corp. management.

EASY FINDIT RedDevNews.com/Brust0311 ADTmag.com/WatersA0311 What we once called FindIT codes are now easy URLs. You’ll see these embedded Living Large with Windows Phone 7 What Does the Future of Hold? throughout Visual Studio Magazine so you can BY KATHLEEN RICHARDS BY JOHN K. WATERS access any additional information quickly. Simply type in VisualStudioMagazine.com/ Microsoft shipped 2 million copies of the The future of Java under the stewardship of followed by the FindIT code into your URL Windows Phone 7 OS in the fourth quarter, Oracle Corp. will be shaped by that address field. (Note that all URLs do not have any and Microsoft says that in January the company’s business model, say Forrester spaces, and they are not case-sensitive.) Microsoft Marketplace surpassed 6,500 apps Research Inc. analysts. and 24,000 registered developers. What Inc. used free Java to sell its hardware, but should Microsoft do to turn its newly minted Oracle—primarily a software company—is mobile platform into a bona fi de hit? likely to see Java in a different light.

RedDevNews.com/Richards0311 ADTmag.com/WatersB0311

VISUALSTUDIOMAGAZINE.COM Microsoft and Open Source Interoperability Java Exploits up in 2010, Cisco Says BY KURT MACKIE BY JOHN K. WATERS Visual Studio 2010 Feature Pack 2 Gianugo Rabellino is the newly appointed The Cisco Systems 2010 Annual Security BY MICKEY GOUSSET senior director of Open Source Communities Report states that in January 2010, Java Visual Studio 2010 Feature Pack 2 is a at Microsoft, tasked with evangelizing the exploits accounted for 1.5 percent of cumulative update for MSDN subscribers company’s open source and interoperability Web malware blocked by the company’s that delivers new testing features for Visual efforts. His work involves collaborating with ScanSafe software. By November, that Studio 2010, including Silverlight 4 app worldwide businesses and communities that number had jumped to 7 percent, testing and a new Coded UI Test Editor. specialize in open source software solutions. according to the company.

VisualStudioMagazine.com/Gousset0311 RedDevNews.com/Mackie0311 ADTmag.com/WatersC0311

Working with Software Factories in C# 4 ID Statement Visual Studio Magazine (ISSN 1537-002X) is published monthly by 1105 Media, Inc., 9201 Oakdale Avenue, Ste. 101, Chatsworth, CA 91311. Periodicals postage paid at Chatsworth, CA 91311-9998, and at additional mailing offi ces. Complimentary BY PATRICK STEELE subscriptions are sent to qualifying subscribers. Annual subscription rates payable in U.S. funds for non-qualifi ed subscribers are: Software factories can streamline activities U.S. $35.00, International $60.00. Annual digital subscription rates payable in U.S. funds for non-qualifi ed subscribers are: U.S. $25.00, International $25.00. Subscription inquiries, back issue requests, and address changes: Mail to: Visual Studio Magazine, P.O. Box by automatically generating code. Learn 2166, Skokie, IL 60076-7866, email [email protected] or call toll free (888) 768-8759, fax number 847-763-9564. Interna- how C# 4 takes advantage of software tional calls 847-763-9135. POSTMASTER: Send address changes to Visual Studio Magazine, P.O. Box 2166, Skokie, IL 60076-7866. Canada Publications Mail Agreement No: 40612608. Return Undeliverable Canadian Addresses to Circulation Dept. or XPO Returns: factory patterns and how abstract- and P.O. Box 201, Richmond Hill, ON L4B 4R5, Canada. delegate-based factories can make for Copyright Statement © Copyright 2011 by 1105 Media, Inc. All rights reserved. Printed in the U.S.A. Reproductions in whole or more fl exible application code. part prohibited except by written permission. Mail requests to “Permissions Editor,” c/o Visual Studio Magazine, 230 California St. Suite 302, San Francisco, CA 94111. VisualStudioMagazine.com/Steele0311 Legal Disclaimer The information in this magazine has not undergone any formal testing by 1105 Media, Inc. and is distributed without any warranty expressed or implied. Implementation or use of any information Platform Questions: Silverlight vs. ASP.NET contained herein is the reader’s sole responsibility. While the information has been reviewed for accuracy, there is no guarantee that the same or similar results may be achieved in all environments. Technical BY PETER VOGEL inaccuracies may result from printing errors and/or new developments in the industry. Practical ASP.NET author Vogel dives into Corporate Address 1105 Media, 9201 Oakdale Ave. Ste 101, Chatsworth, CA 91311 www.1105media.com the debate about the relative value of Silverlight as a Web development platform, Media Kits Direct your Media Kit requests to Matt Morollo, VP Publishing, 508-532-1418 (phone), 508-875-6622 (fax), [email protected] now that Microsoft has thrown its weight behind HTML5 as the platform for universal Reprints For single article reprints (in minimum quantities of 250-500), e-prints, plaques and posters contact: PARS International Phone: 212-221-9595 E-mail: [email protected] www.magreprints.com/QuickQuote.asp Web applications. List Rental This publication’s subscriber list, as well as other lists from 1105 Media, Inc., is available for rental. For more information, VisualStudioMagazine.com/Vogel0311 please contact our list manager, Merit Direct. Phone: 914-368-1000; E-mail: [email protected]; Web: www.meritdirect.com.

4 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com Untitled-1 1 2/9/11 10:36 AM Check out our events at VSLive.com We’ll be in Vegas, at Microsoft HQ and in Orlando in 2011

Letters VisualStudioMagazine.com March 2011 • Volume 21 • No. 3

Editorial Staff Vice President, Doug Barney Editorial Director In January, On VB columnist Joe Kunk wrote a column for the Visual Studio Magazine Editor in Chief Michael Desmond Executive Editor Kathleen Richards Web site entitled “To Comment or Not to Comment.” This article evoked some spirited Managing Editor Wendy Gonchar debate about the costs and benefits of commenting code. Most respondents Associate Managing Editor Katrina Carrasco vigorously supported commenting, but a few offered a counter argument. Tools Editor Peter Vogel

Comments are a clue as to what the developer was thinking when he wrote the Contributing Editors Andrew J. Brust, Ken Cox, Kathleen Dollard, comment. As long as you keep that in mind, comments are useful to have. But I’ Roger Jennings, Joe Kunk, Jeff Levinson, Bill McCarthy, Karl E. Peterson, rather not duplicate info in a comment that’s already evident in the code. Sparse, Patrick Steele, Bill Wagner value-added comments are good. Comments for the sake of comments are bad! Art Staff Arnold Creative Director Scott Shultz Rolling Meadows, Ill. Art Director Joshua Gould Production Staff I’ve seen places where comments have been useful: for example, if you change Director, Print Production Jenny Hernandez-Asandas Production Coordinator Serena Barnes code in a way that looks obvious but something unexpected will happen. However, in general, comments clutter the code that’s written by experts for experts to read. Online/Digital Media Director, Online Media Becky Nagel My guess is that for every time a comment has added to my understanding, there Executive Editor, New Media Michael Domingo have been an equal number of comments that clouded my knowledge of what Site Administrator Shane Lee was actually going on. I almost never read the comments until I have an under- Designer Rodrigo Muñoz standing of what the code is doing. Advertising/Sales Garth VP, Publishing Matt Morollo Regional Sales Manager Chris Kourtoglou New Zealand National Accounts Director William Smith Microsoft Account Manager Danna Vedder

President Henry Allain For every time a comment has Vice President, Publishing Matt Morollo Director of Marketing Michele Imgrund added to my understanding, there have been Online Marketing Director Tracy Cook an equal number of comments that clouded President & Neal Vitale my knowledge of what was actually going on. Chief Executive Offi cer Senior Vice President Richard Vitale & Chief Financial Offi cer Executive Vice President Michael J. Valenti While no one can be completely against comments, I kind of fall into the anti-comment Senior Vice President, Abraham M. Langer camp. I’m a Smalltalk programmer and, to my mind, most Smalltalk code typically Audience Development has too few comments—where too few means practically none. But in Smalltalk & Digital Media Vice President, Christopher M. Coates we (mostly) get away with this because Smalltalk is a good-quality object-oriented Finance & Administration language and object-oriented languages tend to result in more readable code. Vice President, Erik A. Lindgren Information Technology Also, Smalltalk uses named method parameters. Named method parameters make & Application Development code much easier to follow and make comments much less necessary. I’ve never Vice President, Carmel McDonagh Attendee Marketing understood why most of the object-oriented languages that came after Smalltalk Vice President, David F. Myers abandoned named parameters in favor of C-style argument lists. Event Operations Ralph Chairman of the Board Jeffrey S. Klein

Calgary, Alberta, Canada REACHING THE STAFF Staff may be reached via e-mail, telephone, fax, or mail. A list of editors and contact information is also available online at VisualStudioMagazine.com. E-mail: To e-mail any member of the staff, please use the following form: [email protected]. Irvine Offi ce (weekdays, 9:00 a.m. - 5:00 p.m. PT) Visual Studio Magazine wants to hear from you! Send us your thoughts Telephone 949-265-1520; Fax 949-265-1528 about recent stories, technology updates or whatever’s on your mind. 16261 Laguna Canyon Road, Suite 130, Irvine, CA 92618 E-mail us at [email protected] and be sure to include Framingham Offi ce (weekdays, 9:00 a.m. - 5:00 p.m. ET) Telephone 508-875-6644; Fax 508-875-6633 your first and last name, city and state. Please note that letters may be 600 Worcester Road, Suite 204, Framingham, MA 01702 edited for form, fit and style. They express the views of the individual Corporate Offi ce (weekdays, 8:30 a.m. - 5:30 p.m. PT) authors, and do not necessarily reflect the views of the VSM editors or Telephone 818-814-5200; Fax 818-734-1522 1105 Media Inc. 9201 Oakdale Avenue, Suite 101, Chatsworth, CA 91311

Visual Studio Magazine The opinions expressed within the articles and other contents 6 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com herein do not necessarily express those of the publisher. Install LEADTOOLS to eliminate months of research and programming time while maintaining high levels of quality, performance and functionality. LEADTOOLS provides developers easy access to decades of expertise in color, grayscale, document, medical, vector and multimedia imaging development.

‡Silverlight:SXUH6LOYHUOLJKWDQG:LQGRZV3KRQH,PDJLQJ6'. ‡Image Formats & Compression:6XSSRUWVLPDJHIRUPDWVDQGFRPSUHVVLRQVLQFOXGLQJ7,))(;,)3') -3(*-%,*DQG&&,77** ‡Scanning: 7:$,1 :,$  ELW DXWRGHWHFWRSWLPXPGULYHUVHWWLQJVIRUKLJKVSHHGVFDQQLQJ ‡Viewer Controls: Win Forms, Web Forms, WPF, Silverlight, ActiveX and COM. ‡Image Processing:¿OWHUVWUDQVIRUPVFRORUFRQYHUVLRQDQGGUDZLQJIXQFWLRQV VXSSRUWLQJUHJLRQRILQWHUHVWDQGH[WHQGHGJUD\VFDOHGDWD 'HYHORS\RXU ‡Document Cleanup/Preprocessing:$XWRGHVNHZGHVSHFNOHKROHSXQFKOLQHDQGERUGHU DSSOLFDWLRQ UHPRYDOLQYHUWHGWH[WFRUUHFWLRQDQGPRUHIRURSWLPXPUHVXOWVLQ2&5DQG%DUFRGHUHFRJQLWLRQ ZLWKWKH ‡Barcode: $XWRGHWHFW UHDG DQG ZULWH ' DQG ' EDUFRGHV IRU PXOWLWKUHDGHG  ELWGHYHORSPHQW VDPHUREXVW ‡OCR/ICR/OMR: )XOO SDJH RU ]RQDO UHFRJQLWLRQ IRU PXOWLWKUHDGHG  DQG  ELW imaging GHYHORSPHQWZLWK3')3')$;36'2&;0/DQG7H[WRXWSXW technologies ‡Forms Recognition & Processing: $XWRPDWLFDOO\ LGHQWLI\ DQG FODVVLI\ IRUPV DQG XVHGE\ H[WUDFWXVHU¿OOHGGDWD Microsoft, HP, ‡PDF & PDF/A: 5HDGZULWHDQGYLHZVHDUFKDEOH3')ZLWKWH[WLPDJHVERRNPDUNV Sony, Canon, and annotations. ‡Annotations:,QWHUDFWLYH8,IRUGRFXPHQWPDUNXSUHGDFWLRQDQGLPDJHPHDVXUHPHQW Kodak, GE, LQFOXGLQJVXSSRUWIRU',&20DQQRWDWLRQV  Siemens, the US ‡DICOM:)XOOVXSSRUWIRUDOO,2'FODVVHVDQGPRGDOLWLHVGH¿QHGLQWKH',&20VWDQGDUG Air Force and LQFOXGLQJ(QFDSVXODWHG3')&'$DQG5DZ'DWD  Veterans Affairs ‡PACS: )XOOVXSSRUWIRU',&20PHVVDJLQJDQGVHFXUHFRPPXQLFDWLRQHQDEOLQJTXLFN Hospitals. LPSOHPHQWDWLRQRIDQ\',&206&8DQG6&3VHUYLFHV ‡Medical Image Viewer: +LJK OHYHO GLVSOD\ FRQWURO ZLWK EXLOWLQ WRROV IRU LPDJH PDUNXSZLQGRZOHYHOPHDVXUHPHQW]RRPSDQFLQHDQG/87PDQLSXODWLRQ ‡Medical Web Viewer Framework:3OXJLQHQDEOHGIUDPHZRUNWRTXLFNO\EXLOGKLJKTXDOLW\IXOOIHDWXUHGZHEEDVHG PHGLFDOLPDJHGHOLYHU\DQGYLHZHUDSSOLFDWLRQV ‡Medical Workstation Framework: 6HW RI 1(7 PHGLFDO DQG 3$&6 FRPSRQHQWV WKDW FDQ EH XVHG WR EXLOG D IXOO IHDWXUHG3$&6:RUNVWDWLRQDSSOLFDWLRQ ‡3D:&RQVWUXFW'YROXPHVIURP'',&20PHGLFDOLPDJHVDQGYLVXDOL]HZLWKDYDULHW\RIPHWKRGVLQFOXGLQJ0,3 0LQ,3053957DQG66' ‡Multimedia:&DSWXUHSOD\VWUHDPDQGFRQYHUW03(*$9,:0903032**,62'9'DQGPRUH6WUHDP IURP57636HUYHUV ‡DVD:3OD\FUHDWHFRQYHUWDQGEXUQ'9'LPDJHV ‡DVR:3DXVHUHZLQGDQGIDVWIRUZDUGOLYHFDSWXUHDQG8'3RU7&3,3VWUHDPV ‡MPEG Transport Stream::LWK'95IRU8'3DQG7&3,3VWUHDPV DXWROLYHVXSSRUW

Document Barcode Multimedia Silverlight, .NET, Windows Phone, WPF, WCF, WF, C API, C++ Class Lib, COM & more!

Free 60 Day Evaluation! DICOM Medical Form Recognition & Processing Vector www.leadtools.com/vsm (866) 530-3399

Untitled-1 1 2/10/11 9:05 AM

{ SOFTWARE DEVELOPMENT GONE WRONG }

Epoch Billing System

Everybody in the IT department was quite happy—even a little surprised—with how well the outsourced project to replace Caught off guard, Jeff just stared at the legacy billing system was progressing. Well, actually, the project managers the function for a good 10 minutes, trying to figure weren’t all that surprised. Over the past four it out. When he did, it hit him like a ton of bricks. months, they’d pumped out reams of specs and design documents, often boasting that their level of planning hadn’t been seen private static int convertDate management team, just out of curiosity, to since the Apollo missions. So, for them, the (int day, int month, int year) see if the fi x had been made. To his surprise, fact that everything was turning out as { it hadn’t been addressed—nor would it designed spoke volumes about the success be any time soon. Apparently the “bug” of their planning and processes. int[] months = new int[] {0,31,59,90,120,151, was downgraded to a feature request 181,212,243,273,304,334}; because—in the eyes of the project New Billing Code managers—if an application functioned Jeff and the other developers who were return (((year - 1970) * DAY * 365) + (((year as it was designed, there wasn’t a need to stuck supporting the existing billing - 1970)/4) * DAY) + (months[month - 1] go back in and change it. VSM system until the big cutover (still a few * DAY) + ((day-1) * DAY)); months away) wanted to see what this } super system looked like under the hood. Caught off guard, Jeff just stared After all, because they were expected to at the function for a good 10 support the new system once it came minutes, trying to fi gure it out. When online, shouldn’t they at least have an he did, it hit him like a ton of bricks. understanding of how the underlying Rather than using the built-in C# date code worked? functions, the developer had opted to The developers made their case for convert a date into its Unix Epoch—the months before the project managers gave number of seconds elapsed since Jan. 1, up on their “it’s not done yet” rhetoric and 1970—and work from there. reluctantly handed over a few modules that Jeff had to admit, the solution was a they’d deemed bug-free. little bit genius. Unfortunately, it wasn’t When Jeff got his hands on the code, a fi t because the new system was one line in particular caught his eye: running on a Windows server. So Jeff did int strElapsedDays = (convertDate(intDay1, his duty and raised the matter with the intMonth1, intYr1) - convertDate(intDay2, project management team so it could intMonth2, intYr2)) / DAY; be added to the bug-fi x queue for the offshore team. Unusual Process Weeks later, Jeff followed up with Knowing that C# had built-in functions to one of the members of the project easily determine the span of days between two dates, Jeff thought the approach was a little strange. Once he tracked down Tell Us Your Tale convertDate, things got even weirder: public const int DAY = 86400; Mark Bowytz is a contributor to the popular Web site The Daily WTF (thedailywtf.com). He has public const int WEEK = 604800; more than a decade of IT experience and is currently a systems analyst for PPG Industries. Have you experienced the darker side of development? E-mail your tale to Executive Editor Kathleen public const int YEAR = 31449600; Richards at [email protected].

8 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com 0211vsm_GrapeCity_Insert.indd 1 1/11/11 2:45 PM 0211vsm_GrapeCity_Insert.indd 2 2/4/11 3:12 PM

ComponentOne Studio Enterprise for ASP.NET AJAX VSToolbox ComponentOne LLC Web: componentone.com Phone: 800-858-2739 ComponentOne Studio Price: $895.00 (standard), $1,195.00 (with Platinum Support) for ASP.NET AJAX Quick Facts: A suite of ASP.NET ComponentOne delivers a solid set of business-related controls with all the functionality controls targeting the fundamentals of creating Web Forms developers need, but the reporting tools make this suite unique. Pros: A complete set of business- related controls that would meet the BY PETER VOGEL formats, and there’s also a designer— needs of most ASP.NET developers; In reviewing control suites, it would be available from the control’s SmartTag—that excellent support for reporting

nice to have some hard metrics to use to includes presets for the most common Cons: Overall a smaller package ASP.NET Components compare them. But even something as data-entry tasks you’ll want to support. than others; omits some more obvious as the number of controls is hard The suite includes both a Calendar esoteric controls to quantify. The ComponentOne suite adds control and a Scheduling control. I also about three-dozen controls to your Visual liked the suite’s Window control for Studio toolbox—about a half-dozen less creating client-side dialog windows (read In a world that depends increasingly on than, for instance, the Telerik ASP.NET more on this in my ToolTracker blog). client-side code, all of the ComponentOne suite. But ComponentOne has a Gauge Unlike most suites, ComponentOne controls have a flexible client-side object control that Telerik does not—and the includes a complete reporting solution: A model. You add client-side event handlers ComponentOne control can display as a report designer and a ReportViewer by selecting the event you want from the dial, a slider or one of 12 other presets. So control. ReportViewer supports importing control’s Properties window. The control does the ComponentOne Gauge control Crystal, SQL Server Reporting Services and then writes out the skeleton of the handler count as one control or 12? Access reports to create new ComponentOne and drops you into it in Source View, where In the end, it’s what controls you’ll reports. Because the object model for you have access to the full power of the actually use and how productive those ComponentOne ASP.NET reports is the Visual Studio editor. (By comparison, other controls make you that count. For instance, same as the model for Windows Client control suites pop up a custom editor that you can use the ASP.NET Validator reports, you can transfer code between the locks you out of Visual Studio.) Along with controls to ensure that your users enter the two environments. For more customized the Window control, I’ll be looking at the right data. Or you can just drop one of the document generation, a PDF control suite’s JavaScript support in general in the ComponentOne dedicated edit controls (which you won’t find in other suites) lets ToolTracker blog. (one each for date, numeric, currency and you generate documents from your It doesn’t seem to be possible to integrate percent entry) on your form. For more application, including adding attachments. the suite’s Help information into the Visual flexibility, you can use the suite’s You can even encrypt your PDF docu- Studio Help system—you’ll have to visit the MaskedInput control. The MaskedInput ments, making them a good choice for ComponentOne Web site to read the control supports a wide variety of input distributing private data. documentation (or download the PDF file). This is a package aimed squarely at the business developer: Controls that you’ll use on almost every project. These are great controls with excellent functionality, and they’re designed to make developers more productive. There aren’t many of the more exotic controls that you’ll see in other packages. My concern is that, for roughly the same cost—and giving up the PDF control—I could get a package that includes a Cloud control for tag-based navigation, a Captcha control, or a spell checker. If I’m building business applica- tions rather than a social-media tool, do I need those controls? I suspect that I don’t, and it’s just my inner geek crying out for The ComponentOne ReportDesigner interface is similar to those of other major reporting tools. new toys. But I’d still want them. VSM

VisualStudioMagazine.com · March 2011 · VISUAL STUDIO MAGAZINE 9

Telerik TeamPulse

VSToolbox Telerik Inc. Web: telerik.com Phone: 888-365-2779 Supporting Agile Development Price: $249 (Free Community Edition available, limited to one with Telerik TeamPulse project and five users) TeamPulse provides economical support for teams implementing the Quick Facts: A Web-based Agile methodology, but it doesn’t integrate with Visual Studio. Silverlight application that supports Agile development teams throughout the project lifecycle BY PETER VOGEL on your computer with specific options set Pros: Easy to install and use; Communicating and sharing information and open ports. You must also have some per-user pricing; easy to customize;

Tools is critical to the Agile development version of SQL Server installed—I used bidirectional integration with Team process—especially if all team members SQL Server Express. On my computer I Foundation Server and stakeholders aren’t in the same had all of the prerequisites, but the Cons: No integration with Visual Agile Development Development Agile building. So, for information to be shared, installation guide doesn’t assume that—the Studio; assumes specific Agile team members need to record that steps to address any options you might be practices (for instance, user stories information somewhere accessible to the missing are described in the user manual. for requirements gathering) whole team. Time spent recording After that you need to go to the TeamPulse information is, of course, time spent away site on your computer (available from Start from application development. menu) and activate your license. Be aware This is where TeamPulse comes in—by that you’ll need the e-mail and password ToolTracker reducing the pain involved in recording, for an account on the Telerik site. Then accessing and sharing information. Once you’re ready to go. Tools for Parallel Processing you’ve installed TeamPulse on your I found the UI intuitive, but it does Parallel processing is moving from computer, you have a Silverlight-enabled assume that you’re familiar with Agile an interesting “nerd thing” to a core Web site that supports the standard tasks terms, such as “Table Stakes.” After I development tool. In a ToolTracker in the Agile development process. stopped looking for a Save button (entries interview, Stephen Forte—chief TeamPulse understands Agile projects, are auto-saved), it took only a few seconds strategy offi cer at Telerik—said from gathering ideas and requirements to figure out how to enter or review data. I multicore development would through planning, scheduling and activity didn’t have to refer to the Help guide, “hands down” have the biggest tracking. TeamPulse also includes a Best though I may need to in future uses. impact on developers. Microsoft has Practices Analyzer, a rules-based tool for The bad news is there’s no integration since delivered Parallel LINQ (PLINQ) automatically checking the quality of your with Visual Studio. There is, however, and the Task Process Library (TPL). TeamPulse content. bidirectional synchronization with Team But where are the third-party There are a number of prerequisites for Foundation Server. Another plus: the tools? In November 2010, Progeneric installing TeamPulse: IIS must be installed price point is relatively low (per-user Systems Inc. launched its .NET pricing), even before Template Library, which builds on volume discounts. top of the TPL. But the company’s When just having products are described in such everyone in the same general terms—and without any room stops working, sample code—that it’s hard to you should consider determine what, exactly, it’s selling. integrating the Telerik, meanwhile, is exploring TeamPulse product using PLINQ in its RadGridView for into your team’s Windows Presentation Foundation Agile practices. VSM to speed up querying. That may be where PLINQ meets the toolspace— Peter Vogel (peter.vogel@ not tools for parallel processing, but phvis.com) is the tools rather tools that take advantage of editor for Visual Studio it. Even there, the toolspace is still Magazine and a principal immature: It requires some in PH&V Information additional code to make PLINQ TeamPulse takes advantage of Silverlight to deliver an intuitive UI Services, specializing in work with the RadGridView. —P.V. with an Office-like ribbon at the top that works in most browsers. ASP.NET development.

10 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com DESIGN Design Applications That Help Run the Business

Our xamMap™ control in Silverlight and WPF lets you map out any geospatial data like this airplane seating app to manage your business. Come to infragistics.com to try it today!

Infragistics Sales 800 231 8588 Infragistics Europe Sales +44 (0) 800 298 9055 Infragistics India +91 80 4151 8042 @infragistics

Untitled-6 1 11/10/10 11:41 AM

VSInsider BY MARK MICHAELIS

Copy and Paste

solutions already on the market before Visual Developers who lack the time or resources Studio Team Build was released. Similar to research and maintain a host of third-party solutions included CruiseControl.NET in solutions often feel the same way. open source and TeamCity for purchase. Given the prevalence of available solutions, Entering New Markets often for free, why would Microsoft develop Then there’s the allure of new business. There similar proprietary solutions to solve are many cases where Microsoft duplicates Microsoft & Microsoft Open Source (seemingly) the same problems? functionality available from third-party or open source solutions in order to gain a Make It Microsoft foothold in a new market. Let’s face it, there are cases where Microsoft’s Visual Studio Team Build is one such control over Visual Studio development example. When Visual Studio Team System and the languages it supports enables the emerged as a solution for application company to simply do things better. lifecycle management (ALM), there was no In the object-relational mapping space, significant contender that offered automated On occasion I’ve been surprised that it wasn’t until there were fundamental build, project tracking and collaboration, Microsoft has put significant effort into language features in the form of LINQ that source code control, client-side developer developing features and functionality developers began to experience a fully tooling, and a reporting module that already available within the developer object-oriented API that interfaced with spanned the overall solution. Visual Studio ecosystem. Frequently, the functionality is the relational database. Through the Team System provided just such an offering, even available for free via open source, so combination of LINQ and the Entity along with the integration across its parts there doesn’t really seem to be a “market” Framework, mapping a strongly typed, that allowed them to work together. that Microsoft is trying to enter or gain a object-oriented programming API on top Although virtually all of the individual business advantage in. And yet, Microsoft of a relational database became possible. categories of tools included with Visual invests significant time and money in And, because developers outside of Studio Team System were available from creating functionality similar to what’s Microsoft have essentially no ability to alternative sources, none provided the already available—frequently even using the modify the C# language, only Microsoft integration between the tool sets. In choosing open source implementation as a reference could create a broad solution that penetrated to build Visual Studio Team Build as part for requirements of what to do (or not to do). the core of the language and integrated of Visual Studio Team System— even when Let’s consider a few examples. When the with Visual Studio so comprehensively. there were competing third-party solutions— Entity Framework was released, NHibernate Microsoft frequently chooses to duplicate Microsoft was intentionally entering the (open source) and LLBLGen Pro, among what might already be available in open ALM space with its own offering. others, were well-established players in the source and third-party solutions simply There are, of course, numerous reasons market. Ironically, Microsoft itself released because it’s in a position to do it better. why Microsoft would reproduce functionality LINQ to SQL at the same time as the Entity There’s also the benefit of being already available from third parties or open Framework, but later ended development built-in. For many developers, installing source solutions. But most of those reasons on the technology. third-party software—especially open boil down to three themes: Microsoft is in Or consider Visual Studio Unit Testing, source software—is considered a security a unique position to accomplish work that which was launched despite well-established risk and is prohibited by IT. These developers others can’t, deployment of a Microsoft open source alternatives, including NUnit, are clamoring for , best-practice solution is a customer requirement, or a XUnit and MbUnit. There were also software development processes and tooling market opportunity has compelled third-party unit testing solutions like (such as Visual Studio Unit Testing), Microsoft to move into a new space. VSM TestDriven.NET and Resharper. which are built into Visual Studio and Finally, MSBuild fairly closely duplicated require no additional deployment or Mark Michaelis started IntelliTechture Corp. and the functionality and approach provided by configuration work. Developers like these serves as chief technical architect and trainer. He’s NANT (open source). Similarly, when it celebrate when Microsoft provides its own been a Microsoft MVP for C#, Visual Studio Team came to creating an unattended build server, solution to something that’s perhaps System and the Windows SDK since 1996. In 2007, there were and continue to be numerous already freely available. he was recognized as a Microsoft regional director.

12 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com DEVELOP Rich Business Intelligence Applications in WPF and Silverlight

Robust Pivot Grids for WPF and Silverlight let your users analyze data to make key business decisions. Visit infragistics.com to try it today!

Infragistics Sales 800 231 8588 Infragistics Europe Sales +44 (0) 800 298 9055 Infragistics India +91 80 4151 8042 @infragistics

Untitled-6 1 11/10/10 10:57 AM VSM COVER STORY

Build Big-Data Apps in SQL Azure with Federation Get ready to scale out SQL Azure databases beyond today’s 50GB limit with the Transact-SQL and ADO.NET elastic sharding features, which are coming in the 2011 SQL Azure Federation Community Technology Previews. BY ROGER JENNINGS

14 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com EXPERIENCE Beautiful Data Visualizations That Bring Your Data to Life

Use our Motion Framework™ to see your data over time and give your users new insight into their data. Visit infragistics.com/motion to try it today!

Infragistics Sales 800 231 8588 Infragistics Europe Sales +44 (0) 800 298 9055 Infragistics India +91 80 4151 8042 @infragistics

Copyright 1996-2010 Infragistics, Inc. All rights reserved. Infragistics, the Infragistics logo and NetAdvantage are registered trademarks of Infragistics, Inc. Motion Framework is a trademark of Infragistics, Inc.

Untitled-1 1 1/11/11 1:39 PM COVER STORY Sharding Databases

Microsoft recommends that you scale out your SQL Azure databases by partitioning them horizontally into smaller instances, called shards, running on individual SQL Azure database instances, and group the shards into federations.

An urban myth that relational databases and Sharding increases database capacity and query performance, because each added SQL Azure database brings its own and SQL can’t achieve Internet-scale of terabytes—or virtual CPU. Microsoft Software Architect Lee Novik first described petabytes—has fostered a growing “NoSQL” developer SQL Azure sharding details in his “Building Scale-Out Applications community and a raft of new entity-attribute- with SQL Azure” session (bit.ly/i7EfJf) at the Microsoft Professional Developers Conference 2010, held last October in Redmond. value, also known as key value, data stores. The Horizontal partitioning isn’t new to SQL Server. Horizontally Microsoft SQL Azure team gave credence to the partitioning SQL Server 7.0 and later tables to multiple files and myth by limiting the maximum size of the initial filegroups improves performance by reducing average table and index size. Placing each filegroup on an individual disk drive Business Edition of the cloud database to just speeds T-SQL queries. Partitioning also streamlines backup and 10GB. SQL Azure adds a pair of secondary data maintenance operations by reducing their time-window length. replicas to assure high availability, and the team SQL Server 2005 automated the process with the CREATE PAR- TITION FUNCTION command, which lets you automatically map cited performance issues with replication as the the rows of a table or index into specified partitions based on the early size-limiting factor. values of a specified column. You design a CREATE PARTITION SCHEME to determine how to assign partitioned files to filegroups. Today, you can rent a 50GB SQL Azure database for $499.95 per SQL Server partitioned views make rows of all partitions appear as month, but the SQL Azure Team isn’t talking publicly about future a single table; distributed partitioned views enable partitioning scale-up options. Instead, Microsoft recommends that you scale data across multiple linked servers, not just filegroups, for scaling out your SQL Azure databases by partitioning them horizontally out. SQL Server 2000 introduced updateable distributed views with into smaller instances, called shards, running on individual SQL distributed transactions, and SQL Server 2000 SP3 used OLE DB to Azure database instances, and group the shards into federations. optimize query-execution plans for distributed partitioned views. A group of linked servers that participates in distributed partitioned views is called a “federation.” The partitioning Table 1. Sample Values of a sys.federation_member_columns View for column, whose values determine the partition to which Orders_Federation from SalesDB the row belongs, must be part of the primary key and can’t be an identity, timestamp or default column. The following abbreviated system view specifies partitioning 100,000 Customer records into 50 Federation Members numbered 51 through 100 with sequential bigint New Taxonomy Federation Key values starting at 1. If the Federation Root name is SalesDB, the Scaling out SQL Azure with federated database instances Federation Members will be named SalesDB_51 through SalesDB_100. follows a pattern similar to that for on-premises SQL federation_id member_id federation_key_name range_low range_high Server, but is subject to several important limitations. For example, SQL Azure doesn’t support linked servers, - 9,223,372,036, 1 51 CustomerID 2000 854,775,807 CREATE PARTITION FUNCTION, CREATE PARTI- TION SCHEME, cross-database joins, distributed 1 52 CustomerID 2000 4000 (cross-database) transactions, OLE DB or the T-SQL 153 CustomerID 4000 6000 NewSequentialID function. These restrictions require architectural changes for SQL Azure federations, starting 1 … CustomerID … … with this new taxonomy: 1 100 CustomerID 98000 NULL ■ Federation consists of a collection of all SQL Azure database instances that contain partitioned data For this example, range_low values are inclusive and range_high values are exclusive having the same schema. The T-SQL script in “How to the given Federation Member. NULL represents the maximum bigint value +1. to Create a Federation with Customers, Orders and Bigint values range from -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) so negative CustomerID values (if present) would parti- OrderItems Tables” (p. 17) shows a T-SQL script to tion into SalesDB_51 and values > 100,000 would fall into SalesDB_100. Starting create an Orders_Federation with a schema based member_id values at 51 enables future sharding with negative Federation Key values on three tables of the Northwind sample database. to Federation Members SalesDB_01 to SalesDB_50. Random uniqueidentifier (GUID) ■ Federation Members comprise the collection of values require accommodating the entire domain of a 128-bit integer, 00000000- SQL Azure databases that contain related tables 0000-0000-0000-000000000000 to FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF. An with partitioned data, called Federated Tables. A advantage of GUID Federation Keys is that they eliminate hotspots in a shard holding Federation Member also can contain replicated recently entered records. Note that this information is preliminary and might change lookup tables (Products) that provide supplementary before the version 1 CTP releases. data that’s not dependent on the Federation Key.

16 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com Untitled-7 1 2/22/11 12:53 PM Untitled-7 1 2/22/11 12:53 PM COVER STORY

Scaling out SQL Azure with federated database instances follows a pattern similar to that for on-premises SQL Server, but is subject to several important limitations.

■ Federation Key is the primary key value (CustomerID) that and OrderItems). AU clusters can’t be separated in the parti- determines how data is partitioned among Federated Tables, tioning (sharding) process or when moving data between each of which must contain the Federation Key in their pri- Federation Members. mary key, which can be a big integer (bigint, a 64-bit signed ■ Federation Root is the initial database that contains metadata integer) or GUID (uniqueidentifier) data type. For example, for specifying the Partitioning (sharding) Method, range of the Orders and OrderItems tables have composite primary valid values for the Federation Key, and minimum/maximum keys (OrderID + CustomerID and OrderID + ProductID + Federation Key value ranges for each Federation Member. CustomerID, respectively). ■ Partitioning Method determines whether the Federation Key ■ Atomic Unit (AU) is a cluster of a single parent table (Custom- is generated by the application or the data tier. For this article’s ers) row and all related rows of its dependent tables (Orders example, the data tier uniqueidentifier data type provides

How to Create a Federation with Customers, Orders and OrderItems Tables

Here’s a preview of a T-SQL script to create -- Create a federated Orders table PRIMARY KEY NONCLUSTERED (ProductID) a traditional (Northwind-style) sample sales CREATE TABLE Orders( GO orders schema with federated Customers, CustomerID uniqueidentifier NOT NULL, Orders and OrderItems tables and a OrderID uniqueidentifier NOT NULL, -- Create a federated OrderItems table. Products reference table (not federated) for OrderDate datetime NOT NULL) CREATE TABLE OrderItems( sharding. The script has been tested (with -- ... Additional non-key fields CustomerID uniqueidentifier NOT NULL, Federation-specific and SQL Azure-specific FEDERATE ON (CustomerID) OrderID uniqueidentifier NOT NULL, keywords commented) in SQL Server 2008 GO ProductID uniqueidentifier NOT NULL, R2 Management Studio: OrderItemDate datetime NOT NULL, -- Connect to 'master'. /* Note that CustomerID, the federation key, must be -- ... Additional non-key fields CREATE DATABASE SalesDB (EDITION='BUSINESS', part of all unique indexes but not non-unique CONSTRAINT FK_OrderItems_Orders_Customers MAXSIZE=50GB) indexes. SQL Azure requires a clustered index on FOREIGN KEY (OrderID, CustomerID) each table, but clustered indexes on REFERENCES Orders(OrderID, CustomerID), -- Connect to 'SalesDB' and create Federation. uniqueidentifier CONSTRAINT FK_OrderItems_Products FOREIGN KEY CREATE FEDERATION Orders_Federation (RANGE columns cause a performance hit from page (ProductID) REFERENCES Products(ProductID)) uniqueidentifier) splitting. FEDERATE ON (CustomerID) GO */ GO CREATE CLUSTERED INDEX IX_OrderDate /* Connect to 'Order_Federation' federation member ON Orders(OrderDate) CREATE CLUSTERED INDEX IX_OrderItemDate ON covering CustomerID = 0. */ ALTER TABLE Orders ADD CONSTRAINT PK_Orders OrderItems(OrderItemDate) USE FEDERATION Orders_Federation(00000000-0000-0000- PRIMARY KEY NONCLUSTERED (OrderID, CustomerID) ALTER TABLE OrderItems ADD CONSTRAINT PK_OrderItems 0000-000000000000) WITH RESET GO PRIMARY KEY NONCLUSTERED GO (OrderID, CustomerID, ProductID) /* Create a reference (replicated, not federated) GO -- Create Customers Products table. */ The preceding code was adapted from CREATE TABLE Customers( CREATE TABLE Products( code found in a posting by Cihan Biyikoglu, CustomerID uniqueidentifier NOT NULL, ProductID uniqueidentifier NOT NULL, Microsoft program manager for SQL Azure. CompanyName nvarchar(50) NOT NULL) SupplierID uniqueidentifier NOT NULL, The SQL Azure team had not released the -- ... Additional non-key fields ProductName nvarchar(50) NOT NULL, SQL Azure Federation version 1 Community FEDERATE ON (CustomerID) Package nvarchar(50) NOT NULL) Technology Preview (CTP) at publication. GO -- ... Additional non-key fields Post-version 1 CTPs are expected to sup- GO port Federation Keys of the bigint data CREATE CLUSTERED INDEX IX_Customers type. See Biyikoglu’s Dec. 11, 2010, posting, ON Customers(CompanyName) CREATE CLUSTERED INDEX IX_Products_Product- “How to scale out an app with SQL Azure ALTER TABLE Customers ADD CONSTRAINT PK_Customers Name_Package Federations … The Quintessential Sales DB PRIMARY KEY NONCLUSTERED (CustomerID) ON Products(ProductName, Package) with Customer and Orders” (bit.ly/e8eB3L), GO ALTER TABLE Products ADD CONSTRAINT PK_Products for more information. —.J.

VisualStudioMagazine.com · March 2011 · VISUAL STUDIO MAGAZINE 17 COVER STORY Sharding Databases

The SQL Azure team wants to manage scaling federations out and in, as well as leveling the sizes of Federation Member databases.

Preview (CTP) of version 1 in 2011. The current plan is for the CTP 1 Listing 1. Connecting to the Federation Root Database to support partitioning by uniqueidentifier FederationKey values only; // Create a Connection to the Federation Root a post-CTP 1 drop will add bigint FederationKeys (see Table 1, p. 16). SqlGuid fedKeyValue = customerId; SqlConnection connection = new SqlConnection(@"Server=tcp:sqlAzureURI; New T-SQL Key Words for Scripting SQL Azure Federation Database=SalesDB;User ID=mylogin@myserver; The following new T-SQL syntax will support SQL Azure Federations Password=mypassword") in the version 1 CTP (see “How to Create a Federation with Customers, connection.Open(); Orders and OrderItems Tables,” p. 17): // Route to the Specific Customer’s Atomic Units CREATE FEDERATION Federation_Name(Federation_Key_Name RANGE uniqueidentifier) SqlCommand command = connection.CreateCommand()) DROP FEDERATION Federation_Name command.CommandText = CREATE TABLE Table_Name FEDERATE ON (Federation_Key_Name) "USE FEDERATION Orders_Federation(" + fedKeyValue.ToString() + ") WITH RESET"; USE FEDERATION Federation_Name (Fed_Key_Value) WITH FILTERING=ON command.ExecuteNonQuery(); USE FEDERATION Federation_Name (Fed_Key_Value) WITH FILTERING=OFF ALTER FEDERATION Federation_Name SPLIT AT(Fed_Key_Value) random 128-bit (16-byte) GUID values, which balance additions ALTER FEDERATION Orders_Federation DROP AT(Fed_Key_Value) across multiple Federation Members. Sequential bigint values The FILTERING=ON option restricts the visibility of AUs to the are easier to read, but require a feature similar to the SQL specific cluster specified by Fed_Key_Value; FILTERING=OFF Server Denali Sequence object to generate identity values that makes all AUs in the Federation Member visible for bulk opera- are unique over multiple Federated Tables. tions. The ALTER FEDERATION … SPLIT AT Fed_Key_Value The SQL Azure Team plans to release SQL Azure Federation fea- instruction lets you balance the size of Federation Members that tures in piecemeal fashion starting with a Community Technology have grown substantially larger than the average by moving AUs

How to Get Data from the Appropriate Atomic Unit in a Federation Member

SQL Azure Federations version 1 Commu- // Route to Specific Customer (customerId=@customerId1)", connection); nity Technology Preview (CTP) will include using (SqlCommand command = connection. detailsDataAdapter.SelectCommand.Parameters.Add( a sample ADO.NET sharding library and CreateCommand()) "@customerId1", SqlDbType.UniqueIdentifier); code examples to manipulate federated { detailsDataAdapter.SelectCommand.Param- data. The following procedure creates an command.CommandText = eters[0].Value ADO.NET DataSet from an Atomic Unit "USE FEDERATION Orders_Federation(" + = customerId; consisting of the Customers record and fedKeyValue.ToString() + ") WITH RESET"; detailsDataAdapter.Fill(data, "OrderItems"); all Orders and OrderItems records for the command.ExecuteNonQuery(); customer specified by the customerId } connection.Close(); parameter. The only code that differs from connection.Dispose(); that for populating DataSets from conven- // Populate data from Orders table to the DataSet. tional SQL Azure tables is within the using SqlDataAdapter masterDataAdapter = ... block in lines 19 and 20: new SqlDataAdapter(@"SELECT * FROM Orders WHERE } private void GetData(SqlGuid customerId) (customerId=@customerId1)", connection); The preceding code was adapted from { masterDataAdapter.SelectCommand.Parameters.Add( code found in a posting by Cihan Biyikoglu, SqlGuid fedKeyValue = customerId; "@customerId1", SqlDbType.UniqueIdentifier); Microsoft program manager for SQL Azure. masterDataAdapter.SelectCommand.Param- The SQL Azure team had not released the // Create a Connection to the Federation Root eters[0].Value = SQL Azure Federation version 1 Community SqlConnection connection = customerId; Technology Preview (CTP) at publication. new SqlConnection(@"Server=tcp:sqlAzureURI; masterDataAdapter.Fill(data, "Orders"); Post-version 1 CTPs are expected to sup- Database=SalesDB;User ID=mylogin@myserver; port Federation Keys of the bigint data Password=mypassword") // Add data from the OrderItems table to the type. See Biyikoglu’s Dec. 11, 2010 posting, connection.Open(); DataSet. “How to scale out an app with SQL Azure SqlDataAdapter detailsDataAdapter = Federations … The Quintessential Sales DB // Create a DataSet. new SqlDataAdapter(@"SELECT * FROM with Customer and Orders” (bit.ly/e8eB3L), DataSet data = new DataSet(); OrderItems WHERE for more information. —R.J.

18 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com Untitled-5 1 2/2/11 1:18 PM COVER STORY Sharding Databases

The Microsoft Azure Marketplace DataMarket is a classic big-data application, so it’s a good bet that Pablo Castro and his WCF Data Services team are hard at work updating the RESTful OData API.

greater than Fed_Key_Value into a new Federation Member. SPLIT ■ Multicolumn Federation Keys to enable federation on, for AT and DROP AT operations work with AUs exclusively. example, CustomerID+AccountID. The version 1 CTP ADO.NET sharding library will include sample Java developers have had the Hibernate.Shards library for several Microsoft .NET Framework-based code for connecting to the Federa- years; it’s now matured to version 3.0.0 beta 2 on the JBoss.org Web site. tion Root, which automatically routes the connection to the appropriate Developer Oren Eini, more commonly known by the alias “Ayende Federation Member based on information from the sys.federation_ Rahien,” rejuvenated the NHibernate Shard project for .NET last member_columns view, and retrieves AUs as ADO.NET DataSets. fall. SharpFellow blogger John Rayner demonstrated NHibernate Here’s the generic code for instructions that open a connection to a Shards with SQL Azure and provided source code in his “Sharding Federation Member whose member_id specified by dbname_postfix: into the Cloud” post (tinyurl.com/4kmvs6p). Rayner wrote in his post: SqlConnection cn = new “NHibernate.Shards is an extension to the well-known O/RM, which SqlConnection("Server=tcp:servername.db.windows.net;" + allows a logical database to be partitioned across multiple physical "Db=SalesDB_" + dbname_postfix + databases and servers. It’s a port of the Hibernate.Shards project, as ";User ID=username;Password=password;" + with lots of things in NHibernate. I thought it would be interesting "Trusted_Connection=False;Encrypt=True"); to see how well it worked against SQL Azure. It turned out to be not cn.Open(); interesting at all ... just plain easy!” ... Microsoft has most of its object/relational mapping (O/RM) eggs The code in Listing 1 (p. 18) automatically routes the connection to in the Entity Framework basket. You can expect the teams that own the appropriate Federation Member for a particular FederationKey data connectivity to SQL Server and SQL Azure—including the value by connecting to the Federation Root database and executing ADO.NET Team that’s responsible for Entity Framework—to expand a T-SQL USE FEDERATION FederationName(FederationKey) instruc- their repertoire to handle SQL Azure Federation. The Microsoft tion (see “How to Get Data from the Appropriate Atomic Unit in a Azure Marketplace DataMarket is a classic big-data application, so Federation Member,” p. 18). it’s a good bet that Pablo Castro (a Microsoft software architect in At this point, you can issue parameterized select queries with the SQL Server Group) and his WCF Data Services team are hard CommandText such as SELECT * FROM Orders WHERE at work updating the RESTful OData API. Synchronizing SQL (CustomerId=@customerId). Note that SQL Azure supports USE Azure Federations across datacenter boundaries (geolocations) and FEDERATION but not USE DatabaseName instructions. with on-premises SQL Server databases will keep Liam Cavanagh .NET projects based on CTP version 1 that require rows from (Microsoft senior program manager for SQL Azure Data Sync and more than one shard to populate a DataSet from a SELECT query Microsoft Sync Framework) and his team busy for at least a few will require client-side code that executes UNION ALL queries to months. Watch these groups’ blogs closely for signs of progress on aggregate the AUs. Obtaining aggregate values such as SUM(), Federation-enabled connectivity for SQL Azure. AVG(), MIN(), MAX() and COUNT() with CTP version 1 also Don’t believe everything you hear from the “NoSQL” crowd about will require multiple queries that increment accumulator variables the demise of SQL databases for big data. Microsoft intends to protect with values from individual Federation Members. its database turf in the cloud from naysayers who claim it won’t scale past 50GB. The company’s approach is to automate the sharding Automagical Online Partitioning and Other New Features process and its management for scaling out and back in to minimize A primary SQL Azure selling point is minimizing—and ultimately human intervention. Get ready to take advantage of SQL Azure eliminating—all common physical database management tasks by Federations by downloading the CTP 1 as soon as it’s available, and subscribers. The SQL Azure team wants to manage scaling federations then plan your route to high-scalability relational data nirvana. out and in, as well as leveling the sizes of Federation Member databases. Credits: Thanks to Cihan Biyikoglu, program manager for SQL According to Lev Novik and other SQL Azure team members, CTP Azure, for providing important technical insights about SQL Azure versions later than version 1 will add at least the following features Federations and the forthcoming CTPs; visit his “SQL Azure—Your to SQL Azure Federations: Data in the Cloud” blog (bit.ly/giiVdS) for up-to-date information on ■ A new ALTER FEDERATION Federation_Name MERGE (Fed_ SQL Azure Federation developments. You’ll find additional references Key_Value) instruction to enable repartitioning when scale-down to his posts, as well as other sharding approaches for SQL Azure, is appropriate for reducing database subscription expense. Hibernate and NHibernate, in the OakLeaf Systems Resource Links ■ Auto repartitioning to enable SQL Azure to manage reparti- for SQL Azure Federations and Sharding Topics (bit.ly/hINRbX) post. VSM tioning the federated databases online with SPLIT and MERGE operations based on a policy you specify, such as Federated Roger Jennings is the principal developer and writer for OakLeaf Systems and Table size or query execution time. the author of more than 30 books about Windows NT and Windows Server ■ Fan-out queries so that a single query will be able to process 2000, SQL Server, Microsoft Access, ADO.NET data connectivity and Web results gathered across many Federation Members. services. He’s the curator of the OakLeaf Systems blog and a contributing editor ■ Schema management to allow multiversion schema deployment for Visual Studio Magazine, and he occasionally writes for RedDevNews.com. and management across Federation Members. Jennings is a member of the Microsoft Partner Network.

20 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com Untitled-5 1 2/2/11 1:18 PM FEATURE Take Unit Testing to the Next Level

How to associate unit tests with requirements in Visual Studio 2010. BY JEFF LEVINSON

Many teams today use Agile techniques such as Test-Driven Why does this matter? Unit tests are tra- Development (TDD), eXtreme Programming or just a heavy use of ditionally used to verify methods without regard for the functionality the methods are unit testing to verify functionality. One of the gaps in unit testing is part of. However, as unit tests are relied on the ability to map unit tests to requirements to get an overall view of more heavily, it’s helpful to be able to show how many unit tests were written and exe- the requirements coverage (as opposed to code coverage) that the cuted against each requirement. The problem unit tests provide. with doing this is that unit tests are code: Consider the following situation: Your application has 10 requirements that need to be They don’t actually map to a requirement built. There are 100 unit tests that cover all of the methods in your application, giving you and in fact are completely independent of 100 percent coverage of your code. But in terms of providing information on the require- any given requirement. So, what can you do? ments coverage, who knows? Maybe you’ve covered nine of the requirements many times Team Foundation Server (TFS) provides over, but one requirement only has one test that relates to it. the first (that I know of) capability of asso- ciating any automated test—not just unit tests, but load tests and generic tests—with a requirement. This gives you a complete understanding of how many functional tests versus unit tests were created and executed for any given requirement. This article will show you how to do this. As an added benefit of using this tech- nique, functional testers can actually execute the unit tests created by developers as part of automated test runs and modify the data used by the unit tests as needed— without having to ask the developers to make changes. These tests can also be added to test plans and reported on like ILLUSTRATION BY RYAN ETTER RYAN BY ILLUSTRATION Figure 1. The Create Unit Tests dialog. any other functional tests.

22 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com Untitled-5 1 2/2/11 1:19 PM FEATURE Unit Testing

As unit tests are relied on more heavily, it’s helpful to be able to show how many unit tests were written and executed against each requirement.

For the purposes of this how- to article, I’ll be using a simple calculator application that does basic addition, subtraction, mul- tipli cation and division. The class that I’ll be unit testing is the CalcMath class and in particular the PerformOp method. Note that there are some bugs in this class, but this article doesn’t Figure 2. The Test List Editor. address finding those. Click OK. Call the new test project “SimpleCalcTests” and click Creating Basic Unit Tests Create. This will create a new project that’s automatically added to At this point there are no unit tests associated with the solution, so the solution and a test method that calls the PerformOp method let’s add a few here. There are several ways to add unit tests in shown in Listing 1 (note that a DeploymentItem attribute may also Visual Studio, so we’ll create them directly from the method we be generated, but for the current purposes this can be deleted). want to test. Now modify the method so it looks like this: Open the CalcMath class, right-click within the PerformOp [TestMethod()] method and select Create Unit Tests. This will display the Create public void PerformOpAddTest() Unit Tests dialog, as shown in Figure 1 (p. 22). { CalcMath target = new CalcMath (); double expected = 12; double actual; target.PerformOp(Op.Add, 7); Prerequisites and Setup actual = target.PerformOp(Op.Equals, 5); There are two parts to this article: associating unit tests with Assert.AreEqual(expected, actual); test cases and executing those unit tests through Microsoft Test } Manager. In order to complete all of the steps in this hands-on Unit tests should be short, simple, to the point and easy to read— walkthrough, you must have the following installed and because you might have to debug why your test failed, and the failure configured (all of this is pre-configured for you on the Microsoft might be in the test itself. As you can see, this method adds seven trial Virtual PC for Visual Studio 2010): and five together and the expected result is 12. ■ Team Foundation Server 2010 Now add three additional unit tests for subtraction, multiplication ■ Team Foundation Server Power Tools and division. The result is shown in Listing 2 (p. 26). ■ Visual Studio 2010 Ultimate (includes Microsoft Test Manager) You can view the Test List Editor by double-clicking the Simple- ■ Team Build Calc.vsmdi file in the Solution Folder or select Test | Windows | Test ■ Test Controller and at least one Test Agent List Editor. Figure 2 shows the Test List Editor window. At this point, feel free to execute the unit tests to verify that they The Project Setup work. Check the All Loaded Tests checkbox shown in the left panel 1. Download the scripts and source code from VisualStudioMagazine.com/Levinson0311 Listing 1. Generated PerformOp Test Method 2. Open the Visual Studio Command Prompt by clicking Start ///

| All Programs | 2010 | Visual Studio ///A test for PerformOp /// Tools | Visual Studio Command Prompt (2010) [TestMethod()] 3. Edit the CreateTeamProject.cmd script to set the location of public void PerformOpTest() your Team Foundation Server (TFS) { CalcMath target = new CalcMath (); 4. Execute the CreateTeamProject.cmd script (ensure you have Op operation = null; // TODO: Initialize to an appropriate value permissions to create a team project before doing so) double value = 0F; // TODO: Initialize to an appropriate value 5. Edit the CreateWorkItems.cmd script to set the location of double expected = 0F; // TODO: Initialize to an appropriate value double actual; your TFS actual = target.PerformOp(operation, value); 6. Execute the CreateWorkItems.cmd script Assert.AreEqual(expected, actual); 7. Add the SimpleCalculator application to the UnitTestDemo Assert.Inconclusive("Verify the correctness of this test method."); team project created in Step 4 —J.L. }

24 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com Untitled-5 1 2/2/11 1:20 PM FEATURE Unit Testing

Unit tests should be short, simple, to the point and easy to read—because you might have to debug why your test failed, and the failure might be in the test itself.

to the requirements. This will give you full traceability from unit tests to requirements and vice versa. There are two ways to accomplish the first step—either through the TCM command- line tool or through the Test List Editor. Both ways are described here, but you only need to walk through one of these ways to do it. Let’s start with associating unit tests with test cases via the Test List Editor. It’s a simple two-step process, but you must do this for each test one at a time, versus using the TCM command-line tool, which Figure 3. The tcm testcase /import command results. lets you associate multiple unit tests with test cases: of Figure 2, and click the run button located on the toolbar at the top. 1. Right-click the PerformOpAddTest Finally, check the entire solution into TFS. 2. Select Create Test Case from Test that will create the Test Case At this point you have four unit tests, which you’d like to be work item associated with each of the four requirements in your project. Repeat these steps for each of the other unit tests. Now, let’s perform the same operation, but using the TCM Associating Unit Tests with Requirements command-line tool. Do the following: The next step is to associate these unit tests with the requirements. 1. Open the Visual Studio Command Prompt by clicking Start | This is a two-part process that involves first generating the test cases All Programs | Microsoft Visual Studio 2010 | Visual Studio and linking them with the unit tests, and then linking the test cases Tools | Visual Studio Command Prompt (2010) 2. Navigate to the debug folder, which contains the compiled test Listing 2. Adding Test Methods case assembly (SimpleCalcTests.dll) 3. Enter the following command: [TestMethod()] tcm testcase /import /collection:http://:8080/tfs/ / public void PerformOpSubtractTest() { teamproject:UnitTestDemo /storage:SimpleCalcTests.dll CalcMath target = new CalcMath(); Here, points to your server and points to double expected = 12; double actual; your specific collection. This results in the output shown in Figure 3. target.PerformOp(Op.Subtract, 20); Note that I ran this after generating a test case through the Test actual = target.PerformOp(Op.Equals, 8); List Editor, which is why the results shown in Figure 3 may look a Assert.AreEqual(expected, actual); little different than what your results look like. } So, what happened here? The tcm testcase command not only [TestMethod()] creates test cases for unit tests automatically, but it will also update public void PerformOpMultiplyTest() any changes in storage location or remove the automation for test { CalcMath target = new CalcMath(); cases when the unit tests no longer exist. Additional details for this double expected = 12; command can be found in the MSDN library at tinyurl.com/48bnsn7. double actual; After running the tcm testcase /import command, switch back target.PerformOp(Op.Multiply, 3); actual = target.PerformOp(Op.Equals, 4); to Visual Studio and run the My Test Cases work item query. Four Assert.AreEqual(expected, actual); test cases should be returned: one for each of the unit tests. } Associate Test Cases with Requirements [TestMethod()] public void PerformOpDivideTest() While the unit tests are associated with the test cases, they’re still not { associated with the requirements (user stories in the Agile template). CalcMath target = new CalcMath(); To link the test cases with the stories, do the following: double expected = 12; double actual; 1. Run the Product Backlog query to view the User Stories in the target.PerformOp(Op.Divide, 36); project. Note the ID number of the “Build addition functionality actual = target.PerformOp(Op.Equals, 3); for the calculator” user story. Assert.AreEqual(expected, actual); 2. Select the Tested User Stories tab and click Link To. This will } display the Add Link dialog.

26 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com Untitled-5 1 2/2/11 1:20 PM FEATURE Unit Testing

A good use of unit tests is executing them every time the build runs, such as when using Continuous Integration, which is a best practice to help ensure high quality.

4. Click the Save disk icon (on the toolbar) or select File | Save All. 5. Right-click the newly created build definition (by default this should be named “SimpleCalculator”) from the Builds node in Team Explorer and select Queue New Build. At this point the build should exe- cute and complete with all four unit tests running successfully.

Unit Testing with Microsoft Test Manager The next step is to allow the testers to be able to execute the unit tests as part of their testing process. The rea- son this is critical is because testing done by the developers is done at the method level. By using Microsoft Test Manager, the testers are effec- tively executing the tests against the Figure 4. The Plan tab and Properties page after configuration. requirements and thereby associating the test results with the requirements 3. Enter the ID number noted in Step 1 in the Work item IDs that they’re testing. field and click OK. A quick note before I proceed. This operation assumes that you 4. Click Save Work Item on the Test Case. have a configured Test Controller, which is registered with your Repeat these steps for each test case. collection. It also assumes that you have a configured Test Agent, At this point, automated test results that are generated through which is registered with the Test Controller. If this is not the case, Microsoft Test Manager or command-line test runs (with the refer to the “Installing and Configuring Visual Studio Agents and publish option set) will associate the test results with a particular Test and Build Controllers” MSDN library article (tinyurl.com/4ss5wsb) requirement. Microsoft Test Manager must be used at some point for instructions on how to install and configure the Controller to set up a test suite. Now, I’ll show you the entire process. and Agent. 1. Open Microsoft Test Manager (Start | All Programs | Microsoft Create an Automated Build Visual Studio 2010 | Microsoft Test Manager). In order to make this work, you must first create an automated 2. Enter the server name (this is the full URL of the server, such build. If you’re not using automated builds, now is a good time to as http://:8080/tfs). start. A good use of unit tests is executing them every time the 3. Expand the collection name, select the UnitTestDemo project build runs, such as when using Continuous Integration, which is a and click Connect Now. best practice to help ensure high quality. 4. Click Add to create a new Test Plan and call it “Demo Plan.” These next steps assume that you’ve left the solution open in 5. Next, click Select Plan to open the plan. You should now be Visual Studio. looking at the Testing Center, Plan tab, Contents page. 1. Right-click the Builds node and select New Build Definition. 6. Click the Add Requirements button. 2. Select the Workspace tab and click Reset to Default Workspace. 7. Click the Run button from the middle of the screen to return all 3. Select the Build Defaults tab and enter the output location for of the requirements associated with the UnitTestDemo project the build. (this should return four requirements). 8. Select all of the requirements and then click Add requirements Table 1. Parameter Values to plan in the lower-right of the screen. This returns you to the Contents page. First Second Expected 9. Switch to the Properties page. 5712 10. In the Builds section, select Modify and then select the build 0 99 that just completed in the previous set of steps. 11. Click the X in the upper-right corner to return to the Prop- 500 30 530 erties page.

28 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com Untitled-5 1 2/2/11 1:21 PM FEATURE Unit Testing

Using TFS, you can take testing against requirements one step further: You can data-drive the unit tests using the Test Case as the data source.

12. Configure the Automated Test Settings to use an auto- mated test environment. 13. Switch to the Test tab, Run Tests page. 14. Select any suite and then a test and click Run. When you’re done configuring the Properties page, it should look like the one shown in Fig- ure 4 (p. 28). During the test run you’ll see the test run details page. Note that you can actually queue a number of runs. You don’t have to wait for one run to be com- pleted before the next run starts. Wait for two hours (at most) and Figure 5. The Stories Overview report. run the Stories Overview report, shown in Figure 4. First add the DataSource attribute—and be sure and you’ll see the results of your test cases against the requirement to set the URL for your TFS instance and project, and set the Test in Figure 5. Case ID (878 in Listing 2) to be that of the Test Case in your system. 5. Next, update the expected value with a call to the data source. Test Cases as the Data Source for Data-Driven Unit Tests 6. Finally, update the two calls to the PerfomOp method with a Using TFS, you can take testing against requirements one step call to the data source. further: you can data-drive the unit tests using the Test Case as the Please note that the figures in Table 1 are demo values. In actual data source. This approach eliminates the need to have a separate, testing you’d use a spread of values, including boundary values or version-controlled Excel file, text file or other artifact and allows other values that are likely to cause a bug, as shown in Listing 3. you to store the test data for a particular test with that test case. When you re-execute the unit test either from Visual Studio or 1. In Microsoft Test Manager, open the PerformOpAddTest test through Microsoft Test Manager, the unit test will now pull its data case in order to edit it. from the test case work item. This is a handy way to maintain the 2. In the Test Steps section, in the first row in the Action column, data used by the test case and allows testers to easily update the enter the following text and then press enter: @first, @second, data being used by the unit test. It also allows for testers to perform @expected. even more comprehensive regression testing and have those test 3. This causes the parameters section of the test steps to be results linked to the actual requirements. enabled with three columns: “first,” “second” and “expected.” In this article I’ve shown you some simple techniques to associate Fill in these values as shown in Table 1 (p. 28). unit tests with test cases and, by extension, requirements. In doing 4. Next, edit the PerformOpAddTest method so that it looks like that so, end users get a comprehensive view of how well their application is being tested—even to the unit-test level, which is a view most end users never see. In addition, when developers use this simple tech- Listing 3. Modifi ed PerformOpAddTest nique, testers can execute unit tests without ever opening a Visual [TestMethod()] Studio solution. They can also update the data used by the test case [DataSource( "Microsoft.VisualStudio.TestTools.DataSource.TestCase", if the situation warrants it—and do all this without going back to the "http://tfs2010:8080/tfs/DefaultCollection;UnitTestDemo", developers. Using these techniques and tools, you should be able to "878", improve the quality and maintainability of your applications. VSM Microsoft.VisualStudio.TestTools.UnitTesting.DataAccessMethod.Sequential)] public void PerformOpAddTest() { Jeff Levinson recently completed his fourth book, “ with CalcMath target = new CalcMath(); Visual Studio 2010” (Addison-Wesley Professional, 2011), which takes a double expected = Convert.ToDouble(TestContext.DataRow["expected"]); comprehensive look at testing applications using Visual Studio 2010 and double actual; target.PerformOp(Op.Add, Convert.ToDouble(TestContext.DataRow["first"])); Microsoft Test Manager 2010. actual = target.PerformOp(Op.Equals, Convert.ToDouble(TestContext.DataRow["second"])); GO ONLINE Assert.AreEqual(expected, actual); Download the sample code for this article at } VisualStudioMagazine.com/Levinson0311

30 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com Untitled-1 1 1/13/11 9:48 AM

IN THIS SECTION: On VB · 32 // Ask Kathleen · 42 /////////////

{ ON VB }

Get Started with Visual Listing 1. XAML for a Simple Four-Page Pivot Application Basic Development for Layout in MainPage.xaml Windows Phone 7 Tips on Windows Phone 7 development and app design with sample code for a Windows Phone Pivot application. BY JOE KUNK I was the first customer in our local AT&T store to purchase a Windows Phone 7 when it was first released in the United States in handset on hand, and told them to hold one for me. There were no discounts and I had to switch carriers to get the phone, but I only one eager to get a Windows Phone; Microsoft sold 1.5 million Windows Phone 7 OSes in the first six weeks across nine handset Windows Phone 7 supported five languages: English, French, Italian, German and Spanish. Windows Phone 7 is not an extension of the prior Windows Mobile platform, but a complete redesign to be more competitive in the mobile marketplace. In this article, I’ll introduce the provide. Nor does it provide a universal-search feature across Windows Phone 7 device and discuss how to develop applications multiple types of data like those found in the Palm webOS and on it with Visual Basic .NET. Research In Motion BlackBerry OS. According to Microsoft CEO Steve Ballmer’s keynote at the The Device International Consumer Electronics Show in early January, upcoming Microsoft has strict design guidelines for the first-generation handsets Windows Phone 7 updates include copy/paste functionality, that can run Windows Phone 7. The handset display must consist of a improved multitasking, Silverlight and hosting in the display resolution of 480 x 800 (WVGA)—available at launch—or 320 browser, and the ability for Mac users to synch iTunes files. x 480 (HVGA), which is expected in later releases. For comparison, Windows Phone 7 does not support user-accessible memory cards the original Zune is 240 x 320 pixels; the Zune HD is 272 x 480. in the traditional sense; rather, it’s treated as a secured permanent Other hardware requirements include a minimum processor extension of the on-board system memory. If your handset has an speed of 1GHz, minimum camera resolution of 5 megapixels, empty SD Card slot, you must reset your phone to factory default in bluetooth, WiFi, FM radio, accelerometer, compass, light sensor, order to install and use the memory card (get a good backup first!). proximity sensor, assisted GPS (which also uses mobile operator The SD Card will be paired with the handset via an internal password and Internet data to help determine location), 3.5-mm audio jack, and will become unusable in any other device. It’s essential that only and a lower row of three buttons, including “back” (left arrow), Microsoft-approved SD Cards be used; unapproved cards are likely “home” (Windows logo) and “search” (magnifying glass). to cause phone instability and loss of data. The Welcome menu consists of a series of half or full-size tiles that may extend beyond the visible screen. Six of the eight visible Windows Phone 7 Concepts screen tiles are specified by Microsoft, with two half-size or one Here’s a list of the concepts that are important to understand full-size available for the carrier to customize. The six Microsoft before you get started with Windows Phone 7 development. tiles include: Phone, People, Messaging, Outlook, Internet Advertising: The Microsoft Advertising SDK for Windows Explorer and Xbox Live. The Welcome menu can be customized Phone 7 is available for both XNA and Silverlight to incorporate by the user by adding, rearranging or removing tiles. advertising into your app to generate advertising revenue, typically Windows Phone 7 does not have turn-by-turn navigation in its for free or trial versions. The SDK includes a custom control to Maps application, instead leaving that for the mobile carrier to display advertisements, found at pubcenter.microsoft.com.

32 VISUAL STUDIO MAGAZINE · March 2011 · VisualStudioMagazine.com { ON VB }

Touch Input: Windows Phone 7 supports both touch and Listing 2. XAML for a Simple Web Browser gestures. It recognizes up to four simultaneous touch points and in MainPage.xaml recognizes gestures such as tap, double-tap, pan, flick, pinch, stretch and touch hold.