Microsoft`s core data access technology is finally ready
Transcription
Microsoft`s core data access technology is finally ready
VisualStudioMagazine.com Microsoft’s core data access technology is finally ready for prime time—are you? PLUS SEPTEMBER 2010 Volume 20, No. 9 On VB: Validate Forms with ASP.NET MVC 2 Data Annotations Visual Studio 2010 Debugging Tips and Tricks SQL Server 2008 R2 for the Developer Untitled-5 2 3/5/10 10:19 AM Sure, Visual Studio 2010 has a lot of great functionality— we’re excited that it’s only making our User Interface components even better! We’re here to help you go beyond what Visual Studio 2010 gives you so you can create Killer Apps quickly, easily and without breaking a sweat! Go to infragistics.com/beyondthebox today to expand your toolbox with the fastest, best-performing and most powerful UI controls available. You’ll be surprised by your own strength! Infragistics Sales 800 231 8588 Infragistics Europe Sales +44 (0) 800 298 9055 Infragistics India +91-80-6785-1111 twitter.com/infragistics Copyright 1996-2010 Infragistics, Inc. All rights reserved. Infragistics and the Infragistics logo and NetAdvantage are registered trademarks of Infragistics, Inc. Untitled-5 3 3/5/10 10:19 AM Your best source for software development tools! ® Paradise # L05 26301A01 LEADTOOLS Recognition SDK Multi-EditX by LEAD Technologies Develop desktop and server document imaging and ECM applications that require high-speed multi-threaded forms recognition and processing, OCR, ICR, OMR, and barcode technology. • Supports text, OMR, image, and 1D/2D barcode fields • Recognize machine print and constrained handwritten text • Auto-registration and clean-up to improve recognition results • Latin character set support is included. Arabic and Asian support is available by Multi Edit Software 3,214. $ 99 by Pragma Systems Get all in one easy to use high performance package. FIPS Certified and Certified for Windows. • Certified for Windows Server 2008R2 • Compatible with Windows 7 Certified • High-performance servers with for Windows centralized management 7/2008R2 • Active Directory & GSSAPI authentication • Supports over 1000 sessions • Hyper-V and PowerShell support Paradise # P35 04201A01 • Runs in Windows 2008R2/2008/2003/ 7/ Vista/XP/2000 $ 99 programmers.com/pragma 550. ActiveReports 6 by GrapeCity Integrate Business Intelligence/Reporting/Data Analysis into your .NET applications using the NEW ActiveReports 6. • Fast and Flexible reporting engine • Data Visualization and Layout Controls such as Chart, Barcode and Table Cross Section Controls NEW VERSION 6! • Wide range of Export and Preview formats including Windows Forms Viewer, Web Viewer, Adobe Flash and PDF Professional Ed. Paradise # • Royalty-Free Licensing for Web and D03 04301A01 Windows applications 1,310. $ 99 programmers.com/grapecity CA ERwin Data Modeler r7.3 – Product Plus 1 Year Enterprise Maintenance ® by CA CA ERwin Data Modeler is a data modeling solution that enables you to create and maintain databases, data warehouses and enterprise data resource models. These models help you visualize data structures so that you can effectively organize, manage and moderate data complexities, database technologies and the deployment environment. Paradise # P26 04201E01 3,931.99 $ Multi-EditX is “The Solution” for your editing needs with support for over 50 languages. Edit plain text, ANY Unicode, hex, XML, HTML, PHP, Java, Javascript, Perl and more! No more file size limitations, unlimited line length, any file, any size Multi-EditX is “The Solution”! Pre-Order Your Copy and Save! programmers.com/LEAD “Pragma SSH for Windows” Best SSH/SFTP/SCP Servers and Clients for Windows VMware vSphere Essentials Kit Bundle NEW RELEASE! vSphere Essentials provides an all-in-one solution for small offices to virtualize three physical servers for consolidating and managing applications to reduce hardware and operating costs with a low up-front investment. vSphere Essentials includes: 1-49 Users Paradise # A30Z10101A01 223.20 $ programmers.com/multiedit InstallShield Professional for Windows by Flexera Software If your software targets Windows®, InstallShield® is your solution. It makes it easy to author high-quality reliable Windows Installer (MSI) and InstallScript installations and App-V™ virtual packages for Windows platforms, including Windows 7. InstallShield, the industry standard for MSI installations, also supports the latest Microsoft technologies including Visual Studio 2010, .NET Framework 4.0, IIS7.0, SQL Server 2008 SP1, and Windows Server 2008 R2 and Windows Installer 5, keeping your customers happy and your support costs down. Upg from any Active IS Pro + IS Pro Silver Mtn Paradise # I21 02401B01 1,399.00 $ Quick View Plus 11 With support for over 300 different file formats, Quick View Plus 11 Standard Edition lets you view nearly all the files and e-mail attachments you need instantly without NEW purchasing numerous software programs. RELEASE! Quick View Plus Standard Edition maintains the formatting of the files you view. See Standard Edition and print files as they were originally Qty 51-99 Users created and meant to be seen, complete with fonts, text formatting and graphics. Paradise # AV5 01351A01 Compatible Operating Systems: Windows 7 (32-bit version), Vista (32-bit version), XP and 2000 programmers.com/avantstar CALL Intel C++ Compiler Professional Edition ® programmers.com/vSphere for Centralized Management, Continuous Application Availability, and Maximum Operational Efficiency in Your Virtualized Datacenter. Programmer’s Paradise invites you to take advantage of this webinar series sponsored by our TechXtend solutions division. FREE VIRTUALIZATION WEBINAR SERIES: REGISTER TODAY! TechXtend.com/Webinars Word Processing Components NEW RELEASE! TX Text Control is royalty-free, robust and powerful word processing software in reusable component form. • .NET WinForms control for VB.NET and C# • ActiveX for VB6, Delphi, VBScript/HTML, ASP • File formats DOCX, DOC, RTF, HTML, XML, TXT Professional Edition • PDF and PDF/A export, PDF text import Paradise # • Tables, headers & footers, text frames, T79 02101A02 bullets, structured numbered lists, multiple undo/redo, sections, merge fields, columns • Ready-to-use toolbars and dialog boxes 1,220.99 $ Download a demo today. programmers.com/theimagingsource STOP OVERBUYING SOFTWARE TODAY! Single User for Windows Paradise # I23 38101A02 564. 866-719-1528 446.99 $ TX Text Control 15.1 View, Copy and Print Virtually Any File by Avantstar $ programmers.com/ca for 3 hosts Paradise # V55 85101A02 BUILD ON VMWARE ESXi AND VSPHERE programmers.com/flexera by Intel Intel® C++ Compiler Professional Edition offers the best support for creating multithreaded applications. Only the Professional Edition offers the breadth of advanced optimization, multi-threading, and processor support that includes automatic processor dispatch, vectorization, auto-parallelization, OpenMP*, data prefetching, and loop unrolling, along with highly optimized C++ templates for parallelism, math processing, and multimedia libraries. • VMware ESXi and VMware ESX (deployment-time choice) • VMware vStorage VMFS • Four-way virtual SMP • VMware vCenter Server Agent • VMware vStorage APIs/VCB • VMware vCenter Update Manager • VMware vCenter Server for Essentials 99 programmers.com/intel Eliminate Wasteful Software License Spend: • Control your software licensing costs • Stop paying for licenses you’re not using • Reduce your license spend by $300+ per desktop user FREE 30-DAY PROOF OF CONCEPT Learn more: programmers.com/eliminate-wasteful-license-spend programmersparadise.com Prices subject to change. Not responsible for typographical errors. Untitled-1 1 8/3/10 3:10 PM { FRAMEWORKS } 12 September 2010 // Volume 20 // No. 9 Michael Desmond, Editor in Chief, Visual Studio Magazine Opinions on LightSwitch FEATURES 12 Get Ready for the Entity Framework Modeling your data access in .NET with the Entity Framework 1 presented too many challenges for n-tier developers. With Visual Studio 2010 and the Entity Framework 4, the Microsoft core data access technology is ready for prime time—and deserves a second look. BY KATHLEEN RICHARDS 18 SQL Server 2008 R2 for the Developer Microsoft extends its enterprise-capable database platform with powerful new management and scalability features—and there’s plenty in the latest rev for developers. BY DON KIELY 23 Lab Management in Visual Studio 2010 For the first time, Lab Management brings the power of virtualization to your Visual Studio-based development process. Learn how to streamline debug and test challenges with the new Microsoft virtualization technology for developers. BY VIJAY MACHIRAJU 28 LANGUAGE LAB On VB PAGE 28 How to Validate Forms with ASP.NET MVC 2 Data Annotations Learn how to develop a custom validator that works at both the client level with JavaScript and the server level with managed code. BY JOE KUNK AND VIJAY JAGDALE Ask Kathleen PAGE 34 Tips for Debugging Your Code in Visual Studio 2010 How improvements in the latest Microsoft IDE and underused features in Visual Studio 2008 support common debugging strategies to help you write better code. BY KATHLEEN DOLLARD DEPARTMENTS 6 8 Letters to the Editor DevInsight VS TOOLBOX, VS INSIDER VSToolbox: Build Office Apps with Add-in Express PAGE 8 VSToolbox: Create Documents with Aspose.pdf for .NET PAGE 10 VSInsider: Silverlight Surprise PAGE 11 39 Index of Advertisers COLUMNS 3 Frameworks BY MICHAEL DESMOND 40 Redmond Review BY ANDREW BRUST When Microsoft announced the launch of its LightSwitch wizard-driven .NET app tool at the VSLive! Conference in Redmond, Wash., in August, it set off a bit of controversy among developers worried that LightSwitch could lead to a flood of bad apps. LightSwitch, currently in beta, is intended to enable power users, business analysts and those who would otherwise turn to Office macros and Excel spreadsheets to craft legitimate, data-driven .NET apps using a simple and intuitive interface (You can read more about LightSwitch in Andrew Brust’s Redmond Review column on p. 40.). Online readers offered their own take on the value of LightSwitch. Here’s a sampling: “[It] looks like a weak clone of Iron Speed Designer,” wrote one commenter, who compared it to the .NET code generation tool. “There always has been a division between RAD [rapid application development] and programming for the long term,” wrote John McFetridge. “By the long term I mean apps that will be around for years and need to be extended and maintained— this is where architecture comes first. Then there’s RAD, and it sounds like LightSwitch is a great tool [for RAD] so I have no problem with it.” A number of developers said that LightSwitch is a welcome solution to a problem that has been years in the making. “I started as an Access/VBA programmer when Access came out. I created lots of productive apps, some of which are still running good small companies,” commented a developer out of Pittsburgh, Penn. “I migrated to .NET and VB.NET, then to C#. I bemoaned that Access became a dead-end for many beginning and part-time programmers when .NET arrived. Hopefully that changes with LightSwitch. Hooray!” What do you think about the LightSwitch? Write to me at [email protected]. VisualStudioMagazine.com · September 2010 · VISUAL STUDIO MAGAZINE 3 Online Contents Get the complete picture— the latest dev news, analysis and how-to content—at VisualStudioMagazine.com and our partner sites in the Redmond Developer Network. EASY FINDIT What we once called FindIT codes are now easy URLs. You’ll see these embedded throughout Visual Studio Magazine so you can access any additional information quickly. Simply type in VisualStudioMagazine.com/ followed by the FindIT code into your URL address field. (Note that all URLs do not have any spaces, and they are not case-sensitive.) VISUALSTUDIOMAGAZINE.COM REDDEVNEWS.COM ADTMAG.COM Controlling Controllers in ASP.NET MVC BY PETER VOGEL Top 10 Things I Wish I Knew Before I Started My Silverlight 4 Project Net Neutrality—Why Should Enterprise Developers Care? If you’re wondering what ASP.NET Model-View-Controller (MVC) is and whether you should be moving to it, this column is the beginning of an introductory series on the benefits of the framework for traditional ASP.NET programmers. BY LOUIS-PHILIPPE PINSONNEAULT BY JOHN K. WATERS Creating a business application is relatively easy in Silverlight 4 with the right tools in your toolbox and a little advice. Find out what 10 things a Silverlight developer thinks you should know. It’s not just the liberal-leaning MoveOn that opposes the Google-Verizon plan. The framework for net neutrality outlined by the two companies has come under widespread criticism. VisualStudioMagazine.com/Vogel0910 RedDevNews.com/Pinsonneault0910 A Look Inside the Visual Studio Scrum Process Template Microsoft Offers New SQL Migration Tools ADTmag.com/WatersA0910 Microsoft Lays Out Its “Open Cloud” Vision BY MICKEY GOUSSET BY KURT MACKIE BY KURT MACKIE How to create your first Scrum Team Project in Team Foundation Server 2010, and a closer look at what the Visual Studio Scrum Process 1.0 template contains. The company updated some of its free tools to help users move from Access to SQL Server and SQL Azure, and released a new Oracle MySQL migration tool. Microsoft used the occasion of an O’Reilly Open Source Convention to advance its vision of an open cloud by breaking it down into four basic principles. RedDevNews.com/Mackie0910 ADTmag.com/Mackie0910 VisualStudioMagazine.com/Gousset0910 Q&A: Microsoft’s Lisa Feigenbaum Talks About C# Try Your Own OData Feed in the Cloud—or Not! Analysts: Oracle’s Lawsuit Against Google Casts Shadow on Java’s Future BY MICHAEL DESMOND BY DAVID RAMEL BY JOHN K. WATERS The Microsoft community program manager for the Visual Studio Managed Languages Team talks about the new capabilities in C# 4 and what we can expect going forward. SQL Azure Labs has a portal that lets you turn your SQL Azure-hosted database into an OData feed with a couple of clicks. It also lets you try out the Project Houston CTP1 and SQL Azure Data Sync. Sounds great, but Data Driver blogger David Ramel encountered a few glitches. The analysts say the simple filing of the lawsuit could risk the future of Java as a development platform—and not just in the mobile arena. VisualStudioMagazine.com/Desmond0910 ADTmag.com/WatersB0910 RedDevNews.com/Ramel0910 VisualStudioMagazine.com 4 RedDevNews.com VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com ADTmag.com Silverlight, .NET, WPF, WCF, WF, C API, C++ Class Lib, COM & more! Document 'HYHORS\RXUDSSOLFDWLRQZLWKWKHVDPHUREXVWLPDJLQJWHFKQRORJLHVXVHGE\Microsoft, HP, Sony, Canon, Kodak, GE, Siemens, the US Air Force and Veterans Affairs Hospitals. /($'722/6 SURYLGHV GHYHORSHUV HDV\ DFFHVV WR GHFDGHV RI H[SHUWLVH LQ color, grayscale, document, medical, vector and multimedia imaging development. ,QVWDOO /($'722/6 WR HOLPLQDWH PRQWKV RI UHVHDUFK DQG SURJUDPPLQJ WLPH ZKLOH PDLQWDLQLQJKLJKOHYHOVRITXDOLW\SHUIRUPDQFHDQGIXQFWLRQDOLW\ Silverlight: 100% pure Silverlight 3 and 4 Imaging SDK. Image Formats & Compression: Supports 150+ image formats and compressions including TIFF, EXIF, PDF, JPEG2000, JBIG2 and CCITT G3/G4. Display Controls: ActiveX, COM, Win Forms, Web Forms, WPF and Silverlight. Image Processing: ¿OWHUV WUDQVIRUPV FRORU FRQYHUVLRQ DQG GUDZLQJ IXQFWLRQV supporting region of interest and extended grayscale data. OCR/ICR/OMR: Full page or zonal recognition for multithreaded 32 and 64 bit GHYHORSPHQWZLWK3')3')$;36'2&;0/DQG7H[WRXWSXW Forms Recognition & Processing: Automatically identify and classify forms and H[WUDFWXVHU¿OOHGGDWD Barcode:$XWRGHWHFWUHDGDQGZULWH'DQG'EDUFRGHVIRUPXOWLWKUHDGHGELW development. Document Cleanup/Preprocessing: Auto-GHVNHZ GHVSHFNOH KROH SXQFK OLQH and border removal, inverted text correction and more for optimum results in OCR and Barcode recognition. PDF & PDF/A:5HDGZULWHDQGYLHZVHDUFKDEOH3')ZLWKWH[WLPDJHVERRNPDUNVDQG annotations. Annotations: Interactive UI for document mark-up, redaction and image measurement (including support for DICOM annotations). Medical Web Viewer Framework: 3OXJLQ HQDEOHG IUDPHZRUN WR TXLFNO\ EXLOG KLJKTXDOLW\IXOOIHDWXUHGZHEEDVHGPHGLFDOLPDJHGHOLYHU\DQGYLHZHUDSSOLFDWLRQV PACS Workstation Framework: Set of .NET PACS components that can be used to build a full featured PACS Workstation application. Medical Image Viewer: +LJKOHYHOGLVSOD\FRQWUROZLWKEXLOWLQWRROVIRULPDJHPDUNXS ZLQGRZOHYHOPHDVXUHPHQW]RRPSDQFLQHDQG/87PDQLSXODWLRQ DICOM:)XOOVXSSRUWIRUDOO,2'FODVVHVDQGPRGDOLWLHVGH¿QHGLQWKH',&20VWDQGDUG LQFOXGLQJ(QFDSVXODWHG3')&'$DQG5DZ'DWD PACS Communications: Full support for DICOM messaging and secure communication HQDEOLQJTXLFNLPSOHPHQWDWLRQRIDQ\',&206&8DQG6&3VHUYLFHV 3D:&RQVWUXFW'YROXPHVIURP'',&20PHGLFDOLPDJHVDQGYLVXDOL]HZLWKDYDULHW\RI methods including MIP, MinIP, MRP, VRT and SSD. Scanning: 7:$,1 :,$ ELW DXWRGHWHFW RSWLPXP GULYHU VHWWLQJV IRU KLJK speed scanning. DVD: Play, create, convert and burn DVD images. MPEG Transport Stream::LWK'95IRU8'3DQG7&3,3VWUHDPVDXWROLYHVXSSRUW Multimedia: Capture, play, stream and convert MPEG, AVI, WMV, MP4, MP3, OGG, ISO, DVD and more. DICOM Medical Form Recognition & Processing Barcode Multimedia Vector Free 60 Day Evaluation! www.leadtools.com/vsm (866) 530-3399 Untitled-2 1 8/11/10 11:23 AM Letters Check out our events at VSLive.com We’ll be in Orlando in November 2010 VisualStudioMagazine.com September 2010 • Volume 20 • No. 9 Editorial Staff Readers Comment on IntelliTrace In the August issue we published a walk-through of the new IntelliTrace debugging feature (“Debugging Applications with IntelliTrace”), which is included with Visual Studio Ultimate and Test editions. Readers respond: This feature is a nice idea; but I don’t think that it will get much traction if it’s only available in the Ultimate version of Visual Studio, which is a significant price jump from other versions. Also, it requires testers to use Test version. I can’t justify the additional investment for an entire development team just for this feature. TC Submitted via Internet The IntelliTrace feature is new in Visual Studio, but the concept has been around for some time. Back in the late ’90s I used the Mutek BugTrapper tool (geyra.com/ mutek/bugTrapper.htm) to track down a couple of elusive issues. BugTrapper gave at that point only post-mortem dumps, but could (obviously) debug “native” code and was able to generate the dumps by using only a small agent that could easily be deployed to a customer’s site. I haven’t used BugTrapper since, so I’m not up-to-date with its current capabilities. Eugene_NW Submitted via Internet Why is this interesting feature not available for C++ developers? Has all the world switched to .NET? Anonymous Submitted via Internet Of IE9 and HTML5 Andrew Brust in August wrote that Microsoft faces some important choices as it decides how it will support the upcoming HTML5 standard. Here a reader responds: HTML5 will allow us to move a 10-plus-year-old Microsoft Access app from 100-plus client installations (and the necessary tech support) to a centralized Web interface. Since we’re using HTML5 with LAMP technology, we’ll also be able to offer our customers tablet functionality. This is a no-brainer and moves us completely away from Microsoft. In the meantime, we have other teams constantly struggling with SharePoint deployments and late SAP projects. By the way, our .NET projects are completing successfully on time and with impressive functionality, but if Microsoft doesn’t embrace HTML5 as a dev platform, we may move away from .NET. Anonymous Submitted via Internet Vice President, Editorial Director Editor in Chief Executive Editor Managing Editor Associate Managing Editor Associate Managing Editor Doug Barney Michael Desmond Kathleen Richards Wendy Gonchar Katrina Carrasco Marti Longworth Tools Editor Peter Vogel Contributing Editors Andrew J. Brust, Ken Cox, Kathleen Dollard, Roger Jennings, Jeff Levinson, Bill McCarthy, Karl E. Peterson, Keith Pleas, Bill Wagner, Dan Wahlin, John K. Waters Art Staff Creative Director Scott Shultz Art Director Joshua Gould Online/Digital Media Director, Online Media Executive Editor, New Media Site Administrator Designer Becky Nagel Michael Domingo Shane Lee Rodrigo Muñoz President Vice President, Publishing Director of Marketing Online Marketing Director Henry Allain Matt Morollo Michele Imgrund Tracy Cook President & Neal Vitale Chief Executive Officer Senior Vice President Richard Vitale & Chief Financial Officer Executive Vice President Michael J. Valenti Senior Vice President, Audience Development & Digital Media Vice President, Finance & Administration Vice President, Information Technology & Application Development Vice President, Attendee Marketing Vice President, Event Operations Abraham M. Langer Christopher M. Coates Erik A. Lindgren Carmel McDonagh David F. Myers Chairman of the Board Jeffrey S. Klein 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]. Visual Studio Magazine wants to hear from you! Send us your thoughts about recent stories, technology updates or whatever’s on your mind. E-mail us at [email protected] and be sure to include your first and last name, city and state. Please note that letters may be edited for form, fit and style. They express the views of the individual authors, and do not necessarily reflect the views of the VSM editors or 1105 Media Inc. 6 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com Irvine Office (weekdays, 9:00 a.m. - 5:00 p.m. PT) Telephone 949-265-1520; Fax 949-265-1528 16261 Laguna Canyon Road, Suite 130, Irvine, CA 92618 Framingham Office (weekdays, 9:00 a.m. - 5:00 p.m. ET) Telephone 508-875-6644; Fax 508-875-6633 600 Worcester Road, Suite 204, Framingham, MA 01702 Corporate Office (weekdays, 8:30 a.m. - 5:30 p.m. PT) Telephone 818-814-5200; Fax 818-734-1522 9201 Oakdale Avenue, Suite 101, Chatsworth, CA 91311 Visual Studio Magazine The opinions expressed within the articles and other contents herein do not necessarily express those of the publisher. Esri Developer Network ® Integrate Mapping and GIS into Your Applications Give your users an effective way to visualize and analyze their data so they can make more informed decisions and solve business problems. By subscribing to the Esri® Developer Network (EDN ), you have access to the complete Esri SM geographic information system (GIS) software suite for developing and testing applications on every platform. Whether you’re a desktop, mobile, server, or Web developer, EDN provides the tools you need to quickly and cost-effectively integrate mapping and GIS into your applications. Subscribe to EDN and leverage the power of GIS to get more from your data. Visit www.esri.com/edn. Copyright © 2010 Esri. All rights reserved. The Esri globe logo, Esri, EDN, and www.esri.com are trademarks, registered trademarks, or service marks of Esri in the United States, the European Community, or certain other jurisdictions. Other companies and products mentioned herein may be trademarks or registered trademarks of their respective trademark owners. Untitled-3 1 8/11/10 3:48 PM </DevInsight> Toolbox VS Build Office Apps with Add-in Express Add-in Express 2010 Add-in Express simplifies the process of extending Microsoft Office to let you concentrate on adding functionality. PETER VOGEL Automating Microsoft Office has never been for the faint of heart. While Visual Studio Tools for Office (VSTO) allows developers to use the Microsoft .NET Framework to create Office add-ins, you often spend as much time writing and debugging the utility code that integrates your add-in with Office as you do actually adding functionality. Even if your add-in worked when installed, the differences between versions of Office could stop your add-in cold if your users upgraded. Add-in Express dramatically simplifies the process of creating and deploying Office add-ins. For instance, when creating an add-in, you can specify which versions of Office you want to support, beginning with an “Office neutral” option that supports all versions beginning with Office 2000. You can also, when starting your project, specify which Office components you want to support—Add-in Express automatically generates the necessary support code. An Add-in Express project includes a loader that handles integration with Office and an “add-in module,” where you put the components of your add-in. The module follows the .NET Framework paradigm of having a visual designer, where you place tools and an accompanying code file. Rather than adding new tools to the Toolbox, however, the tools that you use to create your add-in appear at the top of the designer and are activated by being clicked. It’s a great paradigm. For instance, adding a keyboard shortcut is as easy as clicking on the tool to add it to the designer, setting some properties and then adding code to the tool’s Action event. Predefined global variables give you access to the object models for the Office components you specified when creating your project. Adding and extending the Office Ribbon menu is equally easy and includes a visual designer that lets you see the result of adding new groups and controls to the Ribbon (see Figure 1). Similar support allows you to visually create new TaskPanes. The add-in designer also offers centralized management for Office events—just add an event tool for an Office component to the Figure 1. The Add-in Express Ribbon designer lets you put new components on the Office Ribbon by adding tools, setting properties and tying code to events. 8 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com Add-in Express 2010 for Microsoft Office and .NET Add-in Express Ltd. Web: add-in-express.com Phone: 375-291-944101 Price: $349 (standard package) Quick Facts: An add-in to Visual Studio for creating Office add-ins in the Microsoft .NET Framework Pros: Solves many problems that Office add-in developers face, including changing the Ribbon, handling version differences and accessing events Cons: Documentation is written by the application’s programmers and translated into English designer. Each of the event tools lists all the global events for the Office component (for example, for Excel, the tool includes the SheetActive and NewWorkbook events, among four dozen others). Code you add here is automatically attached to the event in the appropriate Office component. In addition to general support for Office, Add-in Express offers support for some specific Office technologies. You can use Add-in Express to simplify the process of extending the Outlook shortcut bar, creating SmartTags or creating Excel Real Time Data components (which provide a stream of data to an Excel formula). You’ll still have to learn how to manipulate the object models for the various Office components (some of which are especially bizarre), but Add-in Express makes integrating your code into Office almost trivial. I can no longer imagine doing Office development in the .NET Framework without this tool. The package includes an almost-200page PDF user guide. Your best strategy for this guide is to read through the sample project you’re most interested in first— earlier sections of the guide assume that you’re familiar with later sections. While I tested the 2010 version, Add-in Express works in all versions of Visual Studio since version 2003 and with all versions of Office since version 2000. VSM Peter Vogel ([email protected]) is the tools editor for VSM and a principal in PH&V Information Services, specializing in ASP.NET development. Imagine... ...an intranet employees want to use Why is user adoption such a large hurdle for intranets? Learn more: eIntranet overcomes this hurdle by transforming the user experience. Employees connect with the right people and content instantly. Information finds them, no matter where they go. Collaboration – Complete projects faster in collaborative groupspaces with powerful communication and sharing tools http://www.ektron.com/intranet Timeline and Social Navigation – Find content and collateral based on when it was created and who is using it Easy to deploy, customize and extend – Integrate with business infrastructures and extend the functionality to meet unique needs Mobile engagement – Engage employees on the go, delivering updates via SMS alerts, e-mail or the eIntranet Mobile App Copyright © 2010 Ektron, Inc. All rights reserved. | http://www.ektron.com | 1-877-4-WEB-CMS Untitled-1 1 6/11/10 11:49 AM </DevInsight> Toolbox VS Create Documents with Aspose.Pdf for .NET Aspose.Pdf When it’s time to create a document, PDF is often the format that your users prefer. Aspose.Pdf provides the coding support that lets you build PDF documents on the fly. PETER VOGEL About a month ago, in a ToolTracker blog post entitled “Tool Markets You Don’t Even Know About” (VisualStudioMagazine.com/ Vogel0910), I mentioned PDF document creation as a tool market that you may not have heard of. In that market, Aspose is one of the leaders with a suite of tools for creating PDF documents. The Aspose.Pdf document-creation tool is more than just a PDF printer driver. Aspose.Pdf allows you to build a PDF document on the fly, inserting text, tables, graphs and more as you need them. And, unlike creating a document in Microsoft Word using automation, Aspose.Pdf does it using a set of native Microsoft .NET Framework tools—you don’t even need to have Adobe Acrobat installed on the computer. Creating simple documents is easy with Aspose.Pdf. More importantly, from a database developer’s point of view, the software lets you create data-driven templates. You define an XML template using Extensible Stylesheet Language Formatting Objects (XSL-FO) and bind it to the Aspose.Pdf document to specify the structure of your document. While you can’t load a complete document from your data as you would load a grid control, slotting data into your document is easy. The Aspose.Pdf FillTable method lets you transfer data from .NET DataTables to a document table in a single statement. I found the Aspose.Pdf object model clean and easy to understand. However, as with any document-creation system, creating complex documents can be challenging, especially if you’re worried about aesthetics. I have two criticisms, one major and one minor. First, the major complaint: Creating XSL-FO templates is key to 10 generating data-driven reports with Aspose.Pdf. Unfortunately, Aspose.Pdf doesn’t include a tool to support creating those templates—your best strategy is to start with one of the templates included in the many sample applications provided with Aspose.Pdf and modify it. You can download the schema for XSL-FO from Aspose and use that within Visual Studio to ensure that the templates you create are valid. Which leads to my minor criticism: While Aspose provides a full range of sample applications, they’re all Visual Studio 2003/2005 projects. When I converted the sample applications to Visual Studio 2010, I had to re-reference the Aspose library and reset the application’s .NET version before they would run. That took me five minutes that Aspose could have spent on its end. Still, Aspose.Pdf Aspose Web: aspose.com Phone: 888-277-6734 Price: $599 for developer Enterprise license with Standard Support Quick Facts: Native .NET objects for creating and displaying PDF documents with Adobe Acrobat in both Web and desktop environments Pros: Powerful data-driven tools for creating simple and complex documents on the fly Cons: No support tools (other than a schema) for creating document templates Aspose.Pdf is a capable and easy-to-use PDF creation tool with some intriguing data-centric talents. VSM Peter Vogel ([email protected]) is the tools editor for Visual Studio Magazine and a principal in PH&V Information Services, specializing in ASP.NET development. ToolTracker Documentation Gripes As a reviewer, my main goal is to figure out how to use a new piece of software quickly so I can focus on seeing how well it does its job. Unfortunately, product documentation is usually of little help. Here are my three biggest documentation gripes: Documentation is missing: Sometimes a feature or component isn’t covered because it’s too new or simply wasn’t considered that important. For some free tools, I’ve found no documentation at all. No walkthroughs: When the documentation is present, it’s at the lowest level— what this property or method does. For a product of any complexity, I need to know how to string those method and property calls together. Developers need a walkthrough of typical scenarios. Documentation written by the developer: The people who wrote a tool know it best—unfortunately, they often can’t explain it best. Developer-written guides are often poorly organized and focus on what’s clever or difficult, rather than what’s important. Find more coverage of Visual Studio tools and solutions online at the ToolTracker blog on VisualStudioMagazine.com. —P.V. VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com </DevInsight> VS Insider BY SEBASTIAN HOLST PreEmptive Solutions became a Visual Studio insider (literally) when Microsoft began shipping our Dotfuscator CE code obfuscation module with Visual Studio back in 2003. Three Visual Studio launches later, the 2010 release of the IDE is still special for us. It began in early 2008 when we extended Dotfuscator CE beyond preventing reverse engineering of code to include applicationusage monitoring in the wild. Today, every version of Visual Studio 2010 except Express embeds Dotfuscator CE. The new application-monitoring capabilities include the injection of instrumentation, post-compile, into any managed assemblies that stream usage data at runtime to an endpoint for processing and analysis. We call it Runtime Intelligence. Developers can check out the Runtime Intelligence Endpoint Starter kit—available for download from CodePlex at tinyurl.com/ y37p4w7—to learn how to stream runtime data to any endpoint. We worked closely with Microsoft to enable these new capabilities under Visual Studio 2010, but even with Redmond’s aggressive ecosystem support, it wasn’t surprising that we found some gaps. Our work to integrate Runtime Intelligence into Silverlight served as a case in point. Silverlight sits at the crossroads of a rapidly evolving, heterogeneous computing landscape where developers, designers, end users and a complex network of stakeholders all have a vested interest in knowing their applications are being used. Developers need analytics to work across all of their Microsoft .NET Framework components (not just Silverlight), but designers are looking for Web analytics in line with existing services (not just managed code). ISVs need to include customer opt-in logic, while Web sites do not. In order to be effective, Silverlight instrumentation and analytics have to be broad enough to satisfy this diverse set of stakeholders, yet provide specific optimizations for each surface, development workflow and use case. Figure 1. Runtime Intelligence was missing critical data when tracking Silverlight applications. Hidden by Design As part of the Visual Studio launch, the crew of the .NET Rocks! talk show undertook a multi-city, crosscountry roadshow, and published a very cool Silverlight 4/Bing application that would organize tweets and show their location in real time. They chose to inject Runtime Intelligence to show how Visual Studio 2010 instrumentation could be applied. Figure 1 shows a surprise we got when the monitoring results came back. All Silverlight sessions seemed to end prematurely, unique user count was clearly inaccurate and there was no information on the runtime OS. Many of you probably already know how this part of the story ended. Silverlight by design does not allow service calls from the Application Exit event; therefore, the final Runtime Intelligence posts were all silently failing. Furthermore, the Silverlight sandbox hid the underlying runtime details used to identify unique users and the underlying OS—again by design. To address this behavior, we’re updating Dotfuscator to inject logic for Silverlight programs that write to isolated storage, so data saved at application exit is available at the next startup. The next time the instrumented application is fired up, it will check isolated storage for the information from earlier sessions and post it. The instrumentation will also generate an arbitrary value and write it to isolated storage to track unique user sessions. Filling Gaps As much as Microsoft works to support ISVs like PreEmptive with detailed documentation, early code previews, and direct access to product engineers and managers, at the end of the day it was up to us to discover—and ultimately fill—an unanticipated gap between our product and the Microsoft Silverlight platform. The result benefits everyone. We end up with a more capable service, Microsoft gets better support in Visual Studio for its vital Silverlight platform and developers gain access to vital application runtime data. VSM Sebastian Holst is chief marketing officer at PreEmptive Solutions LLC and has been a member of the W3C Advisory Committee for three years, a board member of IDEAlliance for four years and a cofounder of the Compliance Consortium. VisualStudioMagazine.com · September 2010 · VISUAL STUDIO MAGAZINE 11 Remote Monitoring Silverlight Surprise VSM COVER STORY Get Ready for the Entity Framework The industrial-strength Microsoft ORM is finally ready for prime time. Are you? BY KATHLEEN RICHARDS 12 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com 0810vsm_GrapeCity_Insert.indd 1 7/14/10 12:14 PM 0810vsm_GrapeCity_Insert.indd 2 7/14/10 12:15 PM VSM COVER STORY The ADO.NET Entity Framework 4, updated and released alongside the Microsoft .NET Framework 4 in April, is emerging as the default way to do data access in .NET-based applications. With the second generation of Entity Framework and related tooling in Visual Studio 2010, the Microsoft data access technology is better positioned for enterpriselevel projects with a host of new functionality that brings it more in line with other object-relational mapping (ORM) tools. The protests have died down with version 2 and the question of whether to use the implementation of LINQ known as LINQ to SQL—the lightweight ORM that Microsoft shipped in 2007—or the Entity Framework, has been put to rest. LINQ to SQL is still an option but Microsoft has indicated that the Entity Framework now supports much of the functionality offered in LINQ to SQL and the company isn’t putting any more resources behind it. Enterprise-Level Framework The Entity Framework 1, which shipped out of band in Visual Studio 2008 SP 1 and the .NET Framework 3.5 SP 1 after dropping out of the beta cycle, was only braved by early adopters. It was deemed unusable for enterprise projects by many developers based on feature limitations and lack of adequate support for n-tier architectures. “Until the most recent version of the Entity Framework, you could not easily build n-tier applications with it,” says Lenni Lobel, chief technology officer at Sleek Technologies Inc. and principal consultant at twenty-six New York. Lobel says he’s stayed away from the technology for enterprise-level production, but thinks the Entity Framework 4 is now viable for n-tier apps. Many of the advances in the Entity Framework 4 were driven by feedback from developers who already used ORM tooling, according to Lerman. It now supports n-tier architectures within the framework via API and T4 templates, such as self-tracking entities. Microsoft also added key functionality, such as support for foreign key associations, lazy or deferred loading, and Plain Old CLR Objects (POCOs). Go to VisualStudioMagazine.com/EF0910 for more on the Entity Framework and POCOs. “To me, the most important enhancement is the ability to support self-tracking entities once they’re disconnected from the object context, but there’s still a lot of work to be done,” says Lobel, who notes that the POCO template is now a separate download after the beta cycle. The Entity Framework 4 and Visual Studio 2010 support ModelFirst development, offering a Generate Database Wizard to create the database and parts of the EDM (SSDL, MSL) from a conceptual model. An Update Model Wizard helps you update the EDM when the database changes. The EDM Designer has had a lot of improvements, such as how it handles complex types, but Microsoft couldn’t come up with a way for people to deal with large models outside of a “large canvas,” a complaint from the Entity Framework 1. “If your model is so large—lots of entities—that it’s problematic in the designer, then you should probably be breaking the model up anyway, rather than asking the designer to enable you to work with it,” says Lerman. The EDM Wizard in Visual Studio 2010, which is used to create a conceptual model from an existing database (reverse engineering) and provide the database connections to your app, now supports foreign key associations and pluralization, which is important if you want to follow any kind of naming conventions for your entities. “Previously, you had do lots of modifications to the model afterward,” Lerman explains. The Entity Framework is becoming a core part of the Microsoft technology stack. It works with WCF Data Services, WCF RIA Services, ASP.NET Dynamic Data, ASP.NET MVC and Silverlight, which does not support ADO.NET data sets. “You can use LINQ to SQL or use your own classes as long as you follow certain rules, but a lot of those technologies are depending on a model. Entity Framework provides that model and Microsoft has built them so that they will very easily use an Entity Data Model from Entity Framework,” says Julie Lerman, an independent .NET consultant who specializes in data platforms. The Entity Data Model (EDM) provides a uniform way for developers to work with data by specifying the data structure of a client application through business logic, namely entities and relationships. EDM consists of a conceptual data model (domain), model-based storage structures and a mapping specification that connects the two. It exposes ADO.NET entities as objects in .NET, providing an object-layer for Microsoft LINQ. Using LINQ to Entities, Entity SQL or query builder methods, developers can write queries against the conceptual model and return objects. “It does remove all of the data access code that we used to have to The Microsoft Edge write,” says Lerman, who finished the second edition of her book, “Pro- A few months after its release, the Entity Framework 4 seems to gramming Entity Framework” (O’Reilly, 2010) in August. The book be holding up in comparisons with longstanding open source was rewritten to cover the Entity Framework 4 and Visual Studio 2010. ORM NHibernate. Mark Shiffer is a software architect for consultancy Capitol StratThe Entity Framework takes a different approach than a lot of typical ORMs because the model has a mapping layer, which egies. He’s working on a pilot project using the Entity Framework 4 allows developers to really customize the model, Lerman says. “It’s for the data access layer of an IT operations system for a benefits not just a direct representation of the database and that’s a really administration agency that handles the Illinois state retirement system. “We looked at NHibernate and Entity Framework; it was a toss important distinction.” “The goal of the Entity Framework is to be an abstraction layer on up between the two. The shifting factor was Microsoft’s backing top of your database, so in theory it’s supposed to reduce complexity,” of Entity Framework and it appears that they’re going to stick with says Steve Forte, chief strategy officer at Telerik, which offers a it,” says Shiffer. The project team, which consists of two consultants and four state competing ORM tool called OpenAccess. “However, developers know how to build applications the traditional way—data over forms—so employees, is rewriting the back-end IT operations. The design phase the Entity Framework is something new that needs to be learned and started a little less than a year ago, but the actual coding didn’t start until February, when the Entity Framework 4 and Visual Studio 2010 were the jury is still out on whether the learning curve is worth it.” VisualStudioMagazine.com · September 2010 · VISUAL STUDIO MAGAZINE 13 COVER STORY Entity Framework “You can use LINQ to SQL or use your own classes as long as you follow certain rules, but a lot of those technologies are depending on a model. Entity Framework provides that model.” Julie Lerman, Principal, The Data Farm Work in Progress still in beta. The pilot project focuses on a human resources system. The architecture for the project uses a Model-View-ViewModel The Entity Framework 1 only supported Database First (reverse design pattern with Windows Presentation Foundation, Windows engineering). The Entity Framework 4 added a somewhat limited Communication Foundation, Unity (an IoC container) and the Model-First option. The Database Generation Power Pack available Entity Framework 4 with Self-Tracking Entities. It also requires a for download in the Visual Studio Code Gallery gives you more repository pattern, and a Unit of Work pattern to provide transac- control over how the database schema is created by that domain model, according to Lerman. tional boundaries for data processes, according to Shiffer. “I’m a huge fan of the Model-First [option],” says Dane Morgridge, The IT operations system is a complete redesign, so the team is starting from scratch and using the new Model-First options in a Microsoft MVP for Data Platforms and solution architect at LiquidVisual Studio 2010 to create the conceptual model, and then generate Hub Inc. Morgridge has several projects using the Entity Framethe rest of the EDM and the database schemas. Shiffer is among the work 1 in production. “Previously, I was doing the database design developers who ran into a problem with the number of entities in in SQL Server Management Studio and ever since I started working with Visual Studio 2010, I’ve been doing all of my modeling within his model and limitations in the EDM designer. Even so, he contends that the flexibility and level of customization Visual Studio as opposed to SQL Server. And for what I’ve been supported in the Entity Framework 4 is critical for enterprise-level doing, it has been working great.” Morgridge’s team is using the Database Generation Power Pack— systems. “We had to write some custom workflow processes for the database generation piece and that’s all pretty easy to figure out which he says has huge potential—to figure out templates, but he because it just runs off of some workflows and we use the Self- points out that the Power Pack forces developers to modify the T4 Tracking Entities template, too … It was pretty easy to accomplish templates to create their own. Lerman says that Microsoft got a lot of feedback from the that, so that level of customization control was nice to see.” Shiffer says it’s a matter of understanding the pieces of the Entity ALT.NET community about things such as lack of POCO support. Framework, because the resources to plug in and extend the Entity “POCO support in Entity Framework 4 opens up the possibilities Framework are there. “The Object State Manager and the Object for architecting with repositories, if that’s what you want to do, and Context [entity container] are key concepts to the framework and doing unit testing and really building applications where you can once you understand those concepts, it makes implementing some have a good separation of concerns, which is really important when of the more intense features that we have to do for enterprise soft- you’re architecting large applications,” she says. Morgridge says ORMs have made things easier for developers ware easier,” he says. “We’re still in the middle of digging around in there and imple- but they don’t necessarily follow accepted patterns, such as reposimenting some of this stuff,” he continues, “but the Repository pattern tory patterns, out of the box. “My recommendation to anybody starting out is to look at blogs was very easy to implement within Entity Framework. Unit of Work was fairly easy as well, with the Object Context the way it’s set up. But that talk about how to use repository patterns and things like that, we’re still having some issues with threading because the Object Con- so that you can have clean separation,” he says. “Unfortunately, a lot text isn’t thread-safe, so that’s sending us for a bit of a loop right now.” of sample code just talks about dropping an EDMX file right in the Performance issues are the greatest concern in the pilot project, same folder as your project, and while that works, that’s really not namely errant SQL generation, which has the project team trying to the right way to do things. So, Entity Framework really is what it is, figure out whether the Entity Framework 4 is going to be efficient it’s just a matter of how you use it and what you do with it.” Morgridge’s T4 Template for Repository and Unit of Work patenough in the end. Shiffer describes a simple join and select for one record out of five or six tables, which ended up yielding up to 5,000 lines terns in the Entity Framework is available on CodePlex at efrepository.codeplex.com. of SQL code for the select statement under the Entity Framework SQL. “That’s the biggest question mark right now for us, because it can Reality of Stored Procedures spit out some pretty nasty SQL at times,” says Shiffer. Microsoft responded to Shiffer after he discussed some of these How the Entity Framework works with stored procedures was another issues in his blog. “They’re working on it and working to get it better,” bone of contention in the Entity Framework 1, specifically in the area of data security requirements. Database administrators had a problem he says. Microsoft declined to comment for this article. Will Shiffer and his team switch frameworks? That depends, he with letting the Entity Framework access database tables directly and says, on what his team can do to optimize the SQL code coming out do all of the command generation (SELECT, UPDATE, INSERT and DELETE), instead of using pre-defined stored procedures. of the Entity Framework. “If those stored procedures use output parameters, you’re out of “There are various ways we could do that,” Shiffer explains. “We could stick with Entity Framework and write stored procedure luck,” says Sleek Technologies CTO Lobel. He says Microsoft needs to processes and have them called from there, but that takes away support stored procedures, “not just stored procedures with caveats.” Microsoft has done a lot to improve in that area, according to some of the benefits of using Entity Framework for an ORM. So that decision hasn’t been made yet, that’s why we’re in the middle Lerman. “They worked really hard on how the queries are compiled, which essentially is the process by which you go from a LINQ to of a pilot project trying to test everything out.” 14 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com Project3 12/16/09 11:55 AM Page 1 COVER STORY Entity Framework “To me, the most important enhancement is the ability to support self-tracking entities once they’re disconnected from the object context, but there’s still a lot of work to be done.” Lenni Lobel, Chief Technology Officer, Sleek Technologies Inc. Entities query to a stored query, whether that’s a T-SQL query in SQL Server or something in another database,” she says. Even in the Entity Framework 1, you could build models just from using stored procedures, according to Lerman, by building views on top of tables and then building a model around the views and stored procedures. and chief of new technology at twenty-six New York. “I think they add an extra layer, which although elegant and helpful for large apps, is often overkill for smaller ones.” Many developers who use the Entity Framework aren’t using the entities that it produces directly, but instead create their own wrapper classes, according to Brust. “As long as they’re doing that then why not wrap ADO.NET objects directly?” he asks. Morgridge says there are lots of advantages to using an ORM and while the complexity is there, he doesn’t think it’s great enough to warrant not using it. “It’s really never overkill. The only place I wouldn’t use an ORM is in a case where performance was an utmost factor because the whole additional layer can add some performance issues potentially,” he says. “Sometimes you’re not going to get the most performant-generated SQL out of LINQ expressions. If it’s a case where performance is really an issue, then that’s when I will go back and do a stored procedure or some other ADO.NET method.” Even with small projects, Morgridge says he saves a lot of time by using an ORM. “It cuts my data access code time by 70 percent easy, because I don’t have to write hand-coded SQL statements and things like that.” “It’s definitely worth taking a look at, especially if you’re trying to compare using Entity Framework to using ADO.NET directly,” says Shiffer. “It provides that wrapper that you need to separate your data layer out, and to abstract your concerns about SQL statements and not having to really be concerned with the data structure as much as you normally are if you didn’t have an object-relational mapper in the middle of it all.” Just Programming In late July, Scott Guthrie, corporate vice president of the .NET Developer Platform at Microsoft, got domain developers’ attention with a series of blog posts about the upcoming Code-First option, a longstanding feature of NHibernate, OpenAccess and other ORM frameworks. Microsoft has talked about the Code-First feature since the Entity Framework 1, but has yet to deliver it. “Depending on what you’re doing, Code First is going to be as easy as LINQ to SQL,” says Lerman. “It eliminates writing the visual model, you just write classes and then configure them a little further if you need to, to make them work for the Entity Framework.” She cautions that Code-First is still in the preview stage—it’s part of the Entity Framework Feature CTP 4—and not available for go-live production. But if Guthrie is blogging about it, chances are Microsoft has the features fairly nailed down. Microsoft is responding to a “decently sized” segment of the market that would stay away from the Entity Framework without the Code-First design pattern, observes Forte. “Microsoft’s target audience with both LINQ to SQL and the Entity Framework is probably not the developer that goes Code First,” he says, “but I think that the market dragged them in that direction, so it’s actually pretty interesting and there’s a good level Riding the Coattails of innovation that’s coming out of it.” Telerik’s Steve Forte expects the growing popularity of other MicroOther API enhancements in the Feature pack should make pro- soft technologies—WCF RIA Services and OData with WCF Data gramming against the Entity Framework in the next release simpler. “In Services—to help drive Entity Framework adoption, and says he’s the core API, they’re kind of wrapping some of the other functionality already fielding questions along those lines from customers. so that it’s easier to find and easier to write,” says Lerman. Brust holds a similar view. “Silverlight, WCF Data Services (aka When the simpler API was first announced in June, Rowan Miller, a “Astoria”) and ASP.NET MVC are proving very popular; Entity Microsoft program manager on the Entity Framework Team, blogged: Framework gets to ride coattails.” At the heart of the Entity Framework Productivity Improvements Hybrid applications are another form of adoption. “If you have a are two new types, DbContext and DbSet<TEntity>. DbContext is a brownfield app and you’ve invested heavily in data over forms and simplified alternative to ObjectContext and is the primary object for stored procedures, that doesn’t mean that there isn’t room for an interacting with a database using a specific model. DbSet<TEntity> ORM like Entity Framework, or OpenAccess or NHibernate in is a simplified alternative to ObjectSet<TEntity>and is used to your project,” says Forte. “They have the ability to hook into reporting perform CRUD operations against a specific type from the model. engines and hook into OData, and all three now hook into RIA These new types can be used regardless of whether you created your Services. That’s one thing that should be obvious, but it may not be.” model using the Entity Designer or code. It even works with the cloud. The Visual Studio 2010 design tools didn’t initially support SQL Azure, so you couldn’t point to a SQL Azure table and create a model from it, but that’s changed. Hard Sell The effort to reduce the complexity of the Entity Framework under- SQL Azure also lacked support for Multiple Active Result Sets scores Microsoft’s task of pleasing enterprise-level ORM developers, (MARS), which would have affected Entity Framework 4 features many with a Java background, and others in the .NET community, like lazy loading, but Microsoft’s database in the cloud has since added MARS support. VSM who still need to be sold on the ORM concept. Andrew Brust thinks Entity Framework should be an option, rather than the default way to do data access in .NET-based apps. Kathleen Richards ([email protected]) is the executive editor of “First of all, I don’t love ORMs,” says the Redmond Review columnist Visual Studio Magazine and the editor of RedDevNews.com. 16 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com Project1 10/30/09 1:28 PM Page 1 DynamicPDF Viewer O u r n e w, c u s t o m i z a b l e DynamicPDF Viewer allows you to display PDF documents within any WinForm application. No longer rely on an external viewer for displaying your PDF documents. DynamicPDF Viewer utilizes the proven reliable and efficient Foxit PDF viewing engine and maximizes performance and compatibility with our other DynamicPDF products. DynamicPDF Converter Try our three new products FREE today! Fully functional and never expiring evaluation editions available at www.cete.com/download Our DynamicPDF Converter library can efficiently convert over 30 document types (including HTML and all common Office file formats) to PDF. Events can be used to manage the action taken on a successful or failed conversion. It is highly intuitive and flexible and integrates well with our other DynamicPDF products. DynamicPDF Rasterizer Our DynamicPDF Rasterizer library can quickly convert PDF documents to over 10 common image formats including multi-page TIFF. Rasterizing form field values as well as annotations is fully supported. PDFs can also be rasterized to a System.Drawing.Bitmap class for further manipulation. To learn more about these or any of our other popular tools: DynamicPDF Generator, DynamicPDF Merger, DynamicPDF ReportWriter, DynamicPDF Suite, DynamicPDF WebCache or Firemail, visit us online. ceTe Software has been delivering quality software applications and components to our customers for over 10 years. Our DynamicPDF product line has proven our commitment to delivering innovative software components and our ability to respond to the changing needs of software developers. We back our products with a first class support team trained to provide timely, accurate and thorough responses to any support needs. FEATURE SQL Server 2008 R2 FOR THE DEVELOPER In April, Microsoft released a new version of its flagship database server, with the unwieldy name SQL Server 2008 R2. Version R2 leaves the core database engine of SQL Server 2008 almost completely untouched, but adds a slew of new features that can dramatically expand the role of SQL Server in managing an enterprise’s data. Microsoft only occasionally uses the R2 moniker for its applications, usually for point releases that add a few new features. By contrast, major new versions deliver a host of new features and fixes, while service packs mostly fix bugs. The nice thing about SQL Server 2008 R2 is that it leaves intact what is now a very stable, 2-year-old database engine. Enterprises should be comfortable installing SQL Server 2008 R2 and benefiting from its new features without worrying about breaking changes to the core engine. With SQL Server 2008 R2, Microsoft is filling out the feature set of a mature database product. There are two new top-end SQL Server editions with the R2 release: Datacenter for the biggest and most heavily used enterprise databases, and Parallel Data Warehouse with massively parallel processing to support intensively used data warehouses. A few features from the original release of SQL Server 2008 are migrating to less-expensive editions. For example, backup compression, originally available only with the Enterprise Edition, is now part of the Standard Edition. And the largest database supported by SQL 18 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com Server Express is going up from 4GB to 10GB, a welcome change to allow more flexibility for desktop applications. When reading the Microsoft marketing materials you might get the impression that SQL Server 2008 R2 is targeted only at DBAs and enterprise system architects, cementing the company’s increasingly enterprise-centric focus. But dig more deeply and you’ll find plenty of goodies for developers. In this article, I’ll briefly cover some of the more interesting new features that you can use in application development, as well as a few features that you may encounter that will affect how you write applications. Deep security is one of the primary reasons to use a database server product like SQL Server. But the only significant new security feature in SQL Server 2008 R2 is Extended Protection for authentication, used to prevent authentication relay attacks. This is an attack in which a malicious server uses the credentials of an authenticated user contained in client software to masquerade as the user, thereby giving the attacker access to whatever data the user can access. Extended Protection uses a combination of service and channel bindings to validate that the user is not an attacker and establish a secure channel to verify the authenticity of the client. Extended Protection requires versions of Windows with the feature installed and activated (it’s turned off by default). Application and Multi-Server Management Some new developer features are tightly coupled to server instance management, as is the case with application and multi-server management. The new SQL Server Utility lets a systems administrator create a utility control point on a single instance of SQL Server 2008 R2, which ILLUSTRATION BY RYAN ETTER Microsoft extends its enterprise-capable database platform with powerful new management and scalability features—and there’s plenty in the latest rev for developers. By Don Kiely FEATURE acts as a central repository for configuration and performance data that it collects for all instances of SQL Server enrolled in the utility. The utility control point provides a DBA with far more control and monitoring features than have been previously available to apply policies and analyze resource utilization trends, which help predict and prevent failures due to resource depletion. A companion Utility Explorer displays a dashboard and detailed viewpoints to monitor enrolled instances of SQL Server. As part of these multi-server management features, either a developer or a DBA can define a data-tier application (DAC) that simplifies developing, deploying and managing database objects that support data applications. (Yes, the acronym is DAC and not DTA, which already means Database Engine Tuning Advisor.) A DAC defines all of the database objects—including schemas— needed to support an application. By extracting the database objects and creating a single unit of deployment in a single file type, you can migrate them to the centrally managed world of multiserver management as well as apply upgrades to the various objects. Figure 1 shows the wizard from Management Studio that DBAs use to extract a DAC from an existing set of database objects and generate a DAC package file. You can create a DAC from scratch in Visual Studio 2010 with the SQL Server Data-Tier Application project template. The project Visual Studio creates from this template looks similar to a Database Edition project (the SQL Server 2008 Database Project template), but the end result of building a DAC project is a DACPAC file you can deploy to a SQL Server instance. The SQL Server Data-Tier Application project template hooks into the Code Analysis feature in Visual Studio, shown in Figure 2 (p. 20). Code Analysis helps you improve the quality of your database code every time you build the project. The Design, Naming and Performance categories can help ferret out some of the most basic and common problems that can hurt performance and Figure 1. The SQL Server 2008 R2 Extract Data-Tier Application wizard lets you extract an existing database as a data-tier application (DAC). You can also register a database as a DAC with the accompanying Register Data-Tier Application wizard. complicate code maintenance over the long term. As with all code analysis in Visual Studio, you can select the tests you want and choose to correct or ignore any problems they find. It remains to be seen whether this first version of DAC is robust enough to handle more than applying small changes to departmental databases. For now, DACs are best suited for deploying and updating Microsoft SQL Azure databases. R2 Gives Reporting Services a Boost Reporting Services probably received the biggest number of enhancements in SQL Server 2008 R2 of any feature that shipped with the original SQL Server 2008. SQL Server 2008 R2 includes a number of general reporting enhancements. The improved lookup functions let you join datasets within Reporting Services using new functions. The LookupSet function returns a set of matching values and the Multilookup function returns the set of first-match values for a set of names. You can now build an aggregate on top of other aggregates, for instance, to average a sum of values. RenderFormat lets you control the output formatting of data based on where you’re rendering out the data, such as to Excel or a report, and provides far more control over page breaks and numbering. SQL Server 2008 R2 includes four new data visualization features: sparklines, data bars, indicators and maps. Data bars indicate the magnitude of a value by its length, while a sparkline displays multiple data points. These often show the trend of a single variable, such as sales, over time in a small area of screen or report space. Indicators let you display different icons based on a single data value. Finally, maps let you hook into the spatial data features of SQL Server 2008 R2 in a report, so you can display maps based on a report’s data. Reporting Services still doesn’t include any calendar controls, so there’s still room for data-visualization improvement. Report Manager and Report Viewer have both gotten significant upgrades. Report Manager has an improved interface that’s easier to use, while Report Viewer uses AJAX and a JavaScript object model in Web reports to make it easier to respond to client-side events. Report Viewer also supports additional browsers, including more recent versions of Internet Explorer and Firefox. Reporting Services has long had the ability to share and use multiple data sources, but now you can share datasets to provide consistent data for multiple reports. You can cache the query results for various combinations of parameters and refresh on demand or on a defined schedule. Microsoft made lots of enhancements to Report Builder 3.0. The datasets that it uses are now cached for faster rendering in the current session for up to two hours. It now supports relative references that let you access different parts of reports as action targets. Report Builder also includes a report part gallery that lets you search for reusable report parts. The most intriguing new feature in Reporting Services is using reports as a data source, exposing the data as an ATOM data service. This allows you to provide the report data to other applications, such as sending it to PowerPivot or exposing it though a URL for direct access to the feed. Make sure you check out the “What’s New (Reporting Services)” topic in MSDN Books Online at tinyurl.com/25ld4od for a complete rundown of all the enhancements. Reporting Services has gotten more powerful, —D.K. giving users better insight into their data than ever before. VisualStudioMagazine.com · September 2010 · VISUAL STUDIO MAGAZINE 19 FEATURE SQL Server 2008 R2 Figure 2. The Code Analysis tab in a DAC project properties window lets you analyze your database code. The checks are straightforward, but can help improve your code and make it more consistent for better maintainability. BI for the Power User Probably the most dramatic and visually striking new feature in SQL Server 2008 R2 is PowerPivot for Excel and for SharePoint. PowerPivot provides self-service business intelligence (BI) so end users can create and manipulate data, letting them slice, dice, analyze, and share data and reports. PowerPivot for Excel is a sepa- rate free download for Excel 2007 and 2010 (although you need Excel 2010 to make use of all the PowerPivot features), and PowerPivot for SharePoint adds shared services for working with Excel PowerPivot workbooks that you can publish to SharePoint. Microsoft calls the set of PowerPivot features “managed selfservice business intelligence,” and that’s an apt description. Enterprise BI is beyond the understanding of mere mortals, yet it’s mere mortals who need the information and analyses that BI generates to make business decisions. For power users, PowerPivot provides tools in the familiar Excel environment. It also gives systems administrators the tools they need to provide data in a form that users can utilize, as well as to facilitate sharing the resulting data and analyses. Most importantly, users can make their own analyses without waiting for IT to generate reports. The Excel add-in provides several components on the user’s local machine, including a PowerPivot menu in the Excel ribbon to launch the design window and work with data, and a PowerPivot window that provides all the design tools the user needs. There’s also a local Analysis Services engine that compresses and loads data, and other tools for accessing various sources of data. Figure 3 shows most of the visual components at work with the design window in the foreground, after loading data from the FactInternetSales and related tables from the AdventureWorks2008R2 sample database. Over the years, Microsoft and other vendors have made various attempts to make BI data available to power users. PowerPivot seems to be the first attempt to deliver sophisticated tools that can fully leverage the information locked in data warehouses. The tool is certainly not targeted at the casual user, but neither does it require a degree in computer science to extract valuable data and information. I’ve just scratched the surface of what is new, shiny and exciting in SQL Server 2008 R2. There’s a lot more there for DBAs, including features like Master Data Services for streamlining enterprise data into a single version of the truth, and StreamInsight for event processing to handle massive volumes of complex data in real time. Database compression supports Unicode now, and Microsoft has added features to support high-volume data warehouses. Developers, of course, will find plenty to help their applications make better use of better data. VSM Figure 3. Excel power users will be immediately comfortable with using the PowerPivot add-in for Excel. The PowerPivot window shown here lets users access data sources and manipulate data to their hearts’ content. 20 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com Don Kiely ([email protected]), MVP, MSCD, is a senior technology consultant. When he isn’t writing software, he’s writing about technology, speaking about technology at conferences and training others. d WPF Gri Fast Data Chart Silverlight Grid ASP .NET Grid At Infragistics, we make sure our NetAdvantage for .NET controls make every part of your User Interface the very best it can be. That’s why we’ve tested and re-tested to make sure our Data Grids are the very fastest grids on the market and our Data Charts outperform any you’ve ever experienced. Use our controls and not only will you get the fastest load times, but your apps will always look good too. Fast and good-looking…that’s a killer app. Try them for yourself at infragistics.com/wow. Infragistics Sales 800 231 8588 Infragistics Europe Sales +44 (0) 800 298 9055 Infragistics India +91-80-6785-1111 twitter.com/infragistics Copyright 1996-2010 Infragistics, Inc. All rights reserved. Infragistics and the Infragistics logo and NetAdvantage are registered trademarks of Infragistics, Inc. Untitled-12 1 4/9/10 1:54 PM Untitled-1 1 8/3/10 3:25 PM FEATURE LAB MANAGEMENT IN 2010 Visual Studio Visual Studio Lab Management promises to streamline thorny debug and test challenges by enabling an efficient, virtualized test environment. BY VIJAY MACHIRAJU Many teams have started improving their software development lifecycle using Visual Studio 2010 and Team Foundation Server 2010. Developers can now easily track their work items, version control their source code and manage builds using Visual Studio 2010. In addition, Visual Studio 2010 brings in a great set of architecture and testing tools to integrate the work of all software engineering disciplines in a project. For instance, software testers can use the new testing tools in Visual Studio to create test plans, run tests on various configurations, collect logs to be included in bugs and generate test reports. So, what else can you do with Visual Studio 2010 to increase your productivity? What if you could do the following: ■ Easily create multi-machine test environments to aid in your development or testing activities. ■ Deploy build after build into test environments without having to worry about re-imaging the machines or uninstalling the earlier builds. ■ Increase the build quality by running a set of automated integration tests in addition to unit tests after every build. ■ Collect and attach server logs with bugs in addition to client-side logs, so that developers can fix those bugs faster. In August 2010, Microsoft made Visual Studio Lab Management available without any additional cost for all MSDN subscribers of Visual Studio 2010 Ultimate and Visual Studio Test Professional 2010. For the first time, Lab Management brings the power of virtualization to your Visual Studio-based development process. This article will help you navigate this new technology by describing how it works and how you can realize scenarios such as the ones just described. How Lab Management Works Using virtual machines (VMs) for software development has many benefits. Developers can create sand-boxed environments using VMs and install different software components in them without having to worry about conflicts. They can create a virtual hard disk called the golden image with the base OS and all the necessary prerequisite software for their development needs. After working on a copy of that golden image for a while, they can simply discard that and start fresh from another copy of it without having to re-install the OS or prerequisites. To create VMs, developers often use desktop virtualization tools, such as Microsoft Virtual PC, because they’re easy to install on their desktops. However, to run VMs more efficiently, you need a layer of software called hypervisor that runs directly on physical hardware. Microsoft Hyper-V is a hypervisor that’s included as part of the Windows Server 2008 R2 OS, or as a standalone, free download product. Using Hyper-V, you can easily host multiple VMs on a single physical computer. The physical computer is then called a Hyper-V host. But, what if you want to set up a shared lab of Hyper-V hosts for the benefit of the entire team? Or, what if you want to manage a library of golden images? That’s where Microsoft System Center Virtual Machine Manager (SCVMM) 2008 R2 comes in. SCVMM 2008 R2 is a tool for managing multiple hypervisors. VisualStudioMagazine.com · September 2010 · VISUAL STUDIO MAGAZINE 23 FEATURE Lab Management Using SCVMM 2008 R2, you can pool several Hyper-V hosts into a host group. You can also set up a few machines called library servers to store and manage golden images of various OSes that are commonly used in your project. Every time you need to create a new VM, SCVMM 2008 R2 lets you pick a golden image and one of the host groups and provision a VM in a self-service manner. Although SCVMM 2008 R2 is a great management tool for IT administrators, Visual Studio Lab Management makes virtualization features more easily accessible to developers and testers. It’s implemented as a service in Team Foundation Server, just like version control or work-item tracking. Internally, this service uses SCVMM 2008 R2 and lets you create and use VM environments on Hyper-V hosts right from Microsoft Test Manager or Visual Studio (see Figure 1). Detailed steps for setting up Lab Management can be found in MSDN documentation. In addition, there are several articles on the Visual Studio Lab Management team blog (blogs.msdn.com/b/ lab_management) that provide additional guidance on topics such as capacity planning and supported network topologies as you adopt Lab Management. Creating Environments Setting up and maintaining environments for development, testing, integration and staging is a painstaking task for software teams. Visual Studio Lab Management enables your team members to create environments easily in a self-service manner without having to incur long lead times for IT to provision them. An environment in Lab Management is simply a collection of virtual machines, each fulfilling a role for the application you are developing. For instance, an environment can consist of a virtual machine serving as a database and another virtual machine serving as a Web server. Using Lab Management, you can create environments in one of three ways: Visual Studio 2010 Ultimate or Visual Studio Test Professional 2010 Clients Team Foundation Server 2010 System Center Virtual Machine Manager 2008 R2 Library Servers Hyper-V Hosts Figure 1. Lab Management Architecture 24 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com From VMs you already have From a set of golden images stored in the library ■ By cloning another environment Creating environments from golden images reduces the duplication of effort because these images can be created once and then reused multiple times. To prepare a reusable golden image, follow these steps: ■ Create a VM with all prerequisites: Prepare one VM for each role that you need for your application under test, and for each configuration that you need of that role. As an example, if your application requires a Web server that has to run on a Windows Server 2008 OS, create one VM with a Windows Server 2008 OS, and enable the IIS role in it. ■ Install Visual Studio Agents 2010 in the VM: Visual Studio Agents 2010 is additional software that’s available as a free download with Visual Studio 2010. Lab Management requires that you install three agents in the VMs—Test Agent 2010, Lab Agent 2010 and Build Agent. The software for the first two agents is part of Visual Studio Agents 2010. The software for Build Agent is part of the Team Foundation Server installation. There’s a great utility called VM Prep Tool at vslabmgmt.codeplex.com, which can help you simplify the installation of all three agents into a VM. ■ Store the VM in the library: The VM Prep Tool also generalizes the VM and stores it as a golden image in the library. Every time you use the golden image for creating a new environment, it’ll be customized with a unique computer name. To create an environment from golden images, follow these steps: 1. Import the golden images into your team project: Before using the golden images, you have to first import them into your project. Do this from the Library tab under Lab Center in Microsoft Test Manager 2010. When you import the golden image, you have to provide information on how it should be customized every time an environment is created from it. For example, you have to enter a product key and the Active Directory domain it should be joined to, among other things. 2. Create a new virtual environment: Using the Creation Wizard in the Lab tab, select the golden images and create a new environment. This paradigm of creating an environment on demand from a set of golden images and making that accessible to developers and testers changes the way software teams provision environments. You don’t have to perform the repetitive tasks of installing OSes and prerequisites. Later in this article, we’ll explore another way of creating environments by cloning them. ■ ■ Deploying Application Builds Self-service creation of environments is only the beginning of what you can do with Lab Management. The real value of this technology comes when you start using the rich integration features of those environments. The first such integration is with build automation. Project teams spend significant resources in deploying every build on multiple environments before an application goes into production. Ad hoc processes are followed to roll back an environment to a clean state and to re-try the process each time a deployment fails. Furthermore, test teams have to repeat the same tests on every build to catch regressions. Although it’s expensive for regression tests to be re-run on every build, not doing so often would only delay the detection of problems, thereby affecting the quality of your application. Fast Data Char ts Geosp atial Maps Silverlight Pivot Grids You’ve got the data, but time, budget and staff constraints can make it hard to present that valuable information in a way that will impress. With Infragistics’ NetAdvantage for Silverlight Data Visualization and NetAdvantage for WPF Data Visualization, you can create Web-based data visualizations and dashboarddriven applications on Microsoft Silverlight and WPF that will not only impress decision makers, it actually empowers them. Go to infragistics.com/sldv today and get inspired to create killer apps. Infragistics Sales 800 231 8588 Infragistics Europe Sales +44 (0) 800 298 9055 Infragistics India +91-80-6785-1111 twitter.com/infragistics Untitled-1 1 Copyright 1996-2010 Infragistics, Inc. All rights reserved. Infragistics and the Infragistics logo and NetAdvantage are registered trademarks of Infragistics, Inc. 8/3/10 10:41 AM FEATURE Lab Management In addition to deploying builds on a clean snapshot, Lab Management also allows you to run a set of automated regression tests on it. This entire build-deploy-test workflow is available just as another build template in Visual Studio. ■ Reproduce the bug: When a developer sees the bug in Team Lab Management exploits the power of snapshots to simplify the deployment of application builds into an environment. A snapshot Explorer, he or she can open the snapshot to connect to the same is a “marker” of an entire state of an environment at a given point in environment, provided the environment is not in use by the tester. time. A user can revert to that snapshot at any time, and resume the With this feature, testers don’t have to spend time finding a conexecution of the machines from exactly the same state they were in sistent reproduction for an accidental bug they discovered. Coupled when the snapshot was taken. This makes it convenient to preserve with the rich data collection features, snapshots provide all the the clean state of an environment. One can revert to this clean state information necessary for a developer to act upon an issue. The before deploying a build or after running tests. turnaround of a bug that’s otherwise spent by developers in reproIn addition to deploying builds on a clean snapshot, Lab Manage- ducing it or in recreating the environment is cut down. ment also allows you to run a set of automated regression tests on it. This entire build-deploy-test workflow is available just as another Cloning Environments build template in Visual Studio. Wouldn’t you want the testers to use the same environment on which Follow these steps to create a build-deploy-test workflow: the build-deploy-test workflow was run? When a tester finds a bug, ■ Create a build-deploy-test workflow definition: Using Visual wouldn’t you want a developer to use the same environment to verify Studio Team Explorer, create a new build definition starting the fix? But, all this sharing diminishes the productivity of a team, from lab default template. While creating the definition select because it requires team members to schedule their time to share the virtual environment, the clean snapshot to restore the envi- environments. Lab Management allows cloning of environments so ronment to, the definition for compiling sources, the scripts that every developer and tester can get his own private copy. Bringing up multiple clones of environments at the same time causes for deployment and the test suite. ■ Queue the new build definition: You can either set the buildcomputer name and other networking conflicts. Lab Management deploy-test workflow to be triggered manually or on a schedule. solves this problem through a technology called network isolation, With this, dev teams don’t have to worry about consistency of which automatically configures the network of VMs and their IP the deployment process in various environments. You don’t have to stack to avoid conflicts. Follow these steps to copy environments: ■ Configure network isolation: When creating the environment, spend time running rollback scripts or performing additional procedures when deployment fails. Simply revert to the clean snapshot ensure that network isolation capability is selected. ■ Store a fully prepared environment in the library: After of the environment before deploying the next build. You can also run regression and integration tests in addition to unit tests, because working with it (or after filing a bug with snapshot), shut you have a real environment on which the build is deployed. Testers down the environment and store a copy in the library. Once will now have a better sense of the build quality. the copying is done, you can continue working with it. ■ Create clone: Deploy another copy of the environment from Running Tests the library. At this point, you have two deployed environments. Finding bugs and identifying steps to reproduce them is still more of an art than science. And because of project deadlines, developers often Save Time and Resources don’t have the time to re-create environments to adequately verify their Visual Studio Lab Management enables teams to accelerate setup fixes. These problems often cause software teams to remain inefficient. and restoration of complex multi-machine environments to a All the testing features of Microsoft Test Manager can be exercised known clean state for test execution and build automation. It also on environments created by Visual Studio Lab Management. By allows testers to file rich bugs with links to environment snapshots using environments either in manual or automated testing, you can that developers can then use to re-create complex environments, collect logs of various forms from all machines in the environment. effectively reducing wasted time and resources in development and Testers can attach these logs when they file bugs. In fact, testers can test lifecycle. With the August release of Lab Management, this set also include a snapshot of the entire environment to the bug. of features is available for you to use, if you’re a Visual Studio Developers can then connect to the same environment or to a copy 2010 Ultimate with MSDN or Visual Studio Test Professional 2010 of the environment to reproduce the problem or to validate their with MSDN user. VSM fix. Follow these steps to file a bug with snapshot: ■ Configure to run your test cases on an environment: Create Vijay Machiraju is a senior program manager at Microsoft with the Visual a Test Settings in Microsoft Test Manager using the same set of Studio Team, leading the engineering effort of various features in Lab roles that you used when creating the environment. Use the Test Management. Being in the software industry since 1997, he specializes in Settings tab under Lab Center to do this. While running your application lifecycle management, systems management and virtualization. manual tests, select the option to run the tests on an environment. He’s the coauthor of “Web Services—Concepts, Architectures and Applica■ File a rich bug: During your testing session, when you find a bug, tions” (Springer, 2004) and has published at various conferences. Machiraju take a snapshot of the environment. When a bug is filed, the snap- has a master’s degree in computer science from University of Utah in Salt shot and a variety of logs are automatically attached to the bug. Lake City. You can reach him at [email protected]. 26 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com Gantt Chart You have the vision, but time, budget and staff constraints prevent you from seeing it through. With rich user interface controls like Gantt Charts that Infragistics NetAdvantage® for .NET adds to your Visual Studio 2010 toolbox, you can go to market faster with extreme functionality, complete usability and the “Wow-factor!” Go to infragistics.com/spark now to get innovative controls for creating Killer Apps. Infragistics Sales 800 231 8588 Infragistics Europe Sales +44 (0) 800 298 9055 Infragistics India +91-80-6785-1111 twitter.com/infragistics Copyright 1996-2010 Infragistics, Inc. All rights reserved. Infragistics, the Infragistics logo and NetAdvantage are registered trademarks of Infragistics, Inc. All other trademarks or registered trademarks are the property of their respective owner(s). Untitled-12 1 4/9/10 1:55 PM </Language Lab> YO U R C O D E S O U R C E IN THIS SECTION: On VB · 28 // Ask Kathleen · 34 ////////////////////// ASP.NET MVC 2 { ON VB } How to Validate Forms with ASP.NET MVC 2 Data Annotations Simplify the task of validating Web form input by using attributes. If standard validators don’t meet your needs, you can create custom data annotations for richer validations. BY JOE KUNK AND VIJAY JAGDALE The movement toward declarative statements over detailed procedural programming and convention over configuration signify growing trends in application development. Declarative statements instruct the compiler more on what to do and less on how to do it. “Convention over configuration” refers to the practice of organizing and naming application elements in a predictable and expected manner so that the desired behavior can be inferred by the compiler. Both of these practices result in increased developer productivity and reduced complexity by offloading routine tasks to the compiler. Developers should welcome these changes and strive to take full advantage of them. Data Annotations, introduced in version 2 of the Microsoft ASP.NET Model-View-Controller (MVC) platform, offer a declarative way to validate Web form fields and provide important error messages to users when necessary. In this article, we’ll look at the standard validators in the ASP.NET MVC 2 platform and demonstrate the development of a custom validator that works at both the client level with JavaScript and the server level with managed code. You’ll see how easily a functional Web site can be built by taking advantage of the convention over configuration provided by ASP.NET MVC 2. Basic CRUD Applications First, let’s move through the process of building a standard ASP.NET MVC 2 Web application that provides basic Create Read Update Delete (CRUD) capabilities (the full source code of the sample application is available for download from VisualStudioMagazine. com/Kunk0910). The Visual Basic sample application was developed in Visual Studio 2010 and ASP.NET MVC 2, which is part of the Microsoft .NET Framework 4. Select the ASP.NET MVC 2 Web Application template from the New Project dialog. Although you won’t be building unit tests in this article, we recommend always responding yes to the Create Unit Test Project dialog for easier unit test coding at a later date. Right-click the App_Data folder, add new item and select the SQL Server Database template. Using Server Explorer, create a Customer table with the fields as shown in Figure 1. The CustomerId field is an identity seed column and must be marked as the primary key. Create a few rows of data for the Web site to work with when completed. 28 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com Figure 1. Customer table fields. LINQ to SQL is a quick way to build interaction with the database. Right-click the Model folder and create a data context by choosing the LINQ to SQL Classes template. Add the Customer table by dragging it from the Server Explorer to the LINQ to SQL design surface. Use the SQLMetal utility to create a data context for any non-trivial database. More information on LINQ to SQL and SQLMetal can be found in Roger Jennings’ cover story, “Speed O/R Mapping with LINQ to SQL” (December 2008). Controller and Action Methods Add a controller named CustomerController, which will perform the interactions between the customer table and its related Web pages. Right-click the Controller folder and choose Add Controller or use the keyboard shortcut of Ctrl+M, Ctrl+C. Be sure to check the option “Add action methods for Create, Update, Delete and Details scenarios” of the resulting Add Controller dialog. This creates the scaffolding for all the action methods required for a simple CRUD controller. At this point, build the solution. This is an important step, required to see strongly typed classes in the Add View dialog box in the following step. At the start of the Controller source, add Imports Models. Create Web page views for each of the actions defined within the CustomerController. Place your cursor within an action method in the CustomerController then right-click and choose Add View or use the keyboard shortcut Ctrl+M, Ctrl+V. Figure 2 (p. 30) shows how to create a strongly-typed List view for the Index action. Similarly, create strongly typed views for the other GET actions, using the corresponding View Content for each action. You should now have Create, Delete, Details, Edit and Index .ASPX files in the Customer folder within the Views folder. This ability to create default controllers and views is convention over configuration at work for you. Complete the basic ASP.NET MVC 2 Web site by adding LINQ to SQL code to interact with the database. Listing 1 (p. 30) shows the code for the Index method that lists customers and the Edit methods that retrieve an existing customer for editing and NOVEMBER 14–17, 2010 ORLANDO, FL | HILTON WALT DISNEY WORLD RESORT FOUR DAYS THAT WILL ROCK YOUR CODE. Are you ready to take your code to the next level? Expand your skillset and maximize the development capabilities of Visual Studio during the four action-packed days of Visual Studio Live! Orlando! With pre-conference workshops, 60+ sessions by expert instructors, and keynotes by industry heavyweights, you’ll walk away with knowledge and skills you can put to use today. HARD-HITTING, REAL-WORLD TRAINING ON: PROGRAMING WITH WCF ARCHITECTING FOR AZURE WPF & SILVERLIGHT ASP.NET 4 jQUERY FOR ASP.NET WHAT’S NEW IN VISUAL STUDIO 2010 SHAREPOINT 2010 FOR ASP.NET DEVELOPERS DETAILS AND REGISTRATION AT VSLIVE.COM/ORLANDO USE PRIORITY CODE NQZF10 Supported by: Untitled-11 1 8/17/10 3:51 PM </Language Lab> { ON VB } ASP.NET MVC 2 similar to the <HttpPost()> attribute in Listing 1. By applying these attributes, you can specify which validations are appropriate for the particular field. Both server-side and optional client-side JavaScript validations are supported. The included standard validation annotations are Required, StringLength, RegularExpression and Range. Each annotation provides parameters for a custom error message and resource support to optionally globalize the error message. In addition, the Required annotation provides a Boolean flag to allow empty strings. The StringLength annotation provides parameters for a maximum length and a minimum length. The RegularExpression annotation provides a parameter for the Regex match pattern. The Range annotation provides a lower limit and an upper limit parameter (both of the double numeric type, but able to support other data types). A Range annotation of DateTime type is shown on AnniversaryDate in Listing 2 (opposite page). Listing 1. The Index() and Edit() Methods for the Customer Controller Dim DBContext As New Database1DataContext Figure 2. Create a strongly typed List view for the customer Index action. updating; see the sample application online for the remaining controller methods. To force the application to start with the Customer List page, add the statement Return RedirectToAction(“Index”, “Customer”) as the only statement in the Index method of the HomeController.vb file. For a production application, it would be appropriate at this point to clean up the Views by removing the prompt for the CustomerId field (it’s automatically generated by the database), change the MarketingOptIn field to a checkbox and generally modify the Views to be more visually attractive. For our purposes, what we have now is sufficient to proceed to the discussion of validation with data annotations. Why Data Annotations? Data validation rightfully should be the concern of the Model. Unfortunately, the form data resides with the View. The ModelState property of the controller tracks errors to populate the next view. This makes data validation in ASP.NET MVC 1 particularly challenging. A quick look at the “Validating with a Service Layer” tutorial (tinyurl.com/29f9ld5) shows just how involved this can get. DataAnnotations introduced in ASP.NET MVC 2 greatly simplify the task of validating the form input by using attributes. They also reduce code and ease application maintenance. DataAnnotations have the nice feature of automatically generating client-side JavaScript validations for the four built-in validation attributes. If the standard validators don’t meet your needs, you can create custom validations and implement a wide variety of validation actions such as a database lookup, a Web service call, cross-field validations and so on. Standard Data Annotations Data Annotations are attributes that can be applied to the class properties of the objects that are represented in the Web form, 30 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com ' GET: /Customer Function Index() As ActionResult Dim customers As List(Of Customer) = DBContext.Customers.ToList() Return View(customers) End Function ' GET: /Customer/Edit/5 Function Edit(ByVal id As Integer) As ActionResult Dim CustomerRecord As Customer = (From item In DBContext.Customers Where item.CustomerId = id Select item).SingleOrDefault If (IsNothing(CustomerRecord)) Then _ Return View("CustomerNotFound") Return View(CustomerRecord) End Function ' POST: /Customer/Edit/5 <HttpPost()> _ Function Edit( ByVal id As Integer, ByVal CustomerData As Customer) As ActionResult Dim CustomerRecord As Customer = Nothing Try CustomerRecord = (From item In DBContext.Customers Where item.CustomerId = id Select item).SingleOrDefault If (ModelState.IsValid) Then UpdateModel(CustomerRecord) DBContext.SubmitChanges() Return RedirectToAction("Index", "Home") Else Return View(CustomerRecord) End If Catch ex As Exception ModelState.AddModelError("GeneralError", "Error Updating Database: “ & ex.Message) Return View() End Try End Function You may put multiple validation attributes on a single data field. The validations occur in the following order: Required, Custom Validation Attribute, StringLength, Range and, finally, RegularExpression. You can’t directly annotate the customer table in the DataClasses1.designer.vb file as produced by the LINQ to SQL design surface because it would be overwritten by any subsequent change to the designer. The solution is to create a “buddy” class called CustomerMetaData, which has public properties with the same field names. You can now put data annotation validators on these properties. To relate this new class back to Customer, create a partial customer class and decorate it with a MetadataType attribute of type CustomerMetaData, as shown in Listing 2. Right-click the Models folder and add a new class named DataAnnotations.vb to hold the data annotations for all of your tables. Replace the default code with the code as shown in Listing 2. The data type of each property in CustomerMetaData is ignored; we express the data type as Object for consistency and to avoid confusion if the underlying type changes. If a field doesn’t need validation, it doesn’t need to appear in the CustomerMetaData class. Additional MetadataType classes can be defined for other tables in the database in a similar fashion. With these changes, error messages are shown after entering intentionally incorrect responses on the Create Customer form, as shown in Figure 3. The ModelState.IsValid method is false when any validations fail and should always be checked as shown in the Edit method of Listing 1. For a more responsive UI, client-side JavaScript validations can be enabled in a view with a single line of HTML markup and the inclusion of three script tags. Add the line below just before the Html.BeginForm() tag in the view: <% Html.EnableClientValidation()%> Then add the following three script tags to the end of the View. An easy way to do this is to drag them over from the Scripts folder into the View markup: ASP.NET MVC 2 { ON VB } Figure 3. Validation errors from the standard data annotations. custom JavaScript as a validation rule and associate it with its server-side equivalent. Server-Side Custom Data Annotation The code in Listing 3 is added just before the last line of Listing 2, after the CreditLimit property. In Listing 3, the AnniversaryDate property has been extended with our custom WithinDays() validator in place of the Range() validator. This custom validator inherits from the ValidationAttribute class and overrides the IsValid() method. This is the place where you code your custom <!-- Drag and drop these here from the Scripts folder of the Solution Explorer --> <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script> Custom Data Annotations Professional-grade Web forms may require more advanced validation than what’s available from the standard validators. Custom validators can be defined server-side and optionally client-side with custom JavaScript. An appropriate use of custom validators would be to overcome the limitation that attribute parameters must be constants. To perform a validation with a dynamic range of values, we must create a custom validator. The custom validator WithinDays, which replaces the Range attribute, ensures the AnniversaryDate is within 30 days of the current date. This is shown in Listing 3 (p. 32). More complex validators are certainly possible but this will suffice as an example. Creating a custom validator for both server-side and client-side consists essentially of three steps. First, create a class that inherits from ValidationAttribute to define the server-side validation by overriding the IsValid() function. Second, create the JavaScript to perform the validation in the browser. Third, create a class that inherits from DataAnnotationsModelValidator to identify the Listing 2. Customer Fields Modified with the Standard Data Annotation Validators Imports System.ComponentModel Imports System.ComponentModel.DataAnnotations <MetadataType(GetType(CustomerMetaData))> Partial Public Class Customer End Class Public Class CustomerMetaData <Required(ErrorMessage:="Name is Required")> <StringLength(25)> <RegularExpression("^[A-Za-z\-\.\' ]+$", ErrorMessage:= "Only letters, hyphen, apostrophe and period are allowed")> Public Property Name As Object <StringLength(50, ErrorMessage:= "Email Must Be No Longer than 50 Characters")> Public Property Email As Object <Range(100, 1000)> Public Property CreditLimit As Object <DisplayName("Anniversary Date")> <Required()> <Range(GetType(DateTime), "01/01/2000", "12/31/2010")> <DisplayFormat(DataFormatString:="{0:d}", ApplyFormatInEditMode:=True)> Public Property AnniversaryDate As Object End Class VisualStudioMagazine.com · September 2010 · VISUAL STUDIO MAGAZINE 31 </Language Lab> { ON VB } Listing 3. Server-Side Custom Validator for WithinDays() ASP.NET MVC 2 <DisplayName("Anniversary Date")> <Required()> '<Range(GetType(DateTime), "01/01/2000", "12/31/2010")> <WithinDays(PriorDays:=-30, SubsequentDays:=30, ErrorMessage:= "Date Must be Within 30 Days")> <DisplayFormat(DataFormatString:="{0:d}", ApplyFormatInEditMode:=True)> Public Property AnniversaryDate As Object End Class Public Class WithinDaysAttribute Inherits ValidationAttribute Public Property PriorDays As Integer Public Property SubsequentDays As Integer Private ParmDate As DateTime Public Overrides Function IsValid(ByVal value As Object) As Boolean If IsNothing(value) Then _ Return False If (DateTime.TryParse(value.ToString(), ParmDate) = False) Then Return False Dim WithinRange As Boolean = (ParmDate >= DateTime.Now.AddDays(PriorDays)) And (ParmDate <= DateTime.Now.AddDays(SubsequentDays)) Return WithinRange End Function End Class business-validation rules and return true if the field meets the requirements to be considered valid. In addition, the DisplayName attribute has been added for a slightly more attractive error message and the DisplayFormat attribute has been added to suppress the display of the time portion of the Anniversary Date. You’ll need to change the HTML markup for the Anniversary Date from TextBoxFor to EditorFor in the View for it to honor the DisplayFormat attribute, as shown here: <%: Html.EditorFor(Function(model) model.AnniversaryDate, String.Format("{0:g}", Model.AnniversaryDate))%> Client-Side Custom Data Annotation The custom JavaScript to perform the WithinDays validation in the client browser is shown in Listing 4. The code is assigned as a member of Sys.Mvc.ValidatorRegistry.validators, identified by withindays. It accepts a single parameter of type ModelClientValidationRule named “rule,” which contains the attribute parameters defined in the WithinDaysValidator class shown in Listing 5 (opposite page), and provides a mechanism for returning an error message if appropriate. Now we’re ready to add a WithinDaysValidator class at the end of the DataAnnotations.vb file, as seen in Listing 5. This class identifies the custom JavaScript as a validation rule and associates it with its server-side equivalent. Finally, the custom attribute needs to be registered in the Global. asax as a member of the DataAnnotationsModelValidatorProvider, 32 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com as shown by the last statement of the Application_Start() method of Listing 6 (opposite page). Go ahead and build the project and run it to test out the new custom validator; check out the client-side validation. Note that the date validator expects input in the format of mm/dd/yyyy. As soon as you tab out of a field, the validator is instantly called and you’ll see an error message. When you go back to the field, it validates on every keyup event. It’s worthwhile to note that the client-side validations don’t have to be an exact replica of the server validations. A good rule of thumb is to treat client validations as a quick check—a first line of defense. Then, when the user posts the form, more complete server-side validations can be put in place. Also note that client validations are just a convenience to the user, and shouldn’t be trusted. It’s the server validations that have the final say on the veracity of the data. Room for Improvement ASP.NET MVC is still a young and evolving Web applicationdevelopment platform. While preparing this article, we identified a few issues of which you should be aware: Listing 4. JavaScript to Perform WithinDays Validation in the Client Browser <script type="text/javascript"> Sys.Mvc.ValidatorRegistry.validators["withindays"] = function (rule) { // convert prior and subsequent parameters to // milliseconds(multiply by 86400000). var prior = rule.ValidationParameters["prior"] * 86400000; var subsequent = (rule.ValidationParameters["subsequent"] + 1) * 86400000; // Today’s date minus the time component var today = Date.parse((new Date()).toDateString()); var priorDateValue = today + prior; // prior is // already negative var subsequentDateValue = today + subsequent; // we return the function that // actually does the validation return function (value, context) { //expected date format: mm/dd/yy or mm/dd/yyyy var mdy = value.split("/"); var mm = parseInt(mdy[0]) - 1; // Note month is zero-based var dd = parseInt(mdy[1]); var yy = parseInt(mdy[2]); yy = yy < 30 ? yy + 2000 : yy; // need to make Y2K behavior // conform with .NET // Basic validation for day & month because // JS Date function allows higher/lower values // Yes, I know Feb has 29 days only during // leap year ... like I said, basic validation. if (mm < 12 && dd <= [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mm]) { var inDate = new Date(yy, mm, dd); var inDatevalue = inDate.valueOf(); if (inDatevalue >= priorDateValue && inDatevalue < subsequentDateValue) return true; } return rule.ErrorMessage; }; }; </script> { ON VB } Public Class WithinDaysValidator Inherits DataAnnotationsModelValidator(Of WithinDaysAttribute) Private _priorDays As Integer Private _subsequentDays As Integer Private _message As String Public Sub New(ByVal metadata As ModelMetadata, ByVal context As ControllerContext, ByVal attribute As WithinDaysAttribute) MyBase.New(metadata, context, attribute) _message = attribute.ErrorMessage _priorDays = attribute.PriorDays _subsequentDays = attribute.SubsequentDays End Sub Public Overrides Function GetClientValidationRules() _ As IEnumerable(Of System.Web.Mvc.ModelClientValidationRule) Dim Rule As New ModelClientValidationRule _ With {.ErrorMessage = _message, .ValidationType = "withindays"} Rule.ValidationParameters.Add("prior", _priorDays) Rule.ValidationParameters.Add("subsequent", _subsequentDays) Dim ModelClientValidationRule() = {Rule} Return ModelClientValidationRule End Function End Class 1. The RegularExpression attribute has limitations. RegularExpression pattern-matching options such as ignorecase are absent from the implementation. These can be specified inside a parenthesized group as a modifier; however, client-side JavaScript (ECMAScript) doesn’t support them, therefore they don’t translate well if you want to do client-side validations. So, if you need an ECMAScript-incompatible regular expression and have client validation enabled, you’ll need to create a custom validator. 2. The DisplayFormat attribute doesn’t emit the correct helper methods in the generated views. You’ll have to manually change the helper method to use EditorFor templates. 3. The Range attribute for Date type doesn’t work with client-side validation. A custom validator such as the one we created may be a better solution, but it does require additional coding. 4. If you override the default error message in a custom validator, the error message doesn’t propagate into the client-side validations. Only an explicitly specified error message parameter in the attribute propagates. 5. Putting the StringLength attribute on a field that’s associated with an underlying numeric data type gives an InvalidCastException error. 6. The default validators don’t allow for non-string literal error messages. 7. If a validation attribute is applied to a collection type, you can only apply the exact same validation rules to each item of the collection. The ASP.NET MVC 3.0 preview is already out and has many nice features and additions. Hopefully, it will address some of these issues in its final release. In this article we saw how quickly you can create a fully functional CRUD Web application using ASP.NET MVC 2. Version 2 introduces data annotations, which provide a non-procedural Listing 6. Registering the Custom Attribute in Global.asax Sub Application_Start() AreaRegistration.RegisterAllAreas() RegisterRoutes(RouteTable.Routes) DataAnnotationsModelValidatorProvider.RegisterAdapter( GetType(WithinDaysAttribute), GetType(WithinDaysValidator)) End Sub way to add common validations. Standard data annotations can provide commonly used declarative validation on HTML form fields. Custom data annotations can be created to provide richer validation rules for almost any needed rule. VSM Joe Kunk ([email protected]) is a Microsoft MVP in Visual Basic, three-time president of the Greater Lansing User Group for .NET and senior developer for A. J. Boggs & Company of East Lansing, Mich. He has been developing software for more than 30 years and has worked in the education, government, financial and manufacturing industries. Vijay Jagdale ([email protected]) has been developing software and leading software teams for more than 20 years. Jagdale is an IT manager with the Michigan Department of Technology, Management and Budget (DTMB), a regional conference speaker, and board member of the Greater Lansing User Group for .NET. GO ONLINE Go to VisualStudioMagazine.com/Kunk0910 to read and download sample code for this article. ASP.NET MVC 2 Listing 5. WithinDaysValidator Class to Define the Custom Client Validation Rule </Language Lab> { AS K KATHLEEN } Tips for Debugging Your Code in Visual Studio 2010 Improvements in the latest Microsoft IDE and underused features in Visual Studio 2008 support common debugging strategies to help you write better code. VS 2010 Debugging Tools BY KATHLEEN DOLLARD Every developer should know how to use debugging tools to their fullest advantage. This month, I’ll give a lightning overview of debugging strategies and show you how Visual Studio 2010 supports them. Visual Studio 2008 debugging tools are underused, so I’ll cover new and existing features. I’m skipping the historical debugger in Visual Studio 2010 Ultimate—while it’s very powerful, it’s not available to many developers. I commonly see four debugging strategies: Help Please, Divide and Conquer, Wandering Minstrel and the Scientific Method. Divide and Conquer determines parts of the application that can be excluded from further consideration. The Wandering Minstrel explores with minimal planning; a debugging episode generally includes many approaches. For years, the Help Please strategy was secondary. Someone looked over your shoulder or you explained the problem and noticed the answer (even if you explained it to your dog). The Internet rocketed the Help Please strategy to front and center. At the same time, increasing quirks and bugs in the Microsoft .NET Framework and Visual Studio require programmers to be good Internet sleuths. The Scientific Method puts the other approaches in a formal context. Haphazard debugging works on simple bugs. With more difficult bugs, you’ll waste time performing meaningless trials, leaving holes in your exploration, staring at the screen hoping for inspiration and, worst of all, getting stuck on an incorrect theory of what’s wrong. I wrote about debugging with the Scientific Method years ago with Nancy Folsom, who introduced me to the concept. You gather theories—notions of what the problem might be—and perform a series of experiments with a clear goal for each experiment. The critical nuance is that you design your experiment to disprove your idea, or theory, of what’s wrong. Creating theories integrates other strategies: checking the value returned from a Web service (Divide and Conquer) or articulating a gut feel (Wandering Minstrel). The biggest change in my thinking about debugging in the past few years is the importance of intuition. Gathering theories sometimes involves stepping carefully through the possibilities, but more often relies on your intuition. Intuition is rooted in your knowledge, but unfortunately it encourages you to become infatuated with your expectations. The formality of the Scientific Method offsets this tendency. Experiments to prove your theory is false are a psychological release because you’re never wrong— your theory survives another test or your experiment succeeds. Perhaps more important than the psychology is the nature of 34 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com truth—it can rarely be proven. I’ll let you meditate on the philosophical aspects of science, truth and expectations. I’ll stick to the pragmatic implications of debugging. The key route to efficiency is minimizing time on invalid paths. Your goal is to articulate as many theories as possible, achieve a definitive failure on almost all of them as quickly as possible, rinse, lather and repeat. Until you fix the bug, experiments against your code could succeed for multiple reasons. But if it fails, it fails and you can quickly go on. Q: How does Visual Studio 2010 support debugging? A: Debugging features of Visual Studio allow you to do experiments with your code. You phrase theories in your mind—out loud if working with someone else—and with a record for complex nasty bugs. Then you look for the quickest way to disprove your idea—often the first one you think of. The job of Visual Studio is to make that easy, assuming you can reproduce the error on your machine. The two most important experiments to disprove invalid theories during debugging are whether a piece of code runs and the current state, or the current values of variables and fields. Breakpoints and tracepoints determine whether a particular line of code runs. It’s easy to forget about conditional breakpoints, hit counts and breakpoint filters. Once you’re interested in a piece of code, it’s nice to know how you got there. Visual Studio 2010 extends the call stack with a parallel thread-based call stack. Tracepoints are perhaps the most underused debugging feature. Since the beginning, programmers have done Printf or Console.Writeline debugging, but these mechanisms affect the code for everyone working on the project. Tracepoints are stored in your user files, and thus affect only your instance (assuming you don’t share the user files in source control). The tracepoint dialog explains the content you can include in tracepoints. You can record the value of any state visible to the code and display a half-dozen important system states such as the method name, calling method, thread or even the full call stack. The big changes to breakpoints and tracepoints in Visual Studio 2010 are that you can label, search, export and import. While I don’t think you’ll use the export/import feature often, the scenarios where you’ll use it are the tricky ones where you want to share part of your debugging process. The sad fact is that certain aspects of code are more problematic than others, and you can also export and save tracepoints and breakpoints for particular problem scenarios. Searching and labeling help you organize breakpoints. I tend to leave certain tracepoints and breakpoints in place during development in problematic locations. Labeling groups of related points allows you to search for them, then enable or disable them as a group. Each point can have multiple labels, thus appearing in multiple groups. Once you find an interesting location, you may want to step through code. It’s easy to forget about the “Step into specific,” “Step over properties and operators” and “Set next statement” options on the right-click context menu, or that you can navigate by double-clicking the call stack. Improved DataTips The second big aspect of questioning your code is checking the state. You have multiple routes—the immediate window, Watch Window and Locals Window. You also have DataTips, which are displayed when you hover over a variable. Starting with 2010, you can now pin the DataTips. As you hover, you’ll see a pin on the right side of the box. Clicking on it pins the DataTip, or you can right-click the tooltip and select Pin to Source. Once the DataTip is pinned, you’ll see a small vertical toolbar as you hover over the DataTip. The pin in this toolbar allows you to unpin the DataTip from the source code to create a floating DataTip. Pinned DataTips stay with the code and will scroll off screen as you scroll your code. Unpinned DataTips retain their relationship with the visual screen. These two types of DataTips are different colors and you can drag both types around with the mouse. The down-facing chevrons on the DataTips toolbar let you associate a comment with the DataTip. You can use this as a reminder of why you’re interested in the tip or a target value you wish to compare. You can remove DataTips individually or as a group using Remove DataTips and Remove All DataTips from file. You can copy the expression or value and later paste them somewhere interesting like a Watch Window. You can also edit values in place within a DataTip. Many of these special DataTip features are available through the context menu, which can be a little tricky to activate. Right-click on a portion of the DataTip other than the value, expression or comment; for example, you might click on the symbol category icon. But wait, there’s more … DataTips can contain more than one value. By adding expressions, a single floating or pinned DataTip can contain all of your DataTips for a particular context. Unfortunately, you can’t drag additional expressions onto the DataTip. If you enter a comment, it will appear once for the entire DataTip, allowing you to express why these values should be considered together. But wait, there’s still more … You’re solving a particular problem, or working in a problematic piece of code. You create a set of DataTips to explore this problem and you think it’s solved. Before you delete the DataTips, export them. Assuming you name and store them logically, you can import if you need to return to the problem. They’ll often give a clue to some of the theories you explored. You can also export DataTips if you need to pass the problem on to someone else. Unfortunately, this release does not yet offer a way to export a group of DataTips or a way to see the entire list of active DataTips. If you’re debugging a Windows Presentation Foundation (WPF) application, Visual Studio 2010 supplies a special DataTip visualizer. After the page is constructed, with the DataTip displayed, click the magnifying glass. Figure 1 shows the visualizer for a simple form with a ListBox and Button. You can see the full visual tree on the left, values of the currently highlighted element on the right and a rendering of the elements at the bottom-left. Another trick for WPF is to supply specific trace levels to individual controls. If FirstName doesn’t exist on the DataContext, you’ll get a single error message from commonly used XAML: <TextBox Text="{Binding Path=FirstName}" /> Figure 1. The WPF Visualizer is a tremendous step forward in understanding the Visual Tree in your WPF applications and quickly exploring settings on each part. The visualizer won’t give full results until the tree is completed; specifically, it won’t appear complete when accessed from the constructor. It provides in the Output Window: System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName' property not found on 'object' ''MainWindow' (Name='')'. BindingExpression:Path=FirstName; DataItem='MainWindow' (Name=''); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') You can specify a different level of tracing with the PresentationTraceSources attached property: <TextBox Text="{Binding Path=FirstName, diag:PresentationTraceSources.TraceLevel=High}" /> With the high level of tracing set, and the Tools/Options/ Debugging/OutputWindow/WPF Trace Settings set to Warning, you’ll see nearly a dozen warnings about this failed binding, as well as the error. Most programmers spend more time debugging than writing new code, but we spend the majority of our effort improving our development and workflow techniques. Spending time exploring the debugging features of Visual Studio and examining your habits will make you better at debugging. Q: How do I debug when I can’t reproduce the problem on my system? A: Debugging on a running system that you don’t control involves data-collection tools. The two main avenues are logging/tracing and capturing dumps. Visual Studio 2010 adds the capacity to open mini-dumps in Visual Studio. Tracing tools depend on the platform. Silverlight doesn’t include tracing APIs, so you’ll have to kludge together your own system or use a third-party tool such as Clog. I suggest you create a log class so you can control the output location and insert a standard tracing mechanism if a future version of Silverlight supports tracing. You can write output to a service that manages logs server-side, cache to isolated storage for later transmittal to the server, or possibly use the Internet Explorer 8 and Mozilla Firefox browser consoles. Depending on the audience for your application, there will be privacy issues regarding sending logs of client actions to your server without consent. The big changes to breakpoints and tracepoints in Visual Studio 2010 are that you can label, search, export and import. VisualStudioMagazine.com · September 2010 · VISUAL STUDIO MAGAZINE 35 VS 2010 Debugging Tools { ASK KATHLEEN } </Language Lab> VS 2010 Debugging Tools { ASK KATHLEEN } Event Tracing for Windows Within the CLR If you’re in the Microsoft .NET Framework, you can use built-in tracing features. The .NET Framework 1.0 introduced a set of static methods on the Trace and Debug classes. These static methods force all log information into a single set of listeners and allow filtering only on the verbosity of the output. The .NET Framework 2.0 introduced the TraceSource class. The .NET Framework 4 added Event Tracing for Windows (ETW) support within the CLR. CLR ETW support allows automatic access to information such as loader behavior that would otherwise be tricky to catch. The .NET Framework has a number of logging statements that appear in the ETW system. Each ETW keyword represents a handful of events, and you configure data collection by specifying the CLR provider and a set of keyword to a tool like LogMan. For example, imagine a Managed Extensibility Framework (MEF) application that failed on a user’s computer. The failure appears to the user as missing menu items, and you have little knowledge of the code. If you’re able to work with the user, you can ask them to run a batch file that begins ETW with the rather arcane log request: logman start clrevents -p {e13c0d23-ccbc-4e12-931b-d9cc2eee27e4} 0x8008 0x5 -ets -ct perf And another batch file to stop logging: logman stop clrevents –ets The parameter clrevents indicates the log file, which will have an .ETL extension. The GUID indicates the type of logging—in this case, CLR event logging via the CLR provider. The 8008 hexadecimal indicates the “keywords” that the event system will report. This is an odd use of the phrase “keywords”; each keyword is identified by a number, which is a flag within the 64-bit integer parameter. Each keyword defines a set of events to be reported. The second hex number is the verbosity—5 is verbose and 1 reports only exceptions. The .ETL output file is a binary-encoded file, which makes it smaller when the user sends it to you. Once you have the log in hand, you can get a readable version at the command line using: Tracerpt clrevents.etl This produces an .XML file of the events and a text summary. If you install the Windows Performance Toolkit as part of the Windows 7 SDK, you’ll also have access to XPerf for a graphical version of the .ETL file. The key differences between ETW and tracing through Trace or TraceSource are how much work you must do and how tailored the output is. ETW is in place and you merely need to activate it by starting capture. TraceSource requires that you write logging code into your application, but that code includes exactly the things important to your scenario. The TraceSource class offers more granular tracing than the static methods of the Trace class. You supply a name to each Listing 1. You can use the Managed Extensibility Framework (MEF) to create a provider that returns an existing TraceSource, creates or accesses one as a MEF part, or creates one through traditional means. I don’t like calling this a factory, because in most cases calls don’t create a new item. You can use a similar pattern in many other scenarios. [TraceSourceProvider()] public class TraceSourceProvider : ITraceSourceProvider { [ImportMany()] private IEnumerable<ITraceSource> sources = null; private IEnumerable<TraceSource> traceSources = null; public System.Diagnostics.TraceSource GetTraceSource(string traceSourceName) { if (traceSources == null) { traceSources = from x in sources select x as TraceSource; } var matches = from x in traceSources where x.Name == traceSourceName select x; if (matches.Count() > 0) { var ret = matches.FirstOrDefault() as TraceSource; return ret; } var traceSource = new TraceSource(traceSourceName); traceSources = traceSources.Union (new TraceSource[] {traceSource}); return traceSource; } instance and configure output based on the named instance. This isolates different types of information, such as validation or MEF issues. Because TraceSources are often treated as singletons, they’re a great use for MEF. (For more on MEF, see “Getting Current on MEF,” October 2009, and “Stable Composition in MEF,” November 2009.) In theory, you can either import the TraceSource or you can use a provider or factory. If you know only one TraceSource exists, you could just import it. However, that undermines the value of individual TraceSources, ties you to a specific set of TraceSources with unique interfaces, or is fragile. An MEF-based provider allows you to apply logic to the selection and build a robust system. If needed, the provider can do other work, such as converting types. Listing 1 shows a TraceSource provider, which uses a contract of one type but returns the value as a different type. This is helpful when you wish to isolate classes with a particular interface but use the result in a general manner coupled to the underlying class—especially important when retrofitting MEF in existing systems. You can download a sample application that shows this TraceSource in use. The key differences between ETW and tracing through Trace or TraceSource are how much work you must do and how tailored the output is. 36 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com { ASK KATHLEEN } The TraceSource could be exported either through a class derived from TraceSource or through an exported property. This provider is neutral about whether a specific TraceSource is available. If it doesn’t exist yet, the provider creates a new instance of the TraceSource class with the requested name and tracks it for future use. While this approach isolates the conditional creation, it’s a little messy in use, so you might want to create a helper method. A field for the provider is created at the class level: [Import] private ITraceSourceProvider _traceSourceProvider; And, when needed, the provider returns the TraceSource (MEFTraceSource is a string constant): _traceSourceProvider.GetTraceSource (TraceSourceNames.MEFTraceSource). TraceInformation("There were {0} parts composed", _container.Catalog.Parts.Count()); With or without MEF, TraceSources are a great tool. Adding TraceSource statements to your application during development will give you tools to solve problems that occur later. Until needed, tracing is turned off. It won’t present a performance problem when turned off, unless there are adjacent, expensive logic statements. If you can redeploy your application to the problem situation, you can add tracing during debugging. Q: I have a DataForm on a user control on a tab in a user control. After I display a child window, the DataForm appears disabled. What do you think is going on? A: There are a couple of reasons this can happen. If you set the DialogResult and also call Close (generally setting the result inside the ChildWindow and calling Close from outside), the ChildWindow gets confused and leaves the underlying visuals disabled. It sounds like you’ve encountered a different problem when the DataForm doesn’t correctly re-enable itself. This is a bug that you can work around by altering the DataForm or issuing an explicit BeginEdit after the ChildWindow closes. The second approach works if the user expects to be editing the otherwise grayed-out fields. I found the more involved fix of changing the DataForm on Stefan Olson’s blog (tinyurl.com/2g4vnff). The basic problem is that the DataForm doesn’t correctly reset its visual state. Derive a new class from the DataForm, add a handler for IsEnabledChanged and explicitly set the visual state: void wi_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e) { if (!IsEnabled) { VisualStateManager.GoToState(this, "Disabled", true); } else { VisualStateManager.GoToState(this, "Normal", true); } } This fix isn’t free. Deriving a new class changes the control you’re using. Theming works on the specific control, not its base classes—therefore the implicit styling associated with themes won’t work unless you update the theme. VSM Kathleen Dollard is the chief technologist for AppVenture (appventure.com). She’s been a Microsoft MVP for 11 years and is a member of the INETA Speaker’s Bureau. Dollard has worked extensively with application code generation and is the author of “Code Generation in Microsoft .NET” (Apress, 2004). She speaks at dozens of conferences and user groups each year, and is also active in the Northern Colorado .NET SIG, Denver Visual Studio User Group, Northern Colorado Architect’s Group and IASA Denver. SAVE $ WHEN 200 REGIS YOU T SEPTE ER BY MBER 15! LAS VEGAS • OCTOBER 18 - 20, 2010 We get it—web design is your world. That’s why Web Design World is bringing you the top minds in web design this October. Oh, and did we mention it’s in Vegas? NEW: Exclusive 1-on-1 Consulting Time! We’ve negotiated 20 minutes of individual face time with an expert who will review your website, answer questions and offer helpful tips. all you have to do is check the box when you register, and pick the area you’d like to focus on: • Mobility • Development • Design • Usability • eCommerce • Accessibility The best part? We’re not charging you one extra dime! It’s all part of your registration. There is one tiny catch: seating is limited, so it’s first come, first served! Don’t miss out on your chance for individual, one-on-one expert consulting - register early to save your spot! Register By September 15th to SAVE $200! Use Priority Code NQW6 WebDesignWorld.com Untitled-11 1 8/17/10 3:50 PM Advertising Sales East Matt Morollo VP, Publishing Phone: 508-532-1418 [email protected] West Chris Kourtoglou Regional Sales Manager Phone: 650-787-9515 [email protected] National Accounts Director William Smith Phone: 603-886-3466 [email protected] Microsoft Account Manager Danna Vedder Phone: 253-514-8015 dvedder@11 05media.com Director, Print Production Jenny Hernandez-Asandas Phone: 818-814-5289 Fax: 818-734-1528 [email protected] Production Coordinator Serena Barnes Phone: 818-814-5367 [email protected] [email protected] Ad Index ID Statement Advertiser 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 offices. Complimentary subscriptions are sent to qualifying subscribers. Annual subscription rates payable in U.S. funds for non-qualified subscribers are: U.S. $35.00, International $60.00. Annual digital subscription rates payable in U.S. funds for non-qualified subscribers are: U.S. $25.00, International $25.00. Subscription inquiries, back issue requests, and address changes: Mail to: Visual Studio Magazine, P.O. Box 2166, Skokie, IL 60076-7866, email [email protected] or call toll free (888) 7688759, fax number 847-763-9564. International calls 847-763-9135. POSTMASTER: Send address changes to Visual Studio Magazine, P.O. Box 2166, Skokie, IL 60076-7866. Canada Publications Mail Agreement No: 40612608. Return Undeliverable Canadian Addresses to Circulation Dept. or IMS/NJ. Attn: Returns, 310 Paterson Plank Road, Carlstadt, NJ 07072. Copyright Statment © Copyright 2010 by 1105 Media, Inc. All rights reserved. Printed in the U.S.A. Reproductions in whole or part prohibited except by written permission. Mail requests to “Permissions Editor,” c/o Visual Studio Magazine, 230 California St. Suite 302, San Francisco, CA 94111. Legal 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 contained herein is the reader’s sole responsibility. While the information has been reviewed for accuracy, there is no guarantee that the same or similar results may be achieved in all environments. Technical inaccuracies may result from printing errors and/or new developments in the industry. Page /n Software Inc. www.nsoftware.com 15 Aspose www.aspose.com C4 ceTe Software www.cete.com 17 dtSearch www.dtsearch.com 37 Ektron, inc. www.ektron.com 9 ESRI, Inc. www.esri.com 7 GrapeCity FarPoint www.fpoint.com Infragistics www.infragistics.com 12 A-B, C3 C2, 1, 21, 25, 27 LEAD Technologies, Inc. www.leadtools.com 5 Northwoods Software www.nwoods.com 33 Programmer’s Paradise www.programmersparadise.com 2 TechExcel, Inc. www.techexcel.com 22 VSLive! http://vslive.com/orlando 29 Web Design World http://webdesignworld.com 38 Editorial Index Add-in Express Ltd. add-in-express.com 9 Adobe Systems Inc. adobe.com 9, 10 Aspose aspose.com 10 PreEmptive Solutions LLC preemptive.com 11 Sleek Technologies Inc. 13, 14 Telerik telerik.com 13, 16 Corporate Address 11 Media 1105 92 9201 Oakdale Ave. Ste 101, Chatsworth, CA 91311 w www.1105media.com Media Kits M D Direct your Media Kit requests to Matt Morollo, VP Pu Publishing, 508-532-1418 (phone), 508-875-6622 (f (fax), [email protected] Reprints R For single article reprints (in minimum quantities of Fo 25 250-500), e-prints, plaques and posters contact: PA PARS International Ph Phone: 212-221-9595 EE-mail: [email protected] w www.magreprints.com/QuickQuote.asp List Rental L Media Kits Direct your Media Kit requests to Matt Morollo, VP Publishing, 508-532-1418 (phone), 508-875-6622 (fax), [email protected] This publication’s subscriber list, as well as other lists from 1105 Media, Inc., is available for rental. For more information, please contact our list manager, Merit Direct. Phone: 914-368-1000; E-mail: 1105media@ meritdirect.com; Web: www.meritdirect.com. GO TO VisualStudioMagazine.com to access the stories in this issue, plus read exclusive online-only content. VisualStudioMagazine.com · September 2010 · VISUAL STUDIO MAGAZINE 39 </Redmond Review> BY ANDREW J. BRUST Lauding LightSwitch I’ve said it before: the Microsoft .NET Framework is too complex. There are too many ways to build client applications in the .NET Framework, too many ways to build Web applications and too many data-access technologies to choose from. Even worse, there’s too much code to write, and the tooling for newer technologies, such as Windows Presentation Foundation (WPF) and Silverlight, represents a step backward in productivity, compared to the Windows Forms designer that debuted a little more than eight years ago and the Visual Basic 6 forms designer before it. A new product from Microsoft called Visual Studio LightSwitch could help reverse this regressive tide. Now in beta, it’s a development environment totally focused on data and data-centric applications. The apps consist of useful data query and maintenance screens, and building them in LightSwitch requires little or no code. LightSwitch can create SQL Server databases or work with existing databases, be they in SQL Server or just about any other database product. LightSwitch caters to business developers who need to get apps done. It understands the typical line-of-business app paradigms of search screens, record-creation screens and record-edit screens, and it supports typical business data types such as phone numbers and e-mail addresses, rather than just the primitive data types in databases and the CLR, such as integers and strings. LightSwitch generates modern UIs, which are configurable through a code-free design interface. As you change the layout of your screens, LightSwitch lets you preview them, with data loaded, in real time. And the UI help keeps coming: LightSwitch apps are skin-able and third parties can offer custom themes that make this capability extremely valuable. Extensibility is core to the product, as third parties can also offer custom controls, custom business data types and custom screen layouts. With custom controls and a largely code-free design environment, LightSwitch seems a lot like pre-.NET Framework Visual Basic. Sounds good to me: Visual Basic was a productive environment for business apps built by business developers. Honoring the Old, Enhancing the New LightSwitch gives us back that old productivity, but no one wants to go back to old technology and specialized runtimes. The good news: No one has to. LightSwitch projects are .NET Framework projects, and the code-behind can be written in VB.NET or C#. The LightSwitch IDE comprises special designers within Visual Studio, and LightSwitch solutions are manifested as Silverlight applications that can run in or out of browser. Applications built in LightSwitch use the Entity Framework and WCF RIA Services, and they can read from and write to SharePoint lists. The apps can be deployed to the desktop and use SQL Server, and can be easily redeployed to the cloud, running on Windows Azure and SQL Azure. Unifying these Microsoft technologies and lowering their barrier to entry is the LightSwitch value proposition, and I think it’s compelling. LightSwitch is not meant to displace conventional .NET Framework development, but rather to extend it to audiences that might otherwise go elsewhere. Microsoft is serving enterprise developers with an enterprise dev environment—and renewing its support for the productivity programmer market that made Redmond a dev tool leader in the first place. LightSwitch transcends the false choice between serving one constituency or the other. I should ask Microsoft, “What took you so long?” But at the moment I’ll just say, “Bravo!” Is LightSwitch a slam dunk? I may hope so, but there are people who don’t want the barrier to entry lowered, and they won’t like LightSwitch. Some people might be more receptive, but will regard LightSwitch as just a suite of screen-generating wizards inside Visual Studio. Others may complain that Microsoft is trying to streamline its development stack by adding yet more ways to build apps for it. And some may say all this is too little too late, and that PHP and Adobe AIR have already won the hearts and minds of productivity programmers. Those people may have a point, but LightSwitch does something PHP and AIR cannot—leverage the .NET Framework platform. PHP and AIR rely on runtimes that are less rich and, frankly, less robust than the .NET Framework. If Microsoft can wed streamlined productivity with the strong foundation of the .NET Framework, the results will be impressive. More importantly, LightSwitch could be part of a long-overdue turnaround for Redmond. Microsoft has spent the last decade courting complexity, shaping the .NET Framework into an enterprise-scalee difice; yet today we’re seeing a return to roots. As a developer who got his start on Visual Basic 17 years ago, I’d like to be the first to say, welcome back, Microsoft. VSM With custom controls and a largely code-free design environment, LightSwitch seems a lot like pre-.NET Framework Visual Basic. 40 VISUAL STUDIO MAGAZINE · September 2010 · VisualStudioMagazine.com Untitled-2 1 7/14/10 11:22 AM Untitled-1 1 7/14/10 10:08 AM