VisualStudioMagazine.com

IIDEDE EEVOLUTIONVOLUTION As Visual Studio 2010 takes new form, will your user experience be enhanced?

PLUS Build Web Parts with SharePoint Extensions Create Templates with XML Literals, WCF and LINQ Work with Managed Extensibility Framework APRIL 2009 Volume 19, No. 4 APRIL 2009 Volume Project8 3/17/09 12:39 PM Page 1

Be The Master OnAnyPlatform

VTC–Virtual Training Center for SharePoint

SharePoint is a trademark or a registered trademark of Corporation. DataParts is a registered trademark of Software FX, Inc. Other names are trademarks or registered trademarks of their respective owners. Project8 3/17/09 12:40 PM Page 2

Choose A Higher Power For DataVisualization To master the art of data visualization, you must seek out the leader. For nearly 20 years, Software FX has risen above all others by supplying top-of-the-line data visualization tools to enterprise developers working with diverse markets, platforms and environments. This wisdom has evolved into a vast body of products including best-of-breed data presentation solutions, virtual training for SharePoint, and the most powerful selection of data monitoring and analysis components. For a world of software that can raise your work to a higher level, depend on the source that’s clearly on top.

Our most popular product, Chart FX allows you to build charts, gauges and maps with additional vertical visualization functionality for business intelligence (OLAP), geographic data, financial technical analysis, and statistical studies and formulas. Recognized for the past 15 years as the innovator and industry leader in charting components, Chart FX delivers incomparable gallery options, aesthetics and data analysis features.

Grid FX was built specifically for Visual Studio developers to provide a powerful design-time experience right out of the box. Grid FX includes all Chart FX features, and uses AJAX to provide robust, run-time functionality in ASP.net applications. Dynamic controls for presentation aesthetics and analysis allow easy adaptation to existing applications, and specific tailoring to corporate brand guidelines.

PowerGadgets puts powerful IT monitoring on your desktop and in your data sidebar. IT professionals can now create gadgets that consume data from WMI, Exchange, SQL Server and even the Windows Registry. PowerGadgets does not require any development environments,servers or browsers to run real-time gadget components such as charts, gauges and maps.

Introducing our new products for SharePoint 2007

DataParts is a powerful new way to add interactive business intelligence to SharePoint portals. With DataParts, visualizing and analyzing data becomes remarkably easy – and code-free. DataParts includes our complete suite of advanced lists, card views, charts, digital panels and gauges as web parts that are easily configured for the type of data desired in just minutes.

With the VTC – Virtual Training Center – your IT and help desk personnel will no longer be overloaded with SharePoint questions and training tasks. VTC is a complete program of expertly produced, self-paced tutorial modules designed to empower every user and maximize the value of every SharePoint feature. VTC installs in minutes on your server, allowing instant on-demand access for everyone in your organization.

Visit SoftwareFX.com for interactive demos, free trial versions and more information about our latest products.

Data visualization for every need, every platform Project1 2/24/09 11:24 AM Page 1

Your best source for tools! ®

LEADTOOLS Document dtSearch Engine for Win & .NET VMware Imaging v 16: Add dtSearch‘s “blazing speeds” Lab Automation by LEAD Technologies (CRN Test Center) searching and New Bundle file format support 64-bit The VMware Lab Automation bundle LEADTOOLS Document Imaging has every Version! component you need to develop powerful • dozens of full-text and fielded helps IT administrators consolidate lab image-enabled business applications including data search options infrastructure, reduce storage costs and specialized bi-tonal image display and • file parsers/converters for hit-highlighted eliminate time-consuming provisioning processing, document clean up, high-speed display of all popular file types tasks. Lab users benefit from on-demand scanning, advanced compression (CCITT • Spider supports dynamic and static web data; access to system configurations while IT SAVE 15% remains in administrative control. off combined G3/G4, JBIG2, MRC, ABC) and more. highlights hits with links, images, etc. intact MSRPs • Multi-threaded OCR/ICR/OMR/ • API supports .NET, C++, Java, SQL and more; Includes VMware vCenter Lab Manager MICR/Barcodes (1D/2D) new .NET Spider API Single Server and VMware Infrastructure 3 for 8 CPUs, • Forms recognition/processing Paradise # and vCenter Server. Paradise # Paradise # • PDF and PDF/A “Bottom line: dtSearch manages a terabyte of D29 02101A07 V55 72101A01 L05 03201A01 • Annotation (Image Mark-up) text in a single index and returns results in $949.99 Special promotional pricing CALL I $ 99 • C/C++, .NET, WPF - Win32/64 less than a second.” —InfoWorld expires April 30, 2009. 2,007. programmers.com/lead programmers.com/dtsearch programmers.com/vmware Pragma Fortress SSH c-treeACE™ Professional TX Text Control 14 —SSH Server for Windows by FairCom Word Processing Components Best Seller! by Pragma Systems The c-treeACE database engine is a high performance TX Text Control is royalty-free, Contains Windows SSH & SFTP Servers. Certified database alternative proven by developers in mission robust and powerful word processing for Windows Server 2008. Works with PowerShell. critical enterprise systems, desktop deployments, and software in reusable component form. embedded devices for over 25 years. • Full-featured server with centralized • .NET WinForms control for VB.NET and C# & graphical management • Complete set of including ADO.NET, LINQ, • ActiveX for VB6, Delphi, VBScript/HTML, ASP C#, C/C++, ODBC, JDBC, VCL, and dbExpress • GSSAPI Kerberos & NTLM authentication • File formats DOCX, DOC, RTF, HTML, XML, TXT • Graphical productivity tools • Fastest SFTP & SCP file transfer Professional Edition • Simple deployment • PDF export without additional 3rd party • Supports over 1000 sessions tools or printer drivers Paradise # • No DBA or ongoing administration T79 02101A01 • Runs console applications & allows history • Nested tables, headers & footers, text • Low deployment licensing costs Paradise # scroll back within the same session frames, bullets, numbered lists, multiple $ 99 • Cross-platform support for all major platforms F01 0131 919. Paradise # • Runs in Windows 2008/2003/Vista/XP/2000 undo/redo, sections, merge fields including Windows, UNIX, Linux, and Mac OS X $ 99 P35 043X 711. • Ready-to-use toolbars and dialog boxes Download a demo today. $ 99 Make your applications faster, easier to deploy, 91. programmers.com/pragma and more affordable with c-treeACE. programmers.com/faircom programmers.com/theimagingsource FarPoint Spread Crystal Reports 2008 Enterprise Architect 7.1 for by SAP BusinessObjects Visualize, Document and The Best Grid is a Spreadsheet. Give your users Crystal Reports 2008 is a powerful, Control Your Software Project ® ® the look, feel, and power of , dynamic, actionable reporting solution that by Sparx Systems without needing Excel installed on their machines. helps you design, explore, visualize, and Enterprise Architect is a comprehensive, Join the professional developers around the deliver reports via the web or embedded in integrated UML 2.1 modeling suite world who consistently turn to FarPoint Spread enterprise applications. It enables end providing key benefits at each stage of to add powerful, extendable spreadsheet solu- users to consume reports with stunning system development. Enterprise Architect tions to their COM, ASP.NET, .NET, BizTalk Server visualizations, conduct on report business 7.1 supports UML, SysML, BPMN and and SharePoint Server applications. modeling, and execute decisions instantly other open standards to analyze, design, Corporate Edition from the report itself-reducing dependency • World’s #1 selling development spreadsheet test and construct reliable, well under- 1-4 Users on IT and developers. stood systems. Additional plug-ins are • Read/Write native Microsoft Excel Files Paradise # Paradise # also available for Zachman Framework, • Cross-sheet formula referencing C0N 11101A03 Paradise # MODAF, DoDAF and TOGAF, and to SP6 0001 • Fully extensible models F02 01101A01 $462.99 integrate with Eclipse and Visual Studio $ 99 • Royalty-free, run-time free 182. $936.99 2005/2008. programmers.com/farpoint programmers.com/sap programmers.com/sparxsystems

SANmelody Kit v2.0 Orion Network Virtual Iron Extended by Datacore Performance Monitor Enterprise Edition DataCore SANmelody overcomes the high by Solarwinds by Virtual Iron cost barrier and complexity of traditional Orion Network Performance Monitor is a Virtual Iron Extended Enterprise Edition SAN storage. SANmelody converts standard comprehensive fault and network performance provides the most advanced server Intel/AMD servers, blades or virtual machines management platform that scales with the virtualization and virtual infrastructure (VMs) into fully capable storage servers that rapid growth of your network and expands management capabilities available at virtualize disks and serve them over existing with your network management needs. a fraction of the cost. networks to application servers. They are simple It offers out-of-the-box network-centric views • Unlimited virtual servers to operate, take only minutes to install, and that are designed to deliver the critical let you cost-effectively optimize, manage and information network engineers need. • Virtual SMP protect data storage and disk space. Orion is the easiest product of its • Local, iSCSI, FC storage Paradise # Paradise # kind to use and maintain, meaning you • VLAN S4A 08201E02 V87L01101A01 Paradise # will spend more time actually managing • LiveMigration networks, not supporting Orion NPM. $ 99 $ 99 DCA 01101A06 4,606. • LiveMaintenance 799. CALL • LiveRecovery programmers.com/datacore programmers.com/solarwinds programmers.com/virtualiron 800-445-7899 programmersparadise.com Prices subject to change. Not responsible for typographical errors. 0409vsm_TOC_003.v3 3/19/09 2:21 PM Page 3

April 2009// Volume//19 No. 4 Contents { FRAMEWORKS } 16

Michael Desmond, Editor in Chief, Visual Studio Magazine Going Large When Microsoft launched .NET Framework 3.0 back in November 2006, it heralded a rush of frameworks, foundations, pro- gramming models and languages that continues—unabated—to this day. .NET development has, in short, gone FEATURES large. As VSM Executive Editor Kathleen 16 IDE Evolution Richards reports in our cover story on the 2010 promises significant changes, from advanced WPF evolution of Visual Studio 2010 (see “IDE customization to support for a number of new and updated technologies. What Evolution,” p. 16), developers find them- does the update mean for developers, and how might Visual Studio 2010 set the selves confronted with a lot of hard deci- stage for Microsoft’s flagship IDE down the road? BY KATHLEEN RICHARDS sions. Decisions that have lasting implica- tions both for your applications and for 26 Build and Debug Web Parts with SharePoint Extensions your career. The SharePoint Extension CTP makes developing and testing Web Parts almost Today, Visual Studio supports develop- easy, provided you install it correctly. BY PETER VOGEL ment for Windows Presentation Foundation, Silverlight, ASP.NET, AJAX and DEPARTMENTS WinForms. And the next version extends 6 Letters to the Editor its reach in so many directions, it’s almost silly. There’s ASP.NET-friendly cloud 8 DevDisasters development for Windows Azure, freshly When Aptitude Leads to Futility BY ALEX PAPADIMOULIS integrated SharePoint tooling, and sup- port for parallel programming and func- 10 DevInsight DEVELOPER NEWS, REVIEWS, PRODUCT BRIEFS tional languages like F#. And I didn’t even Microsoft Revamps SQL Data Services Cloud Database PAGE 10 mention the . Product Review: Automation Design Canvas Boasts Advanced Web Testing PAGE 12 Consequently, developers need to Product Briefs: ERWin Data Modeler and ComponentOne LiveLinq PAGE 13 grasp the big picture even as they master the minutiae, which explains the changes 32 LANGUAGE LAB ON VB, C# CORNER, ASK KATHLEEN in this issue of Visual Studio Magazine. We’ve adopted a new design, a fresh On VB PAGE 32 approach and a broader mission. We’ll con- Use XML Literals, WCF and LINQ to create powerful templates that can be called from tinue to provide detailed tutorials. both client- and server-side code. BY STEELE PRICE Familiar columns including Ask Kathleen, C# Corner PAGE 40 C# Corner and On VB will appear in every There are multiple ways to solve every problem. Strive for code that communicates issue of VSM in our new Language Lab your intent and makes your meaning clear for every developer using your code. section (see p. 32). But you’ll also see a BY BILL WAGNER broader exploration of emerging tech- nologies and challenges facing develop- Ask Kathleen PAGE 42 ers—like the changes posed by Visual Learn how to free your application from dependencies and interchange Studio 2010. implementations using Managed Extensibility Framework. BY KATHLEEN DOLLARD So take your time. Check out the new DevDisasters department from the folks COLUMNS at The Daily WTF (p.8). Read Andrew 3 Frameworks BY MICHAEL DESMOND Brust’s Redmond Review column (p. 48). And get back to me with your thoughts 48 Redmond Review BY ANDREW BRUST on what we can do better—I’m at 47 Index of Advertisers [email protected]. COVER ILLUSTRATION BY RYAN ETTER RYAN BY ILLUSTRATION COVER

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 3 0409vsm_WTOC_004.v3 3/19/09 3:13 PM Page 4

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.

VISUALSTUDIOMAGAZINE.COM REDDEVNEWS.COM ADTMAG.COM

Practical ASP.NET RDN Express: The Unbearable Is SOA Dead? Create a Reporting Dashboard with Silverlightness of Being In an interview following her controversial WebPartZones (but Without WebParts): With version 3 revealed at Mix09, there blog post, Burton Group analyst Ann All you need to let your users customize was no shortage of opinions from readers, Thomas Manes explains her point was to their Web pages is the ability to create who took some time to share their get the word out to enterprise architects UserControls. BY PETER VOGEL thoughts about Silverlight’s evolution. that they need to temper expectations LOCATOR+ CODE: VS0904PV1 BY KATHLEEN RICHARDS when pitching enterprise application inte- LOCATOR+ CODE: VS0904RD1 gration projects to corporate sponsors or else they will be nixed. BY JOHN K. WATERS Classic VB Corner Windows WorkFlow 4.0 Promises LOCATOR+ CODE: VS0904AD1 Working with Multiple Monitors: Most VastImprovement of the time it doesn’t matter where the Developer speaking at VSLive! says user puts your application’s windows, but forthcoming WF will be the first truly Eclipse Launches Effort to Define every now and then you really need to usable version since it was released Standard Mobile Dev Tools know—or even decide this for yourself. more than two years ago. Pulsar is aimed at standardizing the way BY KARL E. PETERSON BY JOHN K. WATERS. software is developed for different LOCATOR+ CODE: VS0904KP1 LOCATOR+ CODE VS0904ED2 vendors’ mobile handsets using tools based on the open source framework. BY JOHN K. WATERS LOCATOR+ CODE: VS0904AD2 Inside VSTS Version 1.0 ASP.NET MVC Released Inside the TFS Databases: Get to know Microsoft released ASP.NET Model-View- the ins and outs of TfsWorkItemTracking Controller (MVC) version 1.0 at the MIX09 in the first part of this series covering the Open Source Project Gives Java conference in March. Will the ASP.NET MVC Devs a ‘Lift’ most useful aspects of the TFS database. succeed in advancing a design pattern BY JEFF LEVINSON The open source Lift Framework project for test-driven development of enterprise- aims to develop a Web application frame- LOCATOR+ CODE: VS0904JL1 scale Web applications? work that solves issues present in existing BY MICHAEL DESMOND approaches. BY JOHN K. WATERS LOCATOR+ CODE: VS0904RD3 LOCATOR+ CODE: VS0904AD3

VisualStudioMagazine.com RedDevNews.com ADTmag.com ILLUSTRATION FROM ISTOCKPHOTO FROM ILLUSTRATION

4 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com Project17 1/19/09 5:24 PM Page 1

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 (EDNSM), you have access to the complete ESRI geographic information system (GIS) software suite for developing and testing applications on every platform. Whether you’re a desktop, mobile, server, or Web developer, EDN provides the tools you need to quickly and cost-effectively integrate mapping and GIS into your applications.

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

Copyright © 2009 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. 0409vsm_Letters_6.v4 3/19/09 7:32 AM Page 6

VisualStudioMagazine.com April 2009 • Volume 19 • No. 4

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

Contributing Editors Andrew J. Brust, Ken Cox, John Cronan, Dan Fergus, John Gavilan, Roger Jennings, Don Kiely, Martin Kulov, Jeff Levinson, Bill McCarthy, John Charles Olamendy Turruellas, SharePoint Keith Pleas, Bill Wagner Art Staff Creative Director Scott Shultz Reflections Graphic Designer Erin Horlacher

Online/Digital Media VSM readers respond to the March 2009 cover story on the changing face of Editor, VisualStudio Becky Nagel Magazine.com SharePoint development. Executive Editor, New Media Michael Domingo Online News Editor Kurt Mackie The tools are abysmal. The best examples I’ve seen come out of Ted Pattison. His Associate Editor, Web Gladys Rama commentary in the SDK videos pretty much sums it up. He says that someday Web Producer Shane Lee Director, Web Development Rita Zurcher Microsoft will produce some great and wonderful tools, but until then you need to learn the hard way. Mike, California, posted online President Henry Allain Vice President, Publishing Matt N. Morollo The tools, quite frankly, stink. The documentation for those tools is also very, Director of Marketing Michele Imgrund very poor. The SharePoint developer SDK is full of examples that don’t work. Online Marketing Director Tracy S. Cook Many examples are trivial, too. The fact that you have to use the tools on the SharePoint server is just icing on the cake. Virtual PC is a real dog with a full

MOSS installation. On the other hand, so many of our clients are turned off President & Neal Vitale by the high cost of licensing SharePoint that they decide to go in another Chief Executive Officer Senior Vice President Richard Vitale direction instead. & Chief Financial Officer JP, Kansas, posted online Executive Vice President Michael J. Valenti President, 1105 Events Dick Blouin Good-bye Redmond Developer News Vice President, Finance Christopher M. Coates VSM sister publication RDN published its last print issue in February 2009. A & Administration reader shares her thoughts. Vice President, Digital Media, Abraham M. Langer Audience Development Vice President, Information Erik A. Lindgren I’m disappointed that RDN is going away. When it was created I thought it was Technology & Web Operations Vice President, Digital Media, Doug Mashkuri different and better than anything else for what it covered. The columns about Advertising technology, the interviews and DevDisasters, too, were all good to have. I work in Vice President, Carmel McDonagh a data warehouse development group so we are especially interested in SQL Attendee Marketing Server and data access and data presentation. Often I would tear a page out and Chairman of the Board Jeffrey S. Klein put it on my manager’s desk so he could read it and be aware, too. Visual Studio Magazine is OK, but it’s different. RDN will be missed. REACHING THE EDITORS Editors can be reached via e-mail, fax, telephone or mail. Laura Granstedt, Bridgeport, Conn. A list of editors and contact information is available at VisualStudioMagazine.com. E-mail: E-mail is routed to individuals’ desktops. Please use the following form: [email protected]. Do not include a middle name or middle initials. Telephone: The switchboard is open weekdays 8:30 a.m. to 5:30 p.m. Pacific Time. After 5:30 p.m. you will be directed Visual Studio Magazine wants to hear from you! Send us your thoughts to individual extensions. about recent stories, technology updates or whatever’s on your mind. San Francisco Office 415-814-0950; Fax 415-814-0961 E-mail us at [email protected] and be sure to include Irvine Office 949-265-1520; Fax 949-265-1528 your first and last name, city and state. Please note that letters may be Corporate Office 818-734-1520; Fax 818-734-1528 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 Visual Studio Magazine 1105 Media Inc. The opinions expressed within the articles and other contents herein do not necessarily express those of the publisher.

6 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com Project3 3/18/09 9:10 AM Page 1 0409vsm_DevDisasters_8-9.v6 3/19/09 8:01 AM Page 8

{ SOFTWARE DEVELOPMENT GONE WRONG } Coding Catastrophes

themselves. And who knows, we all a bit” in programming and took it upon might even enjoy a laugh or two himself to build the HR department’s sup- while we’re at it. plemental systems. So, welcome to the first A decade or so later, Rob’s supple- installment of DevDisasters mental applications were central to the in Visual Studio Magazine. business and the ERP system had faded This regular department, out. By the time Rob left, the HR depart- which has appeared in ment worked with an amalgamation of VSM’s sibling publication databases, VB5 applica- Redmond Developer tions and macro-powered Excel spread- News since 2007, will sheets, strewn across different worksta- offer readers a chance tions and servers. to learn the hard lessons At the heart of this “system” lay the without taking the central database. It held monthly snap- hard hits. shots of all 50,000-plus employees’ data going back about four years. Over that A Painful Legacy period of time, the database had grown to The fourth time will be the charm. an impressive 2 million records. And for an That’s what Martin F. told himself on Access database on a file share, that the first day of a new assignment. He meant a typical “Select and Group By” was the fourth consultant sent from his query took a good eight minutes. IT firm to work with the HR department at Pan Euro Investments (PEI), a major Diving into the HR-Access Pool Experience may be the best teacher, but European banking and insurance Robert’s first task was to correct a few failure too often is its bitter reward. After conglomerate. Apparently, the first con- bugs in the “provider importer.” It was an all, what software developer worth his salt sultant walked off the job. The second Excel-based “application” that PEI’s 100-plus hasn’t committed some code-bound atroci- ran. And the third sprinted like a bat out daughter companies would use each month. ty or embarrassed himself with an ill- of hell. After the appropriate data was filled in, the advised kludge? The thing is, good devel- “Just to warn you,” Martin’s new boss spreadsheet would generate a few .CSV files opers learn from these failures to become started, “I’ve been told that our database is and e-mail them to a manager in PEI’s HR better developers. a bit of a mess. Ever since Rob—the guy department. I should know. As the author of who built the system—left, it’s changed In turn, that HR manager would for- DevDisasters and founder of The Daily quite a few hands and has experienced a ward the e-mail to the appropriate subordi- WTF Web site (www.thedailywtf.com), I’ve few ‘growing pains’ over the year.” nates, who would then do the following: made it my personal mission to stand wit- Growing pains was a gross under- 1. Process every .CSV through an ness to the painful shortcomings of soft- statement. Back in the early ’90s, PEI Access-based data-verification program ware developers. The whole thing started purchased an incredibly inefficient and that output “Verified .CSVs” back in 2004, when I noticed how fre- unreliable enterprise resource planning 2. Consolidate all the verified files quently programmers tend to discuss and (ERP) system to help HR manage employ- into another Access database share anecdotes about the poorly written ees. Because the system lacked so many 3. Find and remove any duplicate code they encounter every day. It was clear features, the HR department had no employee records to me that developers could learn an awful choice but to supplement it with applica- 4. Export the data into “Duplicate lot by reading about some other guy’s ugly tions of its own. That’s where Rob came Verified .CSVs” and import it into temporary flameout, rather than experiencing it in. He was an HR specialist who “dabbled tables of the central database

8 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_DevDisasters_8-9.v6 3/19/09 8:01 AM Page 9

5. Perform the final checks and cor- Apparently, Frank showed good aptitude The pages were riddled with race con- rections against temporary tables and then and was asked back for a second interview. ditions and generally only supported one consolidate to master tables When Frank came back for round request at a time. The developers didn’t 6. Run the appropriate reports and two, he was given the grand tour. It was seem to know the difference between send PDF-formatted documents to appro- everything start-up dreams were made of: Cache, ViewState and Session objects, so priate managers at daughter companies posh decor, shiny new Macbooks every- they just used all three simultaneously This song and dance took where, an air-hockey table, free to “make things work.” As for the “helper two people a full week to catered meals and Aeron functions”—they were perhaps the accomplish. After send- chairs as far as the eye most unique take on .NET coding ing the reports to the The could see. After the Frank had ever seen. In one baffling 100-plus managers, developers interview, case, the developers created their own they set aside didn’t seem to know his future boss areValuesDifferent method to act as a three days for the difference between Derrick wrapper for object.Equals(): feedback and cor- Cache, ViewState and made Frank an rections from the offer he couldn’t public bool areValuesDifferent daughter compa- Session objects, so they refuse. (object x, object y) { nies, and then just used all three Frank’s first went back to step simultaneously to day consisted mostly ... snip ... one to repeat the “make things of introductions. process for the “final” work.” When he finally made it if (0 == x.GetType().FullName version. back to his desk, he could- .CompareTo("System.String")) n’t help but wonder about if (0 != ((string)x) Ol’ Teller some things. Things like, why would a .CompareTo((string)y)) Martin had little faith that the code power- Web-based software company with diff = true; ing this ridiculous process would make any 20 employees have only more sense than the process itself. Peering three developers on staff? And if (0 == x.GetType().FullName under the veneer of the ordinary-looking why would two of those developers be .CompareTo("System.Int64")) spreadsheet, Martin uncovered a writhing part-time interns? if (0 != ((long)x) heap of undocumented VBA code that The more he thought about it, .CompareTo((long)y)) made him shudder. the more he worried. Frank counted four dif- diff = true; When Martin completed the requested ferent program managers. What tasks at the bug fixes, his boss thanked him for the small company could possibly keep the New ... snip ... prompt turnaround. Then he quietly added: Product Introduction Manager or Geospatial } “Now, ahem, you just need to fix all of the Systems Program Manager busy all day? daughter companies’ importers.” “Did the company really need 10 As the lead developer later told Frank, As Martin begrudgingly edited each ‘manager’ level positions?” Frank asked “Well, this way, it only checks the value.” and every one of the 100 or so different himself. “Shouldn’t some of these people Frank took a few minutes to explain “provider importer” spreadsheets, he have software backgrounds?” the whole concept of “virtual” methods, and plotted the ways that he could tastefully But Frank shrugged his concerns off, how Equals() does exactly the same thing. flee like there was no tomorrow. And reasoning that this was the type of team His colleague shrugged his shoulders and who knew, maybe the fifth time would be needed to build a successful start-up. replied, “Hmm, I guess that would work, too.” the charm. The really good news came later that Wait … What? day, when Frank learned that the company Death by Aptitude Once Frank finally settled into his comfy would be hiring some new intern developers. Nothing screams sexy like an ad for a C# Aeron chair and fired up his dual-monitor Well, not just any interns, only the “most developer job at a well-funded start-up. In workstation, he was ready to learn the code. aptitudinal” that money could buy. VSM fact, when Frank’s recruiter presented the This, he figured, is where it would all come opportunity to him, Frank knew it would be together and make sense. He heeded his fel- Alex Papadimoulis is a managing partner at a long shot. After all, he had no commercial low developers’ warning that things “were a Inedo LLC and publisher of the Web site The software experience and had only limited little beta-ish” and dove right in. After all of Daily WTF (www.thedailywtf.com). He writes Web development experience. But he did two minutes, he wanted to jump back out. DevDisasters in every issue of VSM. know .NET pretty well, so he figured it’d be worth a try. Maybe his skills could translate to a Web-based software company. Tell Us Your Tale His first interview went surprisingly well. They asked a lot of “aptitude” ques- Each issue Alex Papadimoulis, publisher of the popular Web site The Daily WTF (thedailywtf.com), tions, as they were firm believers that recounts first-person tales of software development gone terribly wrong. Have you “experience can be gained and skills can be experienced the darker side of development? We want to publish your story. E-mail your tale to Executive Editor Kathleen Richards at [email protected] and put “DevDisasters” learned, but attitude never changes.” as the subject line.

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 9 0409vsm_DevInsight_10-13.v7 3/19/09 8:06 AM Page 10

DEVELOPER NEWS /// REVIEWS /// PRODUCTS

always the plan, it said it will no longer expose those capabilities by requiring the REST Web services interface. The move eliminates the Web services layer and exposes TDS to SQL

Data Services Data Server over the cloud. As a result, says Microsoft, developers will be able to move data-driven code developed in Microsoft’s T-SQL language for SQL Server over to SDS. “We were calling it SQL Server but it really was not similar to a SQL Server-type experience,” explains Niraj Matrani, senior product manager for SDS. “Customers preferred more with the traditional T-SQL-based support, so we decided to go in this direction.” Microsoft is suggesting that those who want to use REST-based pro- gramming for applications that do not require a relational database management system can use DEVELOPER NEWS the Azure table storage. “You can still access your rela- tional data (located on premises or in the cloud) via Microsoft Revamps SDS HTTP/REST using the ADO.NET Data Services framework,” Microsoft Senior Program Manager David Robinson wrote in a Cloud Database blog posting. BY JEFFREY SCHWARTZ SDS DOA After months of criticism that the test build of its cloud-based Indeed it was the similarity between Azure Tables for storage SQL Data Services (SDS) lacked the horsepower for enterprise- and SQL Server tables using the Entity Attribute Value (EAV) grade applications, Microsoft is scrapping the effort and moving model that may have helped render Microsoft’s first test build of to a pure relational model instead. SDS dead on arrival. “The two were virtually identical,” says con- Microsoft made the surprise move just one week before its sultant and Microsoft MVP Benjamin Day of Brookline, Mass.- annual MIX09 conference in Las Vegas last month. Ironically, The based Benjamin Day Consulting. company announced its cloud-based database offering at MIX08, The four-month test of SDS failed to meet the performance one year before. The test version of SDS that critics panned was expectations of enterprise developers such as OakLeaf Systems based on REST and SOAP Web services interfaces. Principal and VSM contributor Roger Jennings, who found it was unable to offer the scalability of the existing SQL Server. “They Eliminating Web Services offered some pseudo-relational features but they didn’t offer the Under the new plan, Microsoft will offer a pure relational data- ones that people really wanted,” Jennings explains. base in the cloud by exposing its Tabular Data Stream (TDS) It also became clear that developers weren’t going to rede- over-the-wire protocol for accessing SQL Server via its forthcom- velop their T-SQL application for SDS. “It highlights that chal- ing Azure Services Platform. lenge [that], as people transition to the cloud, they’re absolutely Microsoft will support traditional relational database capa- not going to accept two different programming models—one for bilities, including SQL queries and support for relational schema inside the firewall and one for outside the firewall,” says and stored procedures. While the company maintains that was Forrester Research Inc. analyst Jeffrey Hammond.

10 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com Project1 2/24/09 11:22 AM Page 1

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

Document Form Recognition & Processing Barcode

Mark-up DICOM Medical Multimedia

Develop your application with the same robust imaging technologies used by Microsoft, HP, Sony, Canon, Kodak, GE, Siemens, the US Air Force and Veterans Affairs Hospitals. LEADTOOLS provides developers easy access to decades of expertise in color, grayscale, document, medical, vector and multimedia imaging development. Install LEADTOOLS to eliminate months of research and programming time while maintaining high levels of quality, performance and functionality.

• Image Formats: All industry standards including TIFF, EXIF, •Medical Web Viewer Framework: Plug-in enabled PDF, JPEG/JPEG2000, DICOM, PCL, DWG and hundreds more. framework to quickly build high-quality, full-featured, •Image Compression: From standard JBIG, JBIG2, ABIC, web-based medical image delivery and viewer applications. JPEG and CCITT G3/G4 to LEAD’s specialized ABC, CMP and •Medical Image Viewer: High level display control with built- CMW compression. in tools for image mark-up, window level, measurement, zoom/ •Display Controls: Scroll, zoom, pan, magnify glass, pan, cine, and LUT manipulation. brightness/contrast/gamma, window level. •DICOM: Full support for all IOD classes and modalities defined •Image Processing: 200+ filters, transforms and color in the 2008 DICOM standard (including Encapsulated PDF/CDA conversion functions with extended grayscale (10 to 16-bit) and Raw Data). support. •DICOM Communications: Full support for DICOM •OCR/ICR/OMR: Full page or zonal multi-threaded messaging and secure communication enabling quick recognition with formatted output including PDF, DOC and implementation of any DICOM SCU and SCP services. TXT for Win32 and x64. •WPF (XAML): Viewer, Image List, Annotations, Transitions •Barcode: Read/write all industry standard 1D and 2D bar- and WIC Codecs. codes (DataMatrix, PDF417, MicroPDF417, QR Code and more). •AJAX Web Form Image controls for developing rich web •Forms Recognition and Processing: Automatically applications. identify forms and extract user filled data. •JPIP Client and Server components for interactive streaming •Document Cleanup/Preprocessing: Deskew, despeckle, of large images and associated image data using the minimum line and border removal, registration marks and more. possible bandwidth. •PDF and PDF/A: Read/write raster and text searchable •Scanning: TWAIN 2.0 and WIA (32 and 64-bit), auto-detect PDF files. optimum driver settings for high speed scanning. •Annotations: Interactive UI for document mark-up, •DVD: Play, create, convert and burn DVD images. redaction and image measurement (including support for •Multimedia: Capture, play, stream and convert MPEG, AVI, DICOM annotations). WMV, MP4, MP3, OGG, ISO, DVD and more. •Grayscale Imaging: Display and process signed/ unsigned 10-16 bit, 32 bit data.

LEADTOOLS SDKs feature LEAD’s iCompress™ Technologies. Free 60 Day Evaluation! www.leadtools.com/vsm 866-530-3399 0409vsm_DevInsight_10-13.v7 3/19/09 8:06 AM Page 12

REVIEW Developer Expectations Automation Design Canvas The new offering should be welcomed by developers, says Day: “It looks like it’s Boasts Advanced Web Testing going to make it extremely easy for you to BY KEN COX deploy existing code in the cloud.” The online video and the FAQ docu- But he cautions that until the test Automation Design Canvas (ADC) ment cover these issues adequately. release is available, it’s too early to say 1.1 from ArtOfTest Inc. is a high-end The Quick Start guide offers a how well it will perform compared to on- test tool for developing repeatable, fine overview of the tool’s basic fea- premises versions of SQL Server. “We’ll automated tests of Web applications. tures and environment, but it could have no idea what it will be until we run The generated tests execute on use some polishing and expert it,” he notes. ArtOfTest’s included WebAii—pro- review of what looked like syntax Jennings is skeptical. He pointed out nounced “Web-eye”—framework. errors in the code examples. that TDS was designed to run over high- The designer portion integrates Recording navigation, text speed LANs and that it’s not an Internet- seamlessly with Visual Studio 2008 input and mouse clicks are friendly protocol. But Matrani insists (though not the Express versions) to standard fare for any test tool, but Microsoft has already conducted exten- record, execute and analyze tests of ADC’s strength becomes apparent sive benchmarking and testing and per- browser-based content. both during and after recording Automated Testing Automated formance shouldn’t be a problem. “We operations. think it’s appropriate for what we are Getting Started Using Test Explorer you can doing and the direction we are talking it,” ADC installed flawlessly on a 64-bit reorder, edit and disable any step to he says. “As we get more early-adopter beta of Windows 7 running in a fine-tune the test sequence. I loved customers and we look at the type of Hyper-V virtual machine. The setup the Quick Test button for checking workloads they’re building, they’ll keep adds a template called WebAii to the an individual step without slogging modifying and tweaking our protocols so VS 2008 Test collection. through the whole test sequence. it’s more workload-friendly.” The proper configuration of The powerful Convert to Code func- Matrani adds that SDS will lend itself your test machine is essential. For tion turns a step into a highly read- well to CRM applications, content manage- the tooling to work properly, you able C# or VB function. This is not a ment, product lifecycle management, sup- must disable Internet Explorer’s scripting language. You’re coding ply chain and collaboration. But he Protection Mode, ease Firefox against strongly typed objects with acknowledges that it won’t initially be browser security settings and shut full IntelliSense and tooltip support. suited to data warehousing and OLTP. off User Access Control in Windows. WebAii’s property and method Day and Jennings also warn that rela- tional data has its performance limita- tions. “There are theoretical limits on how scalable you can make a relational data- base,” Day explains. One of the unanswered questions is that of cost. While Microsoft still hasn’t disclosed how it is pricing SDS, rival Amazon Web Services has already low- ered the bar. The company slashed the price of its EC2 service by offering those who sign one- or three-year commitments to usage-based pricing that ranges from 3 cents to 24 cents per hour, depending on configuration. That represents a 30 percent to 50 percent reduction, the company says. Microsoft says SDS with TDS support will be available for testing by mid-year and commercially available by the end of the year. DI

Automation Design Canvas integrates with Visual Studio 2008 to design and Jeffrey Schwartz ([email protected]) is run flexible tests of Web applications. Each test step remains a separate item Visual Studio Magazine’s news editor and the that you can tweak, re-order or turn into a .NET function. You might need to editor of ADTmag.com. add a slight pause for AJAX-enabled controls.

12 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_DevInsight_10-13.v7 3/19/09 8:06 AM Page 13

AUTOMATION DESIGN CANVAS 1.1

names are intuitive, resulting in recog- menu lets you set the expected result; for ArtOfTest Inc. www.artoftest.com nizable statements such as: example, a string of text or a visible 512-535-2428 image. This point, click and configure Price: $2,499 per developer machine; input_Text_Q.Wait.ForExists(1000); feature is very valuable and well- $199 per execute-only machine license designed. Quick Facts: A sophisticated Visual Rather than cluttering Web forms with Recording and playback is usually Studio 2008 plug-in for recording, coding and executing tests of a Web junky “asdfdadfdf”-type input, testers smooth and automatic, but the application using Internet Explorer or can store realistic values once in the soft- CascadingDropDown sample on the AJAX Firefox. ware’s convenient data table option. Control Toolkit site was an exception. It Pros: Easy to learn and use; When you point an HTML control’s Text required adding delays by hand. I suspected powerful recording and playback features; flexible editing of test steps; property to the built-in Data[] object, WebAii was trying to select an option exposes rich, strongly typed C# or VB WebAii loops through its data rows and before its XMLHttpRequest-fed value was objects inserts whatever is in the table. You can available inside the browser DOM. Cons: Pricey; AJAX controls may require also use external sources, such as a SQL ADC logs extensive results and a special attention Server database, to feed data-driven tests. summary report for each test run. The tool can even log a screenshot at any Smooth Design point in the process to help developers The purpose of most tests is to check for assess the results at the post-mortem designer workstation license and $199 for appropriate responses. To configure review stage. an execute-only machine license. DI screen reading in ADC, you use an over- ADC 1.1 and WebAii are chock-full

lay function that suspends record mode of impressive and useful features for test Ken Cox is a Canadian .NET programming Modeling Data while you highlight a screen object such developers. However, prepare for an writer and the author of “ASP.NET 3.5 for as a label or image. The overlay’s context enterprise-level price: $2,499 for a Dummies” (For Dummies, 2008).

PRODUCTS

ERWin Data Modeler Forrester Research Inc. analyst Jeffrey Hammond. “ERwin is 7.3 and LiveLinq probably the most traditional of the data modeling tools,” he notes. Other key providers include Embarcadero Technologies Erwin Data Modeler 7.3 Inc. and Sybase Inc., according to Forrester. IBM, Microsoft and With more complex data sources throughout the enterprise and Quest Software Inc. also are emerging providers of data demands to move beyond structured information, modeling tools management tools. are moving beyond their roots. For one thing, database developers can now find them in application lifecycle management suites. ERWIN DATA MODELER 7.3 Case in point is Erwin from CA Inc., one of the most widely used CA Inc. of the data-modeling tools. The new CA ERwin Data Modeler 7.3 can Price: $8,000 now be integrated with Visual Studio Team System 2008 and SQL www.ca.com 800-225-5224 Server 2008, among a number of other key data repositories includ- ing Teradata and IBM Corp.’s DB2 for its mainframe-based z/OS v9. The tight integration between ERwin and SQL Server allows LiveLinq Boosts Queries for all SQL Server database objects to be captured in ERwin data One of the key benefits of Microsoft LINQ is that it can cut down models for analysis, says CA partner Antonio Amorin, president of development time for data-driven applications. But for those Northbrook, Ill.-based Data Innovations. looking to optimize the speed of applications developed in LINQ and The new release of ERwin also boasts new reporting capabili- for dynamic views of data rendered in LINQ-based queries, ties via a bundled copy of BusinessObjects Crystal Reports, which ComponentOne LLC is readying a new tool called LiveLinq. Available provides graphical rendering in spreadsheets, and HTML. as a community technology preview in February and slated for “Our techie geeks love that because they can completely cus- release next month, LiveLinq is a new class library that the company tomize any report they want, when a model is published,” says says speeds up LINQ queries by indexing in memory. ComponentOne Donna Burbank, a senior principal product marketing manager at CA. claims “typical” performance boosts of 10 to 50 times. The new release also has a new option for data profiling, The live views will render data dynamically to users of apps thanks to a recent partnership with Exeros Inc., whose data profiler using LiveLinq libraries. Any developer familiar with LINQ should is now integrated into ERwin. The data profiling lets developers be able to use LiveLinq without training, says ComponentOne compare data distributed throughout disparate legacy systems, Product Manager Chris Meredith. DI which CA says will ease the process of identifying information such as customer data, and making sure it’s consistent with struc- LIVELINQ tural designs. This allows architects and those on implementation ComponentOne LLC teams to ensure data is modeled so it can be used in data marts, Price: Not disclosed yet warehouses and master-data management hubs. www.componentone.com 800-858-2739 ERwin, which recently celebrated its 20th anniversary, is 412-681-4343 among the leading suppliers of data modeling tools, says

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 13 Project3 3/19/09 9:08 AM Page 1 Project3 3/19/09 9:09 AM Page 2 0409vsm_F1VS_16-23.v7 3/19/09 12:55 PM Page 16

FEATURE VISUAL STUDIO 2010 ......

Is Microsoft enhancing your user experience in Visual Studio 2010 and beyond? BY KATHLEEN RICHARDS

The team in BuildingIDE 41 on the Redmond campus is working on ways to modernize the developer experi- ence for Microsoft’s third-largest application and flag- ship toolset. The Visual Studio platform architects face the same challenges as their developer customers: How EVOLUT to revitalize a pivotal legacy codebase as hardware sys- tems, Software plus Services (S+S) and new ways of building applications demand advancement. Visual Studio (VS) 2010—expected in beta WPF, according to many developers, provided limited around the Microsoft Tech·Ed timeframe (May 11-15, guidance and a lack of sufficient tooling. 2009)—will mark the start of a major remodeling of “It’s good to see Microsoft using WPF in one of the IDE, according to Microsoft, a process that will their core products, as it will surely drive the maturity of continue over several product cycles. WPF and related tools,”says Rockford Lhotka, principal In the upcoming release, the Developer Division technology evangelist at Minneapolis-based consultancy is taking a major leap of faith by “dogfooding” its Magenic Technologies Inc.“Every time Microsoft buys unproven graphics technology. The VS 2010 beta into its own technologies like this, we all benefit.” debuts a new code editor, user interface and shell built on Windows Presentation Foundation (WPF), the Dated and Confused .NET 3.x graphics subsystem that surfaced to mixed These bold moves come as VS’s architects attempt to reviews in Vista. roadmap a remodel of the IDE with investments in five “We’ve told developers how to make applications areas: extensibility beyond the core throughout the that are intuitive and exciting and modern looking for product, frugality with better dependency manage- their customers,”says Matt Carter, Microsoft’s Visual ment and resource allocations, connectivity with S+S, Studio group product manager.“What we’re trying to scalability to the tune of 10,000 projects in a solution; do is say,‘You deserve an environment that’s also very 50,000 files in a system and overall modernization. easy to use and intuitive and visually appealing, but “The 2008 product looks a lot like the 1998 also uses that visual appeal to really provide greater product and I don’t think that’s a good thing,”said insight into what you’re working on, how the different Visual Studio architect Rico Mariani in a Channel 9 parts of your code and your applications are related.’” interview at the Visual Studio Extensibility (VSX) A programming model to take advantage of conference in September. Vista’s new graphics subsystem, WPF was designed to “We’re doing a lot of work around scalability and modernize the user experience by enabling developers frugality in the IDE, so that you can afford to be mod- to code against a powerful framework that housed a ern,”he said.“We can pay for our WPF costs with sav- subset of DirectX 3D, animation, vector graphics, ings elsewhere. We don’t expect WPF to be free.” ClearType, declarative programming, data binding, Moving beyond “single-threaded app” perform- multimedia, styling and controls. The initial releases of ance in Visual Studio and a Model-View-Controller-type ETTER RYAN BY ILLUSTRATION

16 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_F1VS_16-23.v7 3/19/09 12:55 PM Page 17 ......

ION ......

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 17 Project1 1/21/09 11:14 AM Page 1 Project1 1/21/09 11:15 AM Page 2 0409vsm_F1VS_16-23.v7 3/19/09 12:55 PM Page 20

FEATURE VISUAL STUDIO 2010 ......

Microsoft, a Kirkland, Wash.-based research firm. You can look at methods in your code and get a pop-up with history of the modifications as it’s gone through development. You can also lever- age debugging information in Team Foundation Server, create specialized IntelliSense or adorn XML Documentation Comments. “Microsoft will offer a lot of these exten- sions,”Sanfilippo explains.“But it also opens up a market for that ecosystem. It’s an interesting competitive move: If there are features in com- peting dev environments, to put [Visual Studio] on par with what’s found on other toolsets.” At Tech·Ed in Barcelona, Zander showed a DevExpress add-on that lets you create thumb- nail code views, so it’s easy using WPF layers to pick a word and drill down in the Document Map Margin. The WPF shell lets developers undock window palettes and view code on multiple monitors. The new WPF-based Home Screen is also extensible through configuration and XAML files. “I could see extensions to this screen that architecture are among the roadmap’s talking points.“We have can display things like quick-facts,”says Sondre Bjellås, Microsoft plenty of threads but we don’t have a whole lot of concurrency,” technology leader for Capgemini in Oslo, Norway.“How much said Mariani.“And there’s a lot we could do if we separate what code you’ve checked in lately, how much time you spend testing, needs to be synchronous, what needs to interface with the user, how much time you spend documenting your methods and so which is where the SDK models begin. Get the state off of those forth. It could aggregate data from the Team System warehouse objects and separated and get separation between the con- and display it personalized for the individual developer.” trollers, which can initiate asynchronously and have high-quality The WPF redesign of the IDE is the part of VS 2010 that models in the background.” impresses Andrew Brust, chief of new technology at twentysix In VS 2010, developers can experience firsthand the begin- New York, the least.“What I saw looks more like a WPF port of the ning of the IDE’s evolution: improved code navigation, annota- 2008 IDE than a true redesign. I hope that Microsoft will consider tion and extensibility with the WPF-based shell; better perform- making more fundamental UI design changes to VS 2010 before ance and scalability for native code; and fundamental improve- release,”Brust says. ments in debugging and test-driven development. “We’re not embracing WPF because we want graphical ‘wow’—that wouldn’t be enough of a reason,”blogged VS architect Snazzy New UI Bling Mariani in late November.“What we want is flexibility and exten- Like many teams tasked with modernizing their apps, Microsoft sibility. For instance, it’s because the new editor is WPF-based that is revitalizing its legacy code base with a .NET presentation layer. we can, for reasonable engineering cost, offer the ability to add The UI changes appeared modest to several developers who wit- inline adornments, margins, even ‘heads up display’ style exten- nessed the first pubic unveiling at VSLive! in February. The UI sions. ... The best part is you won’t have to wait for us to do these Ribbon found in Vista and Office 2007 is not part of the redesign. things—you want profiler information overlaid on your text? No In the new VS 2010 interface, the menus and commands are problem. Go do it. Test coverage? Hot links to documentation? connected together in a shelf, so it’s easy to coordinate and find Online presence indicators based on e-mail names in comments? things or get the clutter out of the way, explains Carter. Microsoft You could do all these things.” has done design work around how color and negative space is used, The WPF-based editor is built on Microsoft’s new and removed some of the necessary gradients and line work there Managed Extensibility Framework, a .NET 4.0 library for so that the app is “cleaner and crisper than it has been in the past,” building extensible applications or discovering extensions. he explains. “It lets you focus on the work that you’re doing and MEF is available as a preview on CodePlex (see more about minimize the distractions from other parts of the environment.” MEF in this month’s Ask Kathleen, p. 42). Lhotka, who attended the VSLive! keynote delivered by “This whole modernizing thing, I think it’s a little tongue- Microsoft’s Visual Studio GM Jason Zander where the UI was in-cheek,”although it’s a good direction for Microsoft, says Jeff first shown, questions the “less clutter”argument.“While it’s nice Levinson, ALM practice lead at Kirkland, Wash.-based that Visual Studio is now WPF, it didn’t seem to me that the lay- Northwest Cadence Corp.“Companies have been writing add- out and dialogs were all that different from today,”Lhotka says. ins in Visual Studio for 16 years now. They can’t just go and In addition to a new look and feel, WPF allows you to extend dump what’s there. I think what they’re going to do is skin it for the application experience beyond what Microsoft delivers in the WPF, but I don’t know how full-featured WPF is going to be in IDE through third-party or self-written add-ins. terms of interoperability,”he says. WPF allows new extensibility to the source code editor that The current VSX architecture remains intact, according to in the past has been difficult to achieve, says Rob Sanfilippo, VS architect Mariani, but extensibility needs to be more uni- research vice president of developer platforms at Directions on form. Other questions remain: How can developers find and

20 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_F1VS_16-23.v7 3/19/09 12:55 PM Page 21

...... VISUAL STUDIO 2010 FEATURE

plug into the appropriate subsystem? How do you de-bug and ages that you need and the shell is much smaller.” He acknowl- update these components? How many extensions are feasible? edged that the ecosystem makes it hard to address a lot of these A new Extension Manager in VS 2010 lets developers access, issues in a single product cycle. search and download extensions from the VSX gallery, for exam- The platform wave continues in the new IDE, which will ple, from within Visual Studio without a required VSIP package support .NET 4.0,Windows 7, SharePoint 2007 and Microsoft on their machines. Office SharePoint Server, the Azure Services Platform and Perhaps the biggest question around WPF is how it will affect Silverlight 2. the IDE’s performance. Mariani, known as a “performance guy,”has “If you’re a Visual Studio developer, you already have the core acknowledged that there will be a penalty.“I’m expecting to take a knowledge to take advantage of all these great new innovations,” startup hit,” he said during a Channel9 interview, noting that around 300-msec would be acceptable. The new IDE will be targeted at devel- oper machines.“We’re going to down-level to XP in this version,”he explained, but to get the best experience, developers need to have a graphics accelerator (DirectX 9.0). From a practical standpoint, WPF also lets developers zoom in and out of code, undock palettes and view code and designer windows on multiple monitors. “It’s easier to work in differ- ent [but integrated] projects on differ- ent screens independently from your screen resolution,”says Daron Yöndem, a Microsoft regional director and INETA Turkey lead, who described the WPF support as “crazy good” in an e-mail. “I’m looking forward to the great days where we will be able to design our own Visual Studio interface with full templating.”

Crowded with Goodness Designing custom toolsets appeals to many developers, especially those who Powerful Imaging for .NET are accustomed to downloading only the modules they need, which is the Eclipse model. The promise of .NET, according to Microsoft, is that you can target so many applications—Windows, Office, Web, smartphone, cloud—with a single framework. And there’s the rub: How can a single IDE keep up? “It has been bloated for a number of years,” says Northwest Cadence’s Levinson. “For example, if you look at DotImage 7 – Affordable imaging toolkits for .NET. Team Explorer, which is just a Visual Runtime royalty-free deployment to the desktop, scalable Studio Shell, that’s 387MB to download and install … and if you look at some- licensing for servers, and 3 months of free gold support. thing like Eclipse, that thing is around 180MB. Then when you add everything Visit Atalasoft.com for web demos, video tutorials, and a free trial. else on, [Visual Studio] is almost 1GB.” Microsoft has heard the refrain for Call us toll free at 866-568-0129 years—Visual Studio needs to be a small- er footprint and take up less resources.“It takes a long time for certain operations to www.atalasoft.com occur, where it shouldn’t take that long,” says Levinson. “I would like to see them shrink it so that you only install the pack-

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 21 0409vsm_F1VS_16-23.v7 3/19/09 1:06 PM Page 22

FEATURE VISUAL STUDIO 2010 ......

says Microsoft’s Carter, pointing to recent developer feedback on the new SharePoint tooling. New in .NET Indeed, the new Server Explorer,VS 2010 Web Parts,Application Page Designers and user controls for SharePoint are highly anticipat- Framework 4.0 ed by many developers who have bemoaned the lack of tooling. This release is primarily focused on Windows 7. (VS 2008 Visual Studio 2010 will ship with a .NET Framework did not fully support Vista/.NET 3.x until Service Pack 1 was that has undergone major changes, most notably a released last summer.) VS 2010 and Visual C++ will offer new complete overhaul of Windows Workflow. Other note- class libraries for building Windows 7 apps (including UI ele- worthy additions include: ments like the Ribbon), bring back the MFC Class Wizard and support multitouch interfaces. ■ Managed Extensibility Framework (MEF): A new For Web developers, VS 2010 adds much-needed designers .NET 4.0 library for building extensible applications or and ASP.NET integration for Silverlight 2, tooling for ASP.NET discovering extensions. MEF is available as a preview MVC, advanced JavaScript IntelliSense, snippets in HTML and on CodePlex. One-Click Deployment. In addition to support for its bread-and-butter platforms, ■ Integration of .NET : A new library Microsoft is baking in tooling to support emerging application for data and task parallelism that includes the Task trends, namely cloud computing and parallel programming for Parallelism Library and declarative programming building applications that can take advantage of the performance of support via Parallel LINQ (PLINQ). multi-core systems.Visual Studio offers additional support for par- allel programming with debugging windows and profiling for ■ Support for the functional coding against the Parallel Extensions to .NET Framework, PLINQ, developed by Microsoft Research, F# and Microsoft’s the native Parallel Pattern Library and Concurrency Runtime. dynamic languages IronRuby and IronPython via the The Windows Azure Tools for Visual Studio, released out of new dynamic language runtime built on top of the band at the Professional Developers Conference (PDC) 2008 in . —K.. October for building, debugging and deploying cloud apps and services, is also integrated into the new IDE. Third-party products and frameworks are also finding their announced at PDC, fits into this strategy is unclear. The latest Oslo way into the IDE. Two notable inclusions in the VS 2010 tooling community technology preview was released in January. are Oracle database support with an optional database schema Improvements like the “no repro” debugging and the new provider developed by Quest Software Inc., and native JQuery. Test Lab Manager, a virtual machine environment that develop- “We had two paths we could follow there,”explains Carter.“We ers and testers can spin up and tear down, goes beyond quality, could create a JQuery functional equivalent or we could just use asserts Carter, to a team dynamic that can be fostered with the JQuery ourselves … and have it supported by Microsoft. It will new software. have all the IntelliSense that you’d expect from Visual Studio. If “My read is it will enable teams on tight deadlines and budgets you have a problem and call Microsoft, we’re here to support it.” to put out much higher quality code, because the effort required to find and fix the bugs will now be greatly reduced,” says Brust. Team Collaboration “Automation and all the recording features will really help here.” While developers and analysts describe VS 2010 outside of the VSTS 2010, which includes role-based client tools that incor- core platform support as somewhere between a point release and porate VS Professional and a license to TFS, is the first major full-fledged upgrade, Team System 2010 is a milestone release upgrade to the collaboration environment since its debut in that ratchets up the testing capabilities on par with third-party VS 2005. TFS will drop support for SQL Server 2005 as the back- testing products, and reinvents the architecture role to ensure end source control system and thus require an upgrade to best practices in the build process. SQL Server 2008. Team System also rolls up the former Developer “The 2010 release is kind of like an über release,” says edition into the Database edition, resulting in Architect, Tester and Levinson.“The functionality is much better. The introduction of Database roles in addition to Team Suite, which includes all of the hierarchical work items will make your life a lot easier. Plus, now aforementioned functionality in a single SKU. Microsoft is putting out a fully compatible, competitive profession- “We’re looking at quality across the board,” says Carter. al testing tool, which they haven’t really had before. If I had to cate- “When customers are ready to move up from doing unit testing gorize VSTS 2010 in a single word, I would say,‘Awesome!’” in Visual Studio 2010 Professional, to advanced stuff in Visual The new Architecture Edition is more of an app tool than a Studio Team System, that’s an easy transition. That’s really exciting systems tool, according to Levinson. It makes elements composable stuff … things like historical debugging, not only drive quality, they and discoverable so that you can now reverse engineer with help save time and resources for your team.” sequence diagrams or use the Architecture Explorer to drill down to see relationships. IDE support for UML is also added in 2010. VS Call to Action Professional has traditionally shipped with Visio, which offers UML With installable beta 1 bits expected next month, developers can stencils, but this is the first time Microsoft is supporting it in its own test drive the new editor and try out the code navigation. A products. How “Oslo,” the model-driven development tooling new Call Hierarchy feature provides inline information on code

22 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_F1VS_16-23.v7 3/19/09 1:06 PM Page 23

...... VISUAL STUDIO 2010 FEATURE

interaction. Highlight References bypasses the Find in Files feature to highlight reference information in context of selected code and GO ONLINE Quick Search provides insight into other code locations. Use this Locator+ code at VisualStudioMagazine.com to go Like VS 2008, the new IDE will support multitargeting of directly to these related resources. .NET Framework, and new with VS 2010, developers will also be able to “multitarget” both versions of the Common Language READ MORE Runtime (CLR2 and CLR4). Developers can also build client VS0904KR Read this article online. apps for multiple versions of Office, and deploy as a single package. Those with existing solutions based on C++ project systems will need to con- vert to MSBuild in VS 2010 to receive full IDE support. Although Microsoft has said it will provide migration tools, more information is needed. VS 2010/.NET 4.0 beta 2 is expected before the end of the year with a Go Live license, according to sources familiar with Microsoft’s plans. The tiered VS pricing structure, which debuted with VS 2005, isn’t changing, but professional developers may be better able to discern what functionality is available in what SKU/MSDN subscription based on their experience with this pricing model. Microsoft started a step-upgrade discount program last July that offers 30 percent off to developers who upgrade or move from competing products to VS Professional/MSDN Premium subscrip- tions or VSTS, both of which include the VS 2010 upgrade. Microsoft has declined to quantify how many step-upgrades have been sold. VS 2010 is the first release in what the Visual Studio platform architects describe as a multicycle evolution. The team is looking at a 64-bit version of the IDE for VS 11, but hasn’t committed to a tech- nology roadmap. “The reason that you do this is to make sure that the developer experience is as efficient as possible,” says Microsoft’s Carter. “So that’s really what we pivot around—to make sure that with Visual Studio 2008 and 2010 and beyond we deliver a great productive experience that is at once familiar to developers, but also lets them tap into these new capabilities.” The ultimate goal, according to Mariani, is: “How do you make it so that when a developer sits down, they feel like there’s nothing in his or her way between their idea and the execution?” VSM

Kathleen Richards ([email protected]) is executive editor of Visual Studio Magazine, and editor of RedDevNews.com.

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 23 Las Vegas • June 8-11 The Venetian Resort Hotel Casino Post event workshop on June 11 VSLive! Returns to Las Vegas

Attend the educational conference created by developers with deep coverage of existing and new technologies that you can use on the job today. Join your fellow developers for:

Over 45 sessions on WFP, WCF, LINQ, ASP.NET, Oslo, Azure, Team Foundation Server and more Cutting edge techniques needed to solve today’s development challenges Independent, real world information provided by industry experts Face to face time with speakers to ask your toughest questions

Visit www.vslive.com/09lv to view Take the complete agenda and register. advantage of our $99 Save up to $300 with early bird registration AND get a $50 hotel room Venetian gaming credit*. Register by April 29th. rate Use priority code NQ9V02

*Venetian gaming credit of $50 available to the fi rst 200 VSLive! registrants who book 2 or more nights at the Venetian.

009VSL_LV_VSM_adFinal.indd9VSL_LV_VSM_adFinal.indd Sec1:2Sec1:2 33/13/09/13/09 77:17:38:17:38 PMPM Project3 3/20/09 12:07 PM Page 1

Conference Day 1 • Monday, June 8 KEYNOTE: Team Foundation Server 2010 ASP.NET WPF WCF VM1 • Build Blazingly Fast ASP.NET Apps with 100% VM2 • Build a WPF Application in an Hour - Kenneth VM3 • Understanding Transactions in WCF - Clientside UI ExtJS - Peter Kellner Getz Michiel van Otegem VM4 • Introduction to the ASP.Net MVC Framework VM5 • Silverlight Design for Developers - Bill Wolff VM6 • WCF Extensibility In-Depth - Jesus Rodriguez - Gus Emery Lunch VM7 • ‘Real World’ ASP.Net MVC in 75 Minutes! VM8 • XAML Crash Course - Billy Hollis VM9 • Advanced Access Control with WCF - - Gus Emery Michiel van Otegem VM10 • Building High performance ASP.NET web VM11 • Silverlight Data Access Methods - Bill Wolff VM12 • WCF-WF Integration In-Depth with an Eye applications - Peter Kellner Towards Dublin - Jesus Rodriguez VM13 • Implementing Caching Technology as One VM14 • Deep Dive on the WPF/Silverlight Control Set VM15 • Windows Workfl ow and WCF Help Make Rung of the Scalability Ladder - Josef Finsel - Billy Hollis “Software + Services” a Reality - Michael Stiefel Welcome Reception

Conference Day 2 • Tuesday, June 9 KEYNOTE: Silverlight 3 .NET LINQ Agile/Design VT1 • Essential C# 4.0 - Mark Michaelis VT2 • Moving from LINQ to SQL to the Entity VT3 • How to Partition and Layer a Software Framework - Jim Wooley Application - Michael Stiefel VT4 • Writing Better Code: Using Visual Studio to VT5 • Investigating LINQ to XML - Kenneth Getz VT6 • Design Patterns for Mere Mortals Improve Your Code Base - Jason Bock - Philip Japikse Birds-of-a-Feather Lunch VT7 • Practical Parallelism - Rockford Lhotka VT8 • Leveling the LINQ to XML Playing Field with VT9 • Beyond Basic Unit Testing: Mocks, Stubs, User LINQ to XSD - Leonard Lobel Interfaces, and Refactoring for Testability - Benjamin Day VT10 • Exceptional Development: Dealing with VT11 • Super-Optimized Microsoft LINQ: Indexed VT12 • Achieving Balance - Rockford Lhotka Exceptions in .NET - Jason Bock Objects - Aaron Erickson VT13 • Self-Writing Programs - Using the Expressions VT14 • LINQ Kinq for the DBA Guy - Jim Wooley VT15 • Advanced Test Driven Development namespace in C# to “Write Code that Writes Code” - Philip Japikse - Aaron Erickson

Conference Day 3 • Wednesday, June 10 VW1 • Introduction to OSLO - Jon Flanders VW2 • Windows Azure: A New Era of Cloud VW3 • Get More Out of Team Build 2008 Computing - Aaron Skonnard - Brian Randell VW4 • Codename “Dublin”: Windows Application VW5 • Windows Azure: Is the Relational Database VW6 • Dispelling the Myths: Visual Studio Server - Aaron Skonnard Dead? - Benjamin Day Professional vs. Visual Studio Team System VSLive! Panel Discussion Lunch VW7 • Building Textual DSLs with Oslo VW8 • How to Work with Data in the Cloud: SQL Data VW9 • Customizing Team System Projects - Mark Michaelis Services Introduction - Josef Finsel - Brian Randell VW10 • M in Depth: The Underpinnings of Oslo VW11 • Windows Azure, an Enterprise Solution? VW12 • Better Together: Getting the Most Out of - Jon Flanders - Jerry Sevier Visual Studio Team System 2008 Development and Database Editions

Post-Conference Workshops • Thursday, June 11 VPC1 • A Day of Windows Azure - Aaron Skonnard VPC2 • SQL Server 2008 for Developers VPC3 • Build Distributed Apps in .NET 3.5 SP1 - Leonard Lobel - Rockford Lhotka

Should a speaker be unable to attend; all efforts will be made to replace the speaker/session with one of comparable value.

09VSL_LV_VSM_adFinal.indd Sec1:3 3/13/09 7:17:47 PM 0409vsm_How-To_26-32.v5 3/19/09 10:14 AM Page 26

HOW-TO SHAREPOINT EXTENSIONS

Build and Debug Web Parts with SharePoint Extensions Visual Studio 2008 Extensions for SharePoint makes developing and testing Web Parts almost easy, provided you install it correctly. BY PETER VOGEL

26 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_How-To_26-32.v5 3/19/09 10:14 AM Page 27

SHAREPOINT EXTENSIONS HOW-TO

One of the primary ways to extend SharePoint is to create Web Parts—the same Web Parts that are used in ASP.NET. But because SharePoint is an application platform built on top of .NET, creating a Web Part project and then debugging your Web Part inside SharePoint has always been different … and awkward. In addition to making life difficult for SharePoint developers, the troublesome process has discouraged ASP.NET developers from bringing their skills to SharePoint.

Microsoft released the Visual Studio 2008 Extensions for in the dialog. Once you’ve found the pool, right-click on it and Windows SharePoint Services 1.3 (VSeWSS) as a community select Properties. You’ll find the identity name on the Identity tab technology preview (CTP) in January 2009. The extensions sim- (on my machine, the identity was Network Service). The next step plify creating and debugging many kinds of SharePoint compo- is to add the Identity to the Administrators group: From your nents. The CTP version is feature-complete, though presumably computer’s Start menu, select Administrative Tools | Computer there are still some bugs left to remove (the final version is sched- Management and drill down through Local Users and Groups | uled for release in the spring). On the Visual Studio side, the CTP Group to select Administrators. Right-click on the group, select supports VS 2008 but not VS 2005. On the SharePoint side, the Add to Group and enter the name from the Identity tab. CTP supports both Windows SharePoint Services and Office After you make these changes, you can leave the Wizard to SharePoint Server. The Extensions package supports installing run unattended. After the installation is complete, you can use your Web Part, debugging it on the same computer as VS— VS to determine if your installation was correct. remote debugging is not supported. We’ll walk you through the process of installing the Creating Your Web Part Project Extensions and using them to create and debug a Web Part With the Extensions installed, you’re ready to start using their first Project. Along the way, you’ll see how to create a configurable feature: A set of SharePoint templates that support creating most search tool for a SharePoint site. SharePoint components. To create a Web Part, for instance, you select Web Part project template in the SharePoint category of the Installing the Extensions New Project dialog (see Figure 2, p. 28). The resulting project has a The Extensions download package can be retrieved from folder called Web Part1—delete it (renaming Web Parts is not http://tinyurl.com/bjqwmk by following the link in the body of 100% reliable, at least in the CTP) and use the standard Add New the page (don’t click on the Downloads link—it takes you to a Item dialog to add your Web Part with the correct name. For this patch you probably won’t need). You can download up to three article, I added a Web Part called VideoSearchPart. components: two .MSI files (one each for 32-bit and 64-bit The result is a new folder with the three files required for a Windows) and the release document. You must have IIS, SharePoint Web Part: The code file for the Web Part, an XML file SharePoint and VS 2008 installed on your computer to run the containing the information needed to install the Web Part and a installation package. .WEBPART file with the XML used to configure the Web Part. The installation package installs a Web service (called While it doesn’t appear in Solution Explorer, the Web Part tem- VSeWSS) on your computer that VS will use to communicate plate also includes a feature.xml and a setup.bat file, which you’ll with SharePoint. One of the first challenges that you’ll face after use when installing your Web Part on your production starting the installation wizard is to configure the Web service SharePoint site. (Figure 1, p. 28). Your first step is to pick an application pool to Because you can only debug your WebPart on your devel- use for the Web service. If you don’t want to use an existing pool, opment computer, you’ll need to either copy your target site to you’ll need to create the new pool in IIS Manager before starting your local computer or create a test site on your computer. In the installation. There are two conditions that the identity this particular case, I created a test SharePoint site by starting assigned to the pool must meet: SharePoint Central Administration from my Start menu and, ■ It must have the same permissions as those granted to the from the Application Management tab, picking Create or identity used by the SharePoint Central Administration site Extend Web Site to bring up the dialog that lets me add a new ■ The identity must be part of the Administrators group site. After clicking the OK button to create my site, I used the I picked the simplest solution to meet the first condition: I next page in the process to add a Site Collection using used the SharePoint Central Administration site’s pool as the SharePoint’s Wiki template. pool for the Web service. This also saved me from having to set If your development SharePoint site isn’t installed on port up a new pool. 80 at http://Localhost then you’ll have one more configuration To meet the second condition, you must determine the step to make: You must set the start URL for debugging to point Identity used by the pool you’ve picked. You do this in IIS to the URL for your site. To do this, open your project properties,

PHOTO FROM ISTOCK.COM FROM PHOTO Manager, under Application Pools, by finding the pool you picked navigate to the Debug tab and set the “Start browser with URL”

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 27 0409vsm_How-To_26-32.v5 3/19/09 10:15 AM Page 28

HOW-TO SHAREPOINT EXTENSIONS

text box to the URL for the local SharePoint site where you want to test your Web Part . With your project created and configured, you can now check to see if your installation went correctly: Right-click on the project and select Quick Deploy | Recycle Application Pool. If there were any errors in your installation, you will get a message in your Error List. If you changed the “Start browser with URL” option and you get a message that refers to the original LocalHost URL, select Recycle the Application Pool option again (the Extensions seem to use the original setting once, before using your updated setting).

Configuring the Project and the Site You’re not quite ready to start creating your Web Part. While the Extensions make debugging easy, they don’t configure your SharePoint site to support debugging or report error information. To make these changes, return to IIS Manager, drill down FIGURE 1. Configuring the Web service: You can’t move off of this page in through Web sites to your SharePoint site, right- the Extensions setup wizard until you’ve successfully configured the applica- click and select Properties. On the Home Directory tion pool used by the Extensions’ Web service. tab, you’ll find the path to the folder holding your site’s files in the “Local path” text box. In Windows Explorer, navigate to that folder and open the web.config file in the folder. In this file, change the debug attribute on the compilation element to “true”in order to turn on debugging:

You should also configure your SharePoint site to display any error messages that are generated by set- ting the customErrors tag’s mode attribute to Off (the default setting suppresses all error messages):

To get the full list of called modules listed on the error screen, you’ll also need to set the SafeMode’s CallStack attribute to “true”:

FIGURE 2. SharePoint Project Template: The SharePoint Extensions add a SharePoint category to the Add New Item dialog containing a set of tem- Before adding code to the .VB or .CS file that repre- plates for SharePoint components. sents your Web Part, you should update the .XML and .WEBPART files in the project (it doesn’t appear to be possible to change these values after debugging your Web Part for the first time, at least in the CTP). Inside the By default, your Web Part will appear in the Add Web Parts dialog properties element in the .WEBPART file, rewrite the default prop- in the Miscellaneous section. To have your Web Part appear in a erty elements in the file with the title and description you want to different category, open your Web Part’s XML file and add two have displayed in SharePoint’s Add a Web Part dialog. This example Property tags inside the File element: One with its Name attrib- shows the settings for my sample search part: ute set to Group and the other with its Name attribute set to QuickAddGroups. With the two properties defined, set the Value attribute on both tags to whatever value you want for your group Video Title name. This example will cause the part to appear in a section Search called “PHV Tools”: Fuzzy search on video titles Url="VideoSearchPart.webpart"

28 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com Project7 3/5/09 12:14 PM Page 1 0409vsm_How-To_26-32.v5 3/19/09 10:15 AM Page 30

HOW-TO SHAREPOINT EXTENSIONS

Type="GhostableInLibrary" > that your Part needs. This code adds a button to the table and wires an event routine to it: Dim trButton As New TableRow tbl.Rows.Add(trButton)

Programming the Web Part Dim tcButton As New TableCell You’re finally ready to start creating your Web Part. Within the trButton.Cells.Add(tcButton) Web Part’s code file you must—in the CreateChildControls method—create the controls that will appear on your Web Part. Dim SearchButton As New Button() The simplest approach is to create a table, add it to the Web Part SearchButton.Text = "Search" object’s Controls collection, add rows and cells to the table, then AddHandler SearchButton.Click, AddressOf Me.StartSearch add your controls to the Controls collection of the cells in the tcButton.Controls.Add(SearchButton) table. This code adds a Label control to the first cell in the first row of the table: The event routine pulls data from the two TextBoxes in the table (in the first and second rows) and fills a DataSet that is bound to Dim tbl As New Table a GridView (in the fourth row): Me.Controls.Add(tbl) Private Sub StartSearch(ByVal sender As Object, _ Dim trTitle As New TableRow ByVal e As System.EventArgs) tbl.Rows.Add(trTitle) Dim conn As New SqlConnection("…") Dim cm As SqlCommand = conn.CreateCommand Dim tcTitle As New TableCell Dim da As New SqlDataAdapter(cm) trTitle.Cells.Add(tcTitle) Dim ds As New System.Data.DataSet Dim searchString As String Dim TitleLabel As New Label() TitleLabel.Text = "Look for movies with title:" Dim tbl As Table tcText.Controls.Add(SearchTitle) tbl = CType(Me.Controls(0), Table)

For my example, I created a table with four rows: the first row searchString = CType( _ contains a Label and TextBox for the user to enter the title of a tbl.Rows(0).Cells(0).Controls(1), TextBox).Text movie to search for, the second row contains a Label and a cm.CommandText = "Select * From …" TextBox for the user to enter a category (such as Action or da.Fill(ds, "Results") Drama), the third row contains the button to trigger the search, and the final row holds a GridView to display the result. In the Dim gv As GridView CreateControls method, you should also wire up any events gv = CType(tbl.Rows(2).Cells(0).Controls(1), GridView)

packaging machines. “You can get two problems when people try to extend that SharePoint secretaries together, they can figure out SharePoint model past where it’s sup- what they want to do and they can start posed to go.” vs. SQL putting stuff in there.” Is MOSS putting the squeeze on This is a common occurrence that Strengths and Weaknesses database development? can quickly become problematic, particu- SharePoint is popular for storing and BY JEFFREY SCHWARTZ larly in cases where data that requires sharing documents and other unstruc- referential integrity is put into a tured content, but when an individual has It has been well-chronicled how pervasive SharePoint list, says independent con- data based on rows and columns and is Microsoft Office SharePoint Server sultant and Microsoft MVP Don Demsak, trying to join one list to another, “that’s (MOSS) is becoming in the enterprise. who’s observed this trend and a growing not what those tools were made for,” But for some database developers demand for SharePoint developers. Demsak says. “When you need a relation- and administrators—and in certain cases “SharePoint is very successful because al database, you use a relational data- even higher-ups in the IT food chain— you’re removing levels of impedance, and base—the way it was supposed to be.” SharePoint’s rampant growth is a concern, a lot of DBAs hate SharePoint for those Paul Andrew, Microsoft technical particularly in organizations where data same reasons,” explains Demsak. product manager for the SharePoint that belongs in SQL Server is finding its “Basically you’re storing everything in a developer platform says many are already way into MOSS. “You don’t have to be a BLOB, and you can’t relate to object-rela- building custom applications on developer to go in there,” says Ed Smith, tional mapping, and you can’t do good SharePoint that use a mix of SQL Server a systems analyst at Tetra Pak entity relationships. You can’t do relation- schema and tables within MOSS. “Of International, a global supplier of al models because there’s all sorts of course, each has its own strengths, and

30 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_How-To_26-32.v5 3/19/09 10:15 AM Page 31

SHAREPOINT EXTENSIONS HOW-TO

gv.DataSource = ds SharePoint will now allow the user to set a value for the Category gv.DataMember = "Results" property by selecting the “Personalize this Page” choice on the gv.DataBind() “Welcome User”menu at the top of the page to put the page in “per- sonalization mode.”Once the user enters a value, SharePoint will End Sub ensure that the property is automatically set to that value whenever the user returns to the page. It wouldn’t be a real SharePoint application if it didn’t support some level of customization. For my example, the category Simple Debugging TextBox is supported by a customizable category property that At this point, you get the real payoff for the work you’ve done in set- manages an internal field called _category: ting up SharePoint Extensions and configuring your project: to test and debug your project you just set breakpoints in your code and Private _category As String press F5. When your site displays, you’ll need to add your Web Part to a page by selecting, from the Site Actions menu, the Edit Page _ choice. When the page redisplays in Edit Mode, click on any of the _ Add Web Parts bars to display the Add a Web Part dialog with your _ Web Part. After adding the Web Part to your page you’ll find that _ The SharePoint Extensions are a real boon for developers for creating new Web Part projects, the debugging process is Public Property Category() As String much simpler. Not only does this make life easier for Get SharePoint developers, it lowers the barrier to entry for Return _category ASP.NET developers interested in migrating their skills to the End Get SharePoint arena. VSM Set(ByVal value As String) _category = value Peter Vogel ([email protected]) is a principal in PH&V Information End Set Services, specializing in ASP.NET development with expertise in SOA, XML, End Property database and UI design. He’s written several books on app development using Microsoft technologies and presents at conferences around the world. When the SeachCategory TextBox is added to the Table that makes up the control, I initialize the TextBox with the _category GO ONLINE field that is set through the personalizable property: Use this Locator+ code at VisualStudioMagazine.com to go directly to these related resources. Dim SearchCategory As New TextBox() SearchCategory.Text = _category READ & DOWNLOAD tcCategory.Controls.Add(SearchCategory) VS0904PV Read this article and download the associated code.

each is better suited in different parts of ties, such as security, document manage- as not trusting the CEO’s decisions, an application,” Andrew says. ment and workspaces. “This massively because essentially that’s what decisions “Complex data with a deep relational reduces our time to market,” he says in an are made upon,’ he says, before adding a structure doesn’t fit well in SharePoint e-mail. Using these tools “means you get caution: “One thing you don’t want to do lists,” according to John Beasley, a direc- to do all the correct data analysis you’re is swing the pendulum too far and turn tor with U.K.-based Microsoft Gold used to, but can still use SharePoint to the people responsible for data into a reli- Certified Partner InfoStrata Solutions Ltd. provide all the front-end facilities it’s so gious organization.” To get around this, he uses Quest Web good at providing.” Others are avoiding the problem Parts for SharePoint, which allows simple altogether by putting controls over who’s relational structures to be simulated in Adding Controls permitted to commit data to MOSS SharePoint lists, as well as allowing Still, others argue that companies need to servers. That’s the case for the city of developers to keep data in SQL Server understand when to build applications for Prince George, British Columbia, Canada. while accessing it via SharePoint. SQL Server versus SharePoint. “Looking “We’ve locked it down pretty much, so InfoStrata is a Quest partner, but there at SharePoint Lists and relational data- that all they can do is put in content are other third-party tools developers— bases, there isn’t a comparison,” says directly,” says programmer and analyst such as Bamboo Solutions and Graham Sutcliffe, director of technology Rob Woods. “Nobody else really has the CorasWorks Corp.—that make use of at RD2 Inc., a Dallas-based design firm. option of doing any of this kind of stuff ASP.NET Web Parts Controls to enable the “They both have their uses. You except for the IT staff.” building of customizable pages. can’t stifle an organizations progression, SharePoint, Beasley notes, removes but you have to put people in charge of Jeffrey Schwartz ([email protected]) is the tedium of re-developing routine facili- its data. Not trusting the data is the same the news editor for Visual Studio Magazine.

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 31 0409vsm_Langlab_32-46.v11 3/19/0910:57AMPage32 32 XML Literals XML Literals IULSUI AAIE· VISUAL STUDIOMAGAZINE IN THISSECTION: omnsna o urigjs bu n aa beitSQL, justaboutany data, common syntaxforquerying LINQgives usa and LINQare newin Visual Basic9(VB9). XMLliterals Foundation andLINQ. (WCF) Services Factory Windows Communication XMLliterals, three technologies are: The while atthesametimemakingcode more readable. more responsiveThis technique helpsinwriting ASP.NET pages, thatcanbecombinedframework to provide anewtechnique. combine themforauniquesolution to aproblem. thesecapabilitiesand comesty whenwe cantake several of Even more powerties to enhance andflexibili- my productivity. directly to aproblem Ineedto solve andusethosenewcapabili- So what’s adeveloper to do? thesetools isnearlyafull-timejob. allof Staying current with the pastfewyears we’ve newcapabilities. beenfloodedwith Over so much includedto make your lifeasadeveloper easier. easier andmore performant: joinedstrings makes writing longstrings to write StringBuilder usinga For example, parent whenusingXMLliterals. many ways. help VB developers inmany, thatcan technology isaremarkableliteral onitsown piece of An XML Editor anditunderstandsthatyou wantanXElement. Type raw XMLinto the Visual Studio andsimple. forward raw XMLorXHTMLhasbecomereading andwriting straight- difficultprocess of whatusedto beanarchaic, XML literals, With anincredibly usefulnewtool. VB9 includesXMLliterals, XML Literals behaviors andbindings. out changes to config filesforendpoints, Here we’ll show you how to create tle-known. WCF with- services islit- the out-of-the-box services readiness forbuildingfactory Even though WCF hasbeenhere forawhile, XML orobjects. WCF andLINQ XML Literals, One of thegreat thingsabout BY STEELE PRICE called from both client- andserver-side code. Learn how to create powerful templates that canbe What usedto make code difficultto read becomes trans- the We’re goingto lookspecificallyatthree pieces of { ONVB} On VB· YOUR rsnaindnmcly inways that are more productive presentation dynamically, XML literals 32 pi 09·VisualStudioMagazine.com · April 2009 CODE // I choose to pickthetools thatapply C# Corner· .NET Framework isthatthere is SOURCE than many otheralternatives. 40 / / Ask Kathleen · give you the power to create data 42 Dim M ncd eid Consider thefollowing: XML incode behind. structured enhanced productivity solutionto writing readable, TheXMLliterals approach gives usahighly is nocomparison. there such asXHTML, elementsthatreallystructured are XML, good. bevery still performance will anddon’tcan actuallyread thestring worry; You butto be more productive. performance intheruntime, Thegoalhere isnotto maximize thewithout tags. Use MyString.Value to getthetext inside and much lessto type. XMLliterals are far easierto read Compared to StringBuilder, "easier toreadthanStringBuilder,right?" "This isjustthebeginningandabit" "is retainedwhenweusethestring." "You willnoticethatthewhitespace" "This isaString." > String StringBuilder .Empty ) ) ) ) ) 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 33

Language Lab

On VB

Dim MyTable = _

First Cell Contents Second Cell Contents

Reading XHTML in code behind is now remarkably easier. You also get true IntelliSense for the elements that XML Literals are in a known namespace, which of course means even less typing. XML namespaces are recognized by using FIGURE 1. When you add a new template to your Web application, it appears in the My Imports statements such as the follow- Templates area at the bottom of the Add New Item dialog box. ing for XAML:

Imports Imports some performance features to it and I don’t want to retool to Imports System.Windows.Markup accomplish what I need. I could use AJAX and update panels, but then I would need to account for the entire page lifecycle, The result of all this is that you can do things the same way for which in some cases may be quite large. code behind as you are used to doing in ASPX source view. For example, I have a page that contains aggregate infor- Productivity increases by continuing to write markup this way. mation and I wish to display that in a table format. I could put You do not have to learn another language or syntax to achieve all my aggregates into GridView objects and then place those the same in code behind. inside update panels, then … no, no, no. I’m sure you see the Embedded expressions also look very similar to what you trouble here already. If I have more than one update panel on are used to seeing in markup: the page, I’m really loading the entire page multiple times, just to get my aggregated information to run asynchronously. <%= item.@id %> How can you achieve this without creating a new project, using PageMethods or something else with a large lifecycle? An embedded expression lets you access something outside the Enter Windows Communication Foundation (WCF). WCF has XML literal and embed it into the result. In this case; item.@id always had a lesser-known feature called a factory service. With is an attribute from an item element in another XElement. factory services, you don’t have to worry about things like secu- Additionally, variables aren’t limited here; you can use lambdas, rity, as it inherits the same security as the site. As for config set- functions or anything else available to VB. tings, there are none. This is a perfect solution when you need to I know what you’re thinking, so I’ll go ahead and say it.“If access some information in an AJAX way from client-side code. you’re loading from XML and returning XML, can’t you just The factory services are quite similar to WebMethod(), but use XSLT?”Of course we could, but what fun is that? In fact, I they’re completely WCF compliant. To create a factory service, came up with this technique in a project overhaul that was you simply create a new WCF service. But wait, you said factory using XSLT in its previous version. During development, it service; I don’t see any factory service in my Add Items templates. became quite clear that working in XSLT was not the way to go That is correct, to create a configuration-less factory serv- for us. XSLT is a completely different mindset for most of us ice you need to do it by hand; editing the .SVC file of an AJAX- and has a fairly steep learning curve. In addition, the old sys- enabled WCF service. To do this, open the .SVC file with the tem was forcing SQL to return data as XML, which is not XML editor and add the following: exactly optimal. This approach eliminated that issue while dramatically improving performance. Ultimately, using XML Factory="System.ServiceModel.Activation.WebScriptServi literals means you can be productive faster and have more ceHostFactory"

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 33 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 34

On VB

Then you have to go and delete the config information. The embedded expressions let you insert external data into Because this isn’t an intuitive way to proceed, I created a tem- your elements with much less code. Given the same data, the plate that you can install to do the same thing. Install output is identical. the template by copying WCF_FactoryService.zip to Let’s dissect what’s happening here. MyMenu is an C:\Users\\Documents\Visual Studio 2008\ XElement cast by Option Infer, which is a new feature in VB9 Templates\ ItemTemplates\ that lets you declare variables without explicitly stating a data With this template, you can create services that your Web type. The compiler infers the data type of a variable from application can use in a very easy way with no bother to the cur- the type of its initialization expression. The

    element is rent configuration. If you need to move to a full service with dif- outside the LINQ query so it’s not repeated. The LINQ query ferent bindings, it’s very easy to change this from a factory serv- iterates through the items and returns a group of
  • ele- ice. Simply delete the factory attribute from the .SVC file and ments inside the
      element, with the item’s value inserted add your binding, behavior, service and endpoint configurations into the list item. to web.config. All of this can now be done in one line of easy to read and Something you might be thinking: Why use WCF services simple to type code. Anything used for lists of data can be done XML Literals and not a regular page that just returns the small amount of data this way: tables, unordered lists, ordered lists, select inputs we need? (dropdowns), and the like. Have you ever done a view source on While this approach makes sense in some instances, you a page only to see a dropdown with all the states listed as options still have a full-page lifecycle to deal with. Furthermore, the in the HTML? Using WCF services with AJAX will keep people results aren’t as easy to work with when you want to insert them from being able to see this with view source. You’ll probably get into a portion of an already rendered page with JavaScript. If your page to load faster if that was an AJAX call. you used a page you would have to do quite a bit of parsing. In XML literals give you the power to create data presenta- addition to the speed of execution for WCF, there are support- tion dynamically, in ways that are more productive than many ing features that will make life easier. Throwing FaultExceptions other alternatives. Any LINQ-enabled data, SQL, entities, is one thing you cannot do with page results. You can throw objects, files, WMI, XML, RSS feeds and the like can be HttpExceptions, but they aren’t handled the same way on accessed this way. the client. Now that you have all three pieces in place, your Web appli- cation is wired up to both client and server sides. Accessing the Using LINQ service from the server is as simple as calling a method. The serv- LINQ provides the magic you need to glue all this together. ice is already there and calling it is as simple as Services. Writing markup in code behind is easier to read, while accessing GetPresidentsList(). the same code from both the client side and the server side gives On the client you can use ASP.NET AJAX or jQuery to you a lot of power. Combining LINQ and embedded expres- call the service. Referencing services in ASP.NET AJAX is sions in XML literals gives you a better way to handle looping incredibly easy—just add a ScriptManager that points to the through data. service as follows: Instead of a table, let’s shift to something more demonstra- tive, the
        element. Say you just need to iterate through a group of items and return an unordered list. Unordered lists are great for things like menus and navigation. How is this accom- you had to do something like the following: Dim ul as New HtmlGenericControl("ul") Dim li As HtmlGenericControl Calling the service in JavaScript is now very easy and completely For Each i In items wired up for us: li = New HtmlGenericControl("li") li.InnerHtml = i.Value function getPresidents(){ ul.Controls.Add(li) var ws = new Services.MyService(); Next ws.GetPresidentsList(getPresidentsComplete); } Now you can do this: function getPresidentsComplete(result, eventArgs){ Dim MyMenu =
          <%= if (result.d !== null){ From i In items Select
        • <%= $find("<%= PresidentsArea.ClientID %>").InnerHtml = i.Value %>
        • %>
        result.d;} }

        34 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0208vsm_VSMPureAd.final 1/18/08 11:46 AM Page 32 PUREPURE VISUALVISUAL STUDIO STUDIO AND AND .NET .NET

        ENTERPRISE SOLUTIONS FOR .NET DEVELOPMENT

        MAGAZINE.COM

        POWERING THE WINDOWS SOFTWARE REVOLUTION

        OPTIMIZED FOR PRINT ✱ ONLINE ✱ EVENTS For more information visit: www.VisualStudioMagazine.com www.RedDevNews.com www.VSLive.com 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 36

        On VB

        This makes an asynchronous call to the service and the result is error: function(result) { returned when the service performs a callback to var msg = ''; getPresidentsComplete ().You have the ability to call the service if (result.get_message) { both synchronously and asynchronously, depending on what msg = 'Error: ' + result.get_message(); you need to accomplish. Here’s the same idea using jQuery: } else { msg = result.responseText; $.ajax({ if (msg == '') { type: 'POST', msg = 'Error: Unknown... missing Service?'; } url: '/Services/MyFactoryService.svc/' } + 'GetPresidentsList', alert(msg); data: '{}', target.innerHTML = ''; contentType: 'application/json; charset=utf-8', } dataType: 'json', }); success: function(result, eventArgs) { } XML Literals if (result.d !== null){ $("#<%= PresidentsArea.ClientID %>") Assigning our result to a position on our page is simple. Place [0].innerHTML = result.d;} a

        element anywhere on your page and set the }, innerHTML to the result. Anywhere I’m using that master error: onServiceError page; I will have a function that I can use to directly assign }); the results:

        The json notation is assigned for the dataType because WCF is execMyFactoryService('GetPresidentsList', returning JSON for the result object. The syntax is a little differ- $("#<%= PresidentsArea.ClientID %>")[0]); ent, but is still pretty easy to use. jQuery’s nice ajax() method does all the work for you, and what you get returned from the All the error handling and result inspection is handled centrally service ends up in result.d. I used an anonymous function here and when we’re assigning results as the response to some action to retrieve the result, which we expect to be XHTML into the on the Page, this makes understanding what’s happening much InnerHtml of our div element target. easier. If we were to use the full $.ajax syntax everywhere we We can inspect for errors, but you can see that if we threw needed to use it, it might make the scripting too verbose to be any FaultExceptions in the WCF service, then another function readable at first glance. called onServiceError runs. The Error Handling function is jQuery provides a great productivity boost through a superb passed to the result object for us to inspect for errors and react set of tools for navigating and manipulating DOM objects in accordingly. JavaScript. Some of the same features are in ASP.NET AJAX, but My normal process for using this in a production applica- the two models can be used together to provide even more power tion is to define a single function in my master page for calling for your client-side activities. the service. If you provide accessibility through several short- cuts, getting results from the services and assigning those results The Whole Picture become even easier. Now that I’ve explained the parts and pieces, how does it all Here’s a sample that I’ve used: work together? Let’s explore this a little further. A complete template looks like this inside the service: function execMyFactoryService(method, target) { _ var rval = ''; Public Function GetPresidentsTable() As XElement $.ajax({ Dim items = XElement.Load(ApplicationPhysicalPath & _ type: 'POST', "App_Data/SampleData.xml") url: '/Services/MyFactoryService.svc/' + method, Try data: '{}', Dim result = _ async: true,

        contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(result, eventArgs) { if (result.d !== null){ target.innerHTML = result.d; } }, <%= From i In items.Elements Select _

        36 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 37

        On VB

        Lambdas are a new feature in VB9 and can save you a lot of hassle when you need a quick function. LINQ itself is actually a framework built on lambda expressions and are an integral part of how it works.

        Imports System.Web.Script.Serialization Imports System.Runtime.Serialization Namespace Services _ ''' %> ''' This Service provides access to various
        PositionNameBegan TermFinished Term
        <%= i.@id %><%= i.@Name %> <%= i.@Start %><%= i.@End %>
        ''' MyFactoryService procedures through WCF Return result ''' ''' Catch ex As Exception _ ' it’s a shortcut to get the current Method Name _ .GetFrame(0).GetMethod() _ _ End Try Public Class MyService End Function _ The service is a WCF factory service. These are very simple to Public Sub DoWork() create, with the Visual Studio Template included here. End Sub I use a Services Folder in my Application for organization and security. Add the Services Folder, and then add a web.con- End Class fig for the folder. This lets us assign different security rights to the services in the folder if we need to limit them by Roles. End Namespace Adding a New Item to your Web Application looks like Figure 1, p. 33. All that’s left for us to do is enter the code into DoWork(). The new Template is in the My Templates area at the bottom Usually you’ll want to rename this, which is fine, because what’s of the dialog. If you’re like me, you probably have many installed presented here is just a stub to get us started. Templates you need to scroll through to get to My Templates. For debugging we simply add a Try/Catch block to handle When the template creates the service, we can inspect the anything bad that may cause the template to break. For this configuration data using Open With. example we are just returning Nothing, but we could add very Choose XML Editor from the list. This will open the .SVC rich error handling here by throwing FaultExceptions. file for us, rather than the code behind that gets opened when FaultExceptions are handled quite nicely by ASP.NET AJAX and you double-click on the file itself. You may see some jQuery on the client. You can decide how to handle problems in IntelliSense confusion from the editor, but you can safely the service and the client can respond using a combination of ignore it. results and error handling. The generated service is: Let’s talk briefly about what you can do with this in your toolbox. I want to display a bunch of images dynamically. <%@ ServiceHost Maybe I want to get the results from a search out on the Web. I Language="VB" could configure something in the client, or I could stay consis- Debug="true" tent and use our own services. This lets us control everything Service="Services.MyFactoryService" and not expose possibly sensitive information in the client- Factory="System.ServiceModel.Activation. side code, such as a password. We won’t build that one right WebScriptServiceHostFactory" now, but think about how useful it could be to control going CodeBehind="MyService.svc.vb" %> out to your external service accounts to grab dynamic status or images from social networking services. The code behind is: In our Presidents sample we could go look on an external service for the images of the Presidents. Configuring this is Imports System.ServiceModel really quite easy now that we have a set of tools to work with Imports System.ServiceModel.Activation that makes this simple. I could use a WebClient to call the

        VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 37 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 38

        On VB

        jQuery provides a great productivity boost through a superb set of tools for navigating and manipulating DOM objects in JavaScript. Some of the same features are in ASP.NET AJAX, but the two models can be used together to provide even more power for your client-side activities.

        external API and work with the results in the service prior to This function will evaluate the condition, and then return a returning them. different field from the user object based on the condition. What if I already have the images? How do I get them The interesting thing here is that we didn’t have to tell the from the file system easily? I would create a service method lambda what u is, inference will do that for us most of the similar to this: time. Occasionally inference gets confused and you may need XML Literals to qualify what u is which you can do with: _ Public Function GetPortrait( _ Function(u As User) ByVal value As String) As XElement Dim image = (From FileName In _ I don’t want to go on too much about lambdas, you will use My.Computer.FileSystem.GetFiles( _ them all the time with LINQ. Just about any time you need a HttpContext.Current.Server.MapPath( _ Where clause you’ll be using lambdas. LINQ hides some of the "~/Images")) verbosity for you when you’re using the full query syntax, but Where FileName.StartsWith(value) Let File = _ it’s still a lambda. When you use the extension syntax you My.Computer.FileSystem.GetFileInfo(FileName) almost always use lambdas: Select title=<%= File.Name %>>).First() Another reason I bring this up now is to answer the question: Return image What if we need to return complex conditioning to our data End Function when we build the return? This is much easier with lambdas than creating a bunch of functions that may only be used for I have provided a dynamic function to return an image from this specific template. When building our template, maybe we our file system—certainly not a daunting task for us now. We want to change the elements returned based on some criteria in can expand this to handle getting the image path any way that the data. Extended syntax like lambdas make very powerful suits our needs and we can surround all the proper error han- tools for building templates. dling in the function. I can return either an appropriate fault exception or an empty element to just ignore missing images, so Easy Formatting Based on Conditions the client doesn’t see errors. Because we have a true ternary If() command available to us we When designing a template consider what’s static and can make templates that do this: what requires looping. Looping should be done with either LINQ or lambdas in this case. A Do Loop or For Each works <%= If(items.Count = 0, _ just as well, but I find myself replacing them with LINQ since I had no other alternative before. It also makes the code much easier to work with in templates if you use LINQ.

        No records to display.
        Something to consider here is the use of lambda expres- sions. Lambdas are a new feature in VB9 and can save you a , _ lot of hassle when you need a quick function. LINQ itself is CType(Nothing, XElement)) _ actually a framework built on lambda expressions and are an %> integral part of how it works. Lambdas in Visual Basic look <%= —- continue normal processing —- %> like this: This template lets us return Nothing when we have real data to Function(u) If(u.Age < 18, _ work with, or an element describing the lack of data to the u.ParentPermissionGranted, u.PermissionGranted) user. I can go on and on about the wealth of possibilities you have at your disposal when using all these techniques together.

        38 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 39

        Instantly Search Terabytes of Text

        N dozens of indexed, The Bottom Line Currently, nothing else is this flexible and this easy with the out- unindexed, of-the-box tools we get with Visual Studio 2008. You have com- fielded data and plete access to all the features of .NET Framework for building full-text search your templates. Calling them from both the client and server is options (including extremely easy, and because you’re using WCF, ther’s no added Unicode support page lifecycle overhead.A similar service can be created to return XAML instead of XHTML. This makes migrating or extending for hundreds your templates extremely easy if you need access from Silverlight of international or WPF in the future. languages) T4 templates and other code generator-based utilities are great when you can generate everything in advance. This tech- N file parsers / nique goes beyond that to generate during runtime, and we can converters for generate runtime-ready code in any XML derivative such as hit-highlighted XAML and XHTML. display of all ASP.NET 4.0 is expected to provide a new template system, but that doesn’t change the usefulness of this technique. ASP.NET popular file 4.0 will be using a completely different system, which may or may types h Spider DesktopDesktop withwithwit Spider Spider not be as easy to use and as flexible in what it returns. From what N Spider supports th Spider I’ve seen so far, it looks good, but it still doesn’t solve the immediate NNetworketwork withwwithi Spider Spider issues that are addressed by using this technique. static and XML literals, WCF factory services and LINQ, taken by dynamic web Publish forfor CD/DVDs CD/DVDs themselves, are very useful. When these are combined, you get a data; highlights completely different picture for solving real-world problems. All Web withwith Spider Spider New hits while while maintaining a productive, easy-to-implement style. Engine forfor Win Win & & .NET .NET 64-bit XML literals provide high productivity and readability displaying links, when writing structured XML in code behind. It can also help formatting and Engine forfor Linux Linux format long or complex strings to make them more readable. images intact Embedded expressions give you the power to insert external data into the XML in a very easy-to-read and -maintain way. N API supports .NET, C++, Java, databases, etc. WCF factory services allow you to extend the power of the New .NET Spider API framework to your client-side code without the hassle of all the configuration knobs and buttons that are available to WCF ® services. Starting with a factory service does not limit you in any The Smart Choice for Text Retrieval way from upgrading to the full configuration format later. A since 1991 simple change enables a progressive upgrade path when you need this ability. N “Bottom line: dtSearch manages a terabyte of text Finally, using LINQ in embedded expressions enables you in a single index and returns results in less than a to insert external data into XML in a way that is easy to read, second” – InfoWorld with much less code to accomplish the task. LINQ allows you to start thinking differently about how you process loops through N “For combing through large amounts of data,” any data utilizing the same syntax. Now go see what you can do dtSearch “leads the market” – Network Computing with all this new power and productivity. VSM N dtSearch “covers all data sources ... powerful Steele Price ([email protected]) has been professionally designing and Web-based engines” – eWEEK developing data-driven applications for more than 25 years. He has been a Microsoft MVP for Visual Basic since 2005 and frequently works with the N dtSearch “searches at blazing speeds” – Computer Microsoft VB team to help improve the language. Price is currently chief technology officer at Digital Dreamshop, a micro ISV developing enterprise Reseller News Test Center applications with VB.NET, Silverlight, Windows Presentation Foundation See www.dtsearch.com for hundreds more reviews, and LINQ. and hundreds of developer case studies GO ONLINE Use this Locator+ code at VisualStudioMagazine.com to go Contact dtSearch for directly to these related resources. fully-functional evaluations

        READ MORE VS0904OV Read this article online. 1-800-IT-FINDS • www.dtsearch.com

        VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 39 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 40

        { C#CORNER }

        Make Your Code Clear List sequence = new List(Enumerable.Range(1, 50). There are multiple ways to solve every problem. Strive Select(n =>(double)n)); for code that communicates your intent and makes your double actual = NumericAlgorithm.Mean(sequence); meaning clear for every developer who uses it. BY BILL WAGNER One less line of code, and that means one less bit of work for every use of your library. Of course, this first change leads to the It’s often not that hard to create code that works. What often obvious change of making the NumericAlgorithms class a static separates average code from high-quality code is how well that class: Clear Code Clear code—especially its public interface—describes its own capa- bilities. A small time investment in your code will save time public static class NumericAlgorithm explaining how it works and avoid enhancing it unnecessarily, creating more work for yourself and your users. Doing so prevents any customer from accidentally creating a In this article, I’ll walk you through a review of a small NumericAlgorithm class. It also prevents library maintainers library, discussing a series of changes and the motivation from creating instance data or instance methods in the class. behind those changes. You’ll see how to improve the resiliency These are small changes, to be sure, but they do prevent and quality of a codebase. users from accidentally doing the wrong thing. Next, you should look at the current API and consider its A Working Numeric Library limitations. All the APIs use List as the input Listing 1 (opposite page) shows a small numeric class that per- sequence. That’s unnecessarily limiting. The internals of the forms a few simple calculations on a sequence of numbers. This methods don’t rely on any capabilities beyond IEnumerable library has some simple mathematical functions: mean, medi- . You can see the costs of this restriction on the sample an, variance, minimum and maximum. It’s not a major library, code. Instead of writing this: but there are enough methods here to demonstrate the con- cepts involved in shaping the impression your code can give to List sequence = new customer developers. List(Enumerable.Range(1, 50). This library works, but there are many areas where the code Select(n =>(double)n)); can be improved.When developers look at your API, they’ll create an impression of the library based on your stated API. If they’re Users should be able to write the simpler version: your team members and they examine your source, they’ll contin- ue to build on those assumptions. Your code gives those client IEnumerable sequence = developers an impression of your code. You’re going to spend Enumerable.Range(1, 50).Select(n =>(double)n); your time making its intent clearer, not fixing behavior. The first problem is that all of the methods on this class are This version allows users to call your library using any type of instance methods. There’s no reason for instance methods on collection: a list, an array or even a dynamically read sequence this class. The first change is to make all the methods static as I’m using above. instead of instance methods: This changes the signatures of all the methods in the class:

        public static double Mean(List sequence) public static double Mean(IEnumerable sequence)

        After this change, your customers no longer need to create a In addition, you’ll need to change the internal implementation NumericAlgorithm object in order to use these methods. of some of the methods. In particular, the Mean, Median and Instead of writing this: Variance methods now must generate both the sum and the count of elements. That’s because IEnumerable doesn’t NumericAlgorithm target = new NumericAlgorithm(); contain a Count property where List does. List sequence = new At this point, you’ll notice that some of the methods might List(Enumerable.Range(1, 50). need additional work. The Mean() and Variance() methods Select(n =>(double)n)); must iterate the collection more than once: calculating the sum, double actual = target.Mean(sequence); the count of items and even the squares of the collection. You may be tempted to create more complicated methods to per- After this change, they can write this simpler version: form all those calculations in one pass. If you look at the fin-

        40 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 41

        C# Corner

        ished version of the numeric library, you’ll notice that I didn’t do C# NUMERIC LIBRARY VERSION 1 that extra work. I ran some performance tests and found that making those changes just didn’t change the performance public class NumericAlgorithm metrics by any appreciable amount. Therefore, I went with the { simpler implementation. Your mileage may vary, but test public double Mean(List sequence) { performance before making changes with the intent of double total = Sum(sequence); improving performance. return (sequence.Count == 0) Also, your algorithms should make the smallest set of ? total : total / sequence.Count; assumptions about the parameters you need. By making fewer } assumptions, you automatically get more reach from possible public double Median(List sequence) users. Look at your methods and determine if you need all the { capabilities of a parameter type. Whenever you can, provide a if (sequence == null) less-constraining interface. throw new ArgumentNullException("sequence", "Sequence must not be null"); if (sequence.Count == 0) Avoiding Problems return 0; I wrote this sample to be representative of common production code I see in libraries. Too often, many of the developers I work List local = new List(sequence); with create libraries from the inside out. They have strong local.Sort(); knowledge about how they’ll implement a particular set of fea- return local[local.Count / 2]; tures, and that knowledge deeply colors how they create the } Code Clear functionality. Those assumptions show up quickly in the test code. It’s especially evident in the test code that demonstrates public double Variance(List sequence) the successful scenarios for your library. For example, let’s look { double sum = Sum(sequence); again at one of the first test samples for the original library: if (sequence.Count == 0) return 0; [TestMethod()] List squares = public void MedianSimpleTest() sequence.Select(n => n * n).ToList(); double sumSquares = Sum(squares); { double variance = (sumSquares + sum * sum / NumericAlgorithm target = new NumericAlgorithm(); sequence.Count) / (sequence.Count - 1); List sequence = new return variance; List(Enumerable.Range(0, 50). } Select(n => (double)n)); public double Sum(List sequence) double expected = 25; { double actual = target.Median(sequence); if (sequence == null) Assert.AreEqual(expected, actual); throw new ArgumentNullException("sequence", } "Sequence must not be null"); double total = 0; sequence.ForEach(num => total += num); Contrast that with the final version: return total; [TestMethod()] } public void MedianSimpleTest() } { IEnumerable sequence = Enumerable.Range( 0, 50).Select(n => (double)n); LISTING 1 This version of the numeric library works correctly. However, there are many poor practices in this library that make it double expected = 25; harder to use. In addition, those practices will confuse users of the double actual = NumericAlgorithm.Median(sequence); code. They’ll make assumptions about what the code does because Assert.AreEqual(expected, actual); of how it’s structured. In its current form, those assumptions will } be wrong.

        There’s not a huge difference in size.You may not easily see ben- efits when you examine a single test method. Instead, seriously developers will need to write. When possible, I’ll write the suc- examine the clarity of the test code. Is it clear what the test code cess scenario tests before I create any of the library code. That is trying to do? Is it clear how to use the API? forces me to think about the problem and the solution through The second test, which executes the exact same actions, has a client developer’s eyes: What code would I want to call in less code that’s unrelated to the problem at hand. It’s easier to order to solve a given problem? If I start by writing the library understand exactly what test is executing. (I realize that the code, I’ll create a library that looks like how I solved the prob- Enumerable.Range() method may be unfamiliar if you don’t lem, not a library that looks like how I want to use a solution. use LINQ much, but that’s not related to the API.) In fact, using Of course, not every project can be written that way. Too the new version, you could replace the range call with an array, often, we’re extending existing systems that don’t have a test or any other storage. framework already in use. In that case, you’ll end up working I look at test code as a way to evaluate the code that client through the tasks I outlined earlier in this article: create the

        VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 41 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 42

        C# Corner

        tests; look at the code in the tests; and modify the library Your code communicates your design intent to its users. until you have the API you’d like. At each step, look at It’s important that you take advantage of this opportunity to your tests—especially the success tests—and decide if the API communicate to the users of your code. Do it well. VSM is as convenient as it could be. If not, you should continue to make modifications until you have an API that matches your Bill Wagner ([email protected]), author of “Effective C#: 50 expectations. Specific Ways to Improve Your C#” (Addison-Wesley Professional, 2004) and “More Effective C#: 50 Specific Ways to Improve Your C#” (Addison- Structuring Your Code Wesley Professional, 2008), has been a commercial software developer for Compare the initial version of the library with the final version the past 20 years. He’s a Microsoft regional director and a Visual C# (see Go Online for how to access a sample of the final version). MVP.Wagner’s interests include the C# language, .NET Framework and Even with only a few methods, you can see more clarity in how software design. the library will use its parameters and how it can be used. The API more clearly describes how it will be used. GO ONLINE Think about your own classes and examine if they com- Use this Locator+ code at VisualStudioMagazine.com to go municate their intent and their use for other developers. Does directly to these related resources. Clear Code Clear their structure communicate your design intent? If not, modify the public API until it matches your assumptions about the READ & DOWNLOAD usage of your classes. VS0904CC Read this article and download the associated code.

        { ASK KATHLEEN }

        Working with MEF projects within Microsoft are committed to it, including the Learn how to free your application from dependencies Visual Studio (VS) 2010 code editor. Until it appears in .NET and interchange implementations using Managed Framework, you’ll need to download MEF and place Extensibility Framework. System.ComponentModel.Composition.dll in an accessible BY KATHLEEN DOLLARD location.You should also realize that changes to the API may occur. Your application will be the MEF host while your cus- Q: I’ve been hearing the term MEF lately and I know it means tomers will write MEF clients or extensions. Extensions are Managed Extensibility Framework, but I don’t understand what it simpler to write because the host must also manage the does. Would it be a good fit for allowing customers to add their own CompositionContainer. I’ll step through the process of creating forms to our Windows Presentation Foundation (WPF) app? We an interface, building extensions and building a WPF host. The need those new forms to appear in our menus and we don’t want to WPF host will pass a catalog to a CompositionContainer that give customers our Visual Basic source code to recompile. will specify a directory to search for menu extensions. Extensions support contracts. The most common con- A:This sounds like a good application for MEF.You could use tracts are interfaces, and these interfaces might be quite simple: the same approach for WinForms or ASP.NET and the C# code would be similar to what I’ll show here. Public Interface IExtension MEF is an extensibility model that allows components to Sub ShowWindow() interact using a simple model. Components are called parts in End Interface MEF.MEF is designed to be extensible to different types of mod- els, but ships with an attributed model. This lets you define the Your customers can add extensions by implementing this interaction between your parts via normal .NET attributes. If a interface and specifying the Export attribute from the part needs something, it uses an Import attribute and if a part System.ComponentModel.Composition namespace: supplies something it uses an Export attribute. Any part can be a host or client, provider or consumer. MEF bases these interac- _ tions on contracts and offers a flexible discovery model. Your _ application makes a request and leaves it to MEF to provide the Partial Public Class First implementation. This frees your application from dependencies Implements IExtension and lets you interchange implementations. MEF is currently available as a preview on CodePlex. It’s in Public Sub ShowWindow() _ the System.ComponentModel namespace, indicating that it Implements Common.IExtension.ShowWindow will appear as a full member of .NET Framework 4.0. Several End Sub

        42 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 43

        Ask Kathleen

        End Class Overriding the OnStartup method let’s you prepare the con- tainer when your application starts: You can also use an arbitrary string to identify the export, but the common case for extensions is to retrieve via an interface Protected Overrides Sub OnStartup( _ contract. The ExportMetadata attribute lets you include extra ByVal e As StartupEventArgs) information about the extension that the host can retrieve with- MyBase.OnStartup(e) out actually instantiating the underlying object, which lets you If Compose() Then control instantiation and protects performance. MainWindow.Show() When you design your solution, put interfaces in a sepa- Else rate assembly referenced by both the host and all extension Shutdown() assemblies. Do not establish any direct references between your End If host and extensions. All of your assemblies will need a reference End Sub to System.ComponentModel.Composition.dll. Your compiled extensions will need to be placed in a convenient location. You The compose method does the actual preparation: can specify the build location in the Project Properties dialog. The host is responsible for managing the Compo- Private Function Compose() As Boolean sitionContainer. The CompositionContainer hooks up imports Dim cat As New AggregateCatalog and exports behind the scenes and must know what exports are available. Creating the container as a project level variable lets you The aggregate catalog allows you to manage several catalogs MEF clean it up in OnExit. The call to the container’s Dispose method together. If a set of catalogs appear together in an aggregate cat- disposes of any parts that implement IDisposable: alog, all matching items within this set of catalogs are discov- ered. Several different types of catalogs are available, including Protected Overrides Sub OnExit( _ DirectoryCatalog, which loads all assemblies in a specified ByVal e As System.Windows.ExitEventArgs) directory. In your case, I’d suggest including the location of MyBase.OnExit(e) extensions as part of the application settings to allow later con- If mContainer IsNot Nothing Then figuration. You’ll also add the current assembly: mContainer.Dispose() End If Dim extLocation = My.Settings.ExtensionLocation End Sub cat.Catalogs.Add(New DirectoryCatalog(extLocation))

        8VcNdj8ji9ZkZadebZci8dhih 7n>cXgZVh^c\EgdYjXi^k^in4

        Æ7Z[dgZGVaan!lZhigj\\aZYideg^dg^i^oZl]VidjgXjhidbZgh gZVaancZZYZY#CdllZldg`dci]Z]^\]ZhikVajZegd_ZXih ZkZgnildlZZ`h#6cY!lZÉkZgZYjXZYgZaZVhZi^bZhWn*%#Ç 6\^aZVcYGVaanXVcXjindjgi^bZ"id"bVg`Zi Wn*%VcY^cXgZVhZegdYjXi^k^inWn'*#

        ;h_a>kZZb[ijed" 8ID!>cdk^h

        =ZVgi]Zl]daZhidgnVcYhZZl]nGVaan^hi]Zdcan 6\^aZA^[ZXnXaZBVcV\ZbZcikZcYdgid\jVgVciZZndjghjXXZhh# AZVgcbdgZVilll#gVaanYZk#Xdb

        '%%.GVaanHd[ilVgZ9ZkZadebZci8dge

        VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 43 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 44

        Ask Kathleen

        The menu caption is retrieved from the MEF metadata. While this works, your goal is to make life as easy as possible for programmers writing extensions. This metadata approach requires they know to use the exact string "MenuCaption". It’s easy to fix this using strongly typed MEF metadata.

        cat.Catalogs.Add(New AssemblyCatalog( _ End Property Me.GetType.Assembly)) MEF mContainer = New CompositionContainer(cat) There’s one more detail specific to VB. The Application Framework automatically instantiates the specified window and At this point the container is ready to work, but no work has bypasses your MainWindow property. Disable the Application been requested. A composition batch allows you to specify the Framework and add a Sub Main to the Application.xaml.vb file: items to evaluate for Import requests when you call the Compose method. Any object later instantiated via an Import '''

        request will also be evaluated for additional Import requests. In '''Application Entry Point. many cases the first call to Compose will be the only one you ''' need to perform. Because Compose performs the composition, _ it will fail if composition rules are not followed, so the Public Shared Sub Main() Try/Catch block provides reporting: Dim app As Application = New Application app.Run() Dim batch = New Hosting.CompositionBatch() End Sub batch.AddPart(Me) Try mContainer.Compose(batch) Catch ex As CompositionException MessageBox.Show(ex.ToString()) Return False End Try Return True End Function

        The Main window of the application uses an Import attribute on a field. For MEF to satisfy this request and create the field value, the Main window itself must be provided via MEF—MEF evaluates Import attributes on anything explicitly added to a batch and anything that is instantiated via another Import. You can do this by replacing the MainWindow method in the base class via Overloads (new in C#):

        _ Public Overloads Property MainWindow() As Window Get Return MyBase.MainWindow End Get Managed Extensibility Framework offers several catalog types. The Set(ByVal value As Window) directory catalog searches a file system directory for parts that match your MyBase.MainWindow = value import requests. This lets your users add extensions just by dropping assemblies into a specified directory. End Set

        44 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 45

        Ask Kathleen

        This causes the application to retrieve the MainWindow via the End Sub property and thus evaluates MEF requests in the Main window. The Main window exports itself to MEF to match the Note that the menu caption is retrieved from the MEF metadata. MainWindow property import: While this works, your goal is to make life as easy as possible for programmers writing extensions. This metadata approach _ requires they know to use the exact string "MenuCaption". It’s Partial Public Class Main easy to fix this using strongly typed MEF metadata. To begin, create an interface: The Main window uses MEF to discover available extensions that implement the IExtension interface: Public Interface IExtensionMetadata ReadOnly Property MenuCaption() As String _ End Interface Private exportExtensions As ExportCollection( _ Of IExtension) Now create an attribute that parallels this interface. This attrib- ute needs to match the metadata interface. It does not need to Anything that appears in the catalog or is manually added to the implement the interface, but this is the easiest way to keep them container through batches and implements the IExtension inter- in sync: face will appear in this collection. Note that this creates a collec- tion of Export objects that contain sufficient information to _ them. This is important to maintain adequate performance. Public Class ExtensionMetadataAttribute The Main window fills the menu using standard WPF code: Inherits Attribute Implements IExtensionMetadata Private Sub Main_Loaded() Handles Me.Loaded Private mMenuCaption As String For Each export In exportExtensions Public Sub New(ByVal menuCaption As String) Dim newItem = New MenuItem() mMenuCaption = menuCaption newItem.Header = export.Metadata("MenuCaption") End Sub Me.ExtensionMenu.Items.Add(newItem) Public ReadOnly Property MenuCaption() _ Next As String Implements IExtensionMetadata.MenuCaption

        PERFECTION IN SOFTWARE PROTECTION Exceptional Software Protection

        Software Protection

        Document Protection

        Order your Free Software Development Kit now! Access Protection Phone 1-800-6-GO-WIBU | [email protected] Media Protection CodeMeter for .NET  More than 1000 Key-Storage License Entries  Control Networketwork LicensingLicensing - Different ISV´s can share one dongle - Control concurrent users  - Control “roaming“ users WIBU-SYSTEMS USA Inc. Secure Expiration Date with a Real-Time-Clock 110 W Dayton Street, - Unique Time Certifi cation Feature  Create “Standby“ Licenses Edmonds, WA 98020 - Control Relative and/or Absolute time - Hot Standby and Cold Standby United States www.wibu.us  - Provide Overfl ow Licenses More ways to sell = More sales [email protected]  Create Student and Version Licenses  Pay-Per-Use Counter

        VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 45 0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 46

        Ask Kathleen

        Get You are committing to maintaining the interfaces you Return mMenuCaption release to your customers. If you alter the interface, you will End Get break their code. Instead you can create a new interface, leaving End Property the previous interface intact. MEF itself is extensible. If you End Class encounter versioning or AppDomain isolation problems, you could create an additional programming model that would Your customers can decorate their extensions with this attribute: combine the MEF and MAF, however you would reintroduce some of the complexities of MAF. _ MEF also has a direct access API, which you might require, _ but the Import/Export attribute model is desirable for most Partial Public Class First scenarios in VB or C#. The full extensibility of MEF allows its use in other scenarios, including dynamic languages, external You can leverage this metadata by altering the Import request in definitions and alternate discovery mechanisms. MEF the Main window to include a second type parameter: So far, I’ve skipped over the important issues of cardinality and lifetime. When you place the Import attribute on a single _ item, you state that you expect a single item. The standard MEF Private exportExtensions As ExportCollection( _ container configuration throws an exception if no matches or Of IExtension, IExtensionMetadata) multiple matches are found:

        This provides a strongly typed MetadataView to simplify access _ to export metadata: Private textToDisplay As ITextToDisplay

        newItem.Header = export.MetadataView.MenuCaption If you know there may be multiple matches, you can import into an IEnumerable or an ExportCollection. If you don’t want While I’ve answered your question, I don’t think I’ve solved your an exception thrown if no match is found, you can set the problem yet.At this point, the windows display but do not interact AllowDefault parameter on the Import attribute to True. If you with each other or the rest of your application. That next step is don’t know how many matches will be discovered, place the easy because MEF makes no distinction between extensions and import on a collection and manage getting the correct instance host while resolving Import and Export attributes. The sample in in your code. the download uses additional interfaces to provide a string to Lifetime refers to whether a single instance of the export is extensions from the host as a simple demonstration.Your app will used for all requests (CreationPolicy.Shared), or a new instance probably provide more sophisticated functionality such as the created for each request (CreationPolicy.NonShared). You parent window, where extension user controls or specific busi- declare the lifetime using a CreationPolicy parameter on the ness objects or application data should be sited. Export attribute or the RequiredCreationPolicy on the Import It’s valuable to export classes, not primitive values or struc- attribute. The default creation policy is Any and if both Export tures. The values of reference types will reflect changes as your and Import attributes have a CreationPolicy of Any, the result is application proceeds rather than reflecting only the value MEF a shared instance. If the CreationPolicies conflict, MEF throws supplied at composition. This also means two-way communica- an exception. This allows you fine grain and flexible control tions can be provided either through mutable objects that allow over instance creation from either the export or import side. changes, or through immutable objects that expose specific data. MEF has the capacity to let you build highly decoupled In addition to host/extension interactions, multiple extensions applications that support customer extensions, granular devel- can communicate with each other using interfaces that are opment, test mocking and good programming design. It’s a entirely unknown to the host or initial programmers. good technique to add to your arsenal. VSM The compiler shortcuts recompiling non-referenced assemblies and a composable application doesn’t maintain ref- Kathleen Dollard ([email protected]) is chief technologist for AppVenture erences. Avoid problems with out-of-date assemblies by using (www.appventure.com), as well as a consultant, author, trainer and speaker. Rebuild Solution before testing your application. She’s been a Microsoft MVP for 11 years and an active member of the INETA MEF is similar to System.AddIn (also called MAF), which I Speakers Bureau. She wrote “Code Generation in Microsoft .NET” (Apress, discussed in April 2008 (see “Extend Your Apps with External 2004) and blogs at http://msmvps.com/blogs/kathleen. Add-Ins”). MAF is significantly more complex to use, but solves additional problems of isolation and versioning. MEF extensions GO ONLINE run in the AppDomain of the host, with the rights of your Use this Locator+ code at VisualStudioMagazine.com to go AppDomain. This means when using MEF you must trust exten- directly to these related resources. sions not to run malicious code, or offer protection via Code Access Security. MAF solves this problem by creating extensions READ MORE in a separate AppDomain, which you can lock down or sandbox. VS0904AK Read this article online.

        46 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com 0409vsm_AdIndex_47.v2 3/19/09 4:35 PM Page 47

        Advertising Sales Ad Index

        Advertiser Page /n Software Inc. 7 www.nsoftware.com Accusoft Pegasus 23 www.accusoft.com AppDev Training 29 East www.appdev.com Andrew Mintz Aspose C3 www.aspose.com National Sales Manager Phone: 508-532-1433 Atalasoft Inc. 21 [email protected] www.atalasoft.com ComponentArt Inc. 14, 15 www.componentart.com dtSearch Corp. 39 West www.dtsearch.com Chris Kourtoglou ESRI 5 Regional Sales Manager www.esri.com Phone: 650-579-0121 Intel Corp. C4 [email protected] www.intel.com LEAD Technologies Inc. 11 www.leadtools.com National Accounts Director Director, Print Production Jenny Hernandez-Asandas Microsoft Corp. 18, 19 William Smith Phone: 818-734-1520 ext 101 www.microsoft.com Phone: 603-886-3466 Fax: 818-734-1528 Rally Software 43 [email protected] [email protected] www.rallydev.com Software FX C2,1 Microsoft Account Manager Production Coordinator www.software FX.com Serena Barnes Danna Vedder Visual Studio Magazine 35 Phone: 818-734-1520 ext 164 http://visualstudiomagazine.com Phone: 253-514-8015 [email protected] [email protected] VSLive! Las Vegas 24, 25 [email protected] http://vslive.com/ Wayside Technology Group Inc. 2 www.waysidetechnology.com

        information has been reviewed for accuracy, there is WIBU-SYSTEMS USA Inc. 45 ID Statement www.wibu.com Visual Studio Magazine (ISSN 1537-002X) is published no guarantee that the same or similar results may be monthly by 1105 Media Inc., 9121 Oakdale Avenue, achieved in all environments. Technical inaccuracies may result from printing errors and/or new develop- Ste. 101, Chatsworth, CA 91311. Periodicals postage Editorial Index paid at Chatsworth, CA 91311-9998, and at additional ments in the industry. mailing offices. Complimentary subscriptions are sent AAmazon.com Inc. 12, 48 www.amazon.com to qualifying subscribers. Annual subscription rates for Corporate Address non-qualified subscribers are: U.S. $34.97, Canada 1105 Media Inc. ArtOfTest Inc. 12, 13 www.artoftest.com $52.97 (U.S. funds); International $78.97 (U.S. funds). 9121 Oakdale Ave. Ste 101 Subscription inquiries, back issue requests, and Chatsworth, CA 91311 CA Inc. 13 address changes: Mail to: Visual Studio Magazine, www.1105media.com www.ca.com P.O. Box 1164, Skokie, IL 60076-8164, e-mail Capgemini 20 [email protected] or call toll free 888-768- Media Kits www.us.capgemini.com 8759, fax number 847-763-9564. International calls Direct your Media Kit requests to Matt Morollo, VP ComponentOne LLC 13 847-763-9135. POSTMASTER: Send address changes Publishing. www.componentone.com to Visual Studio Magazine, P.O. Box 1164, Skokie, IL Phone: 508-532-1418 Embarcadero Technologies Inc. 13 60076-8164. Canada Publications Mail Agreement No: Fax: 508-875-6622 www.embarcadero.com 40612608. Return Undeliverable Canadian Addresses E-mail: [email protected] Exeros Inc. 13 to Circulation Dept. or Bleuchip International, P.O. Box www.exeros.com 25542, London, ON N6C 6B2. Reprints IBM Corp. 13 For single article reprints (in minimum quantities of www.ibm.com Copyright Statement 250-500), e-prints, plaques and posters contact: © Copyright 2009 by 1105 Media, Inc. All rights InfoStrata Solutions Ltd. 31 PARS International www.infostratasolutions.com reserved. Printed in the U.S.A. Reproductions in Phone: 212-221-9595 whole or part prohibited except by written permis- E-mail: [email protected] Magenic Technologies Inc. 16 www.magenic.com sion. Mail requests to "Permissions Editor," c/o Visual Online: www.magreprints.com/QuickQuote.asp Studio Magazine, 2600 El Camino Real, Ste 300, San Northwest Cadence Corp. 20, 21 Mateo, CA 94403. List Rental www.nwcadence.com This publication’s subscriber list, as well as other Quest Software Inc. 13 www.quest.com Legal Disclaimer lists from 1105 Media Inc., are available for rental. The information in this magazine has not undergone For more information, please contact our list manager, SAP AG 13 any formal testing by 1105 Media, Inc. and is distrib- Merit Direct. www.sap.com uted without any warranty expressed or implied. Phone: 914-368-1000 Sybase Inc. 13 Implementation or use of any information contained E-mail: [email protected] www.sybase.com herein is the reader's sole responsibility. While the Online: www.meritdirect.com

        VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 47 0409vsm_RedReview_48.v4 3/19/09 2:36 PM Page 48

        BY ANDREW BRUST

        What’s Old Is New Again When I wrote my first column for this magazine 15 years ago, database work (in other words, almost all .NET developers), this first I covered a new advance in database programmability for Visual cut at SDS didn’t make much sense. Microsoft had turned SQL Server Basic programmers. I’ve been gone from these pages for a while, into a structured storage repository instead of a relational database, but I’m back. And, as an appropriate topic for a return engagement, and had implicitly told developers that if they wanted to move to

        Developer News Developer I focus on another database programming advance, this time for the cloud, they’d need to re-design their databases and re-write .NET developers. their code. Ouch. Back then, I explored something called the VB Compatibility To call Microsoft tone deaf on this issue would be an under- Layer (VBCL), which let VB 3 programmers use version 1.1 of the statement. But eventually the SDS team heard the music, and got Access/Jet Database Engine. VB 3 was the first version of the product the rhythm. On Feb. 23, at the co-located VSLive!/Microsoft to include its own database engine, and the VBCL ensured the Developer Conference in San Francisco, Microsoft hinted that they newest version of that engine would be available to its programmers. would re-jigger the SDS model to be relational, and on March 10 it Compatibility was key then, and it remains so today—as Microsoft announced through the SDS team blog that SDS would, in fact, be a seems to have belatedly realized with its cloud computing strategy. cloud-based SQL Server, accessible via T-SQL over Tabular Data Last month Microsoft announced a major change of course Stream (TDS), SQL Server’s native protocol. Apparently, existing on- for SQL Data Services (SDS), its cloud database offering. Although premises .NET/SQL Server code will work fine with the new SDS; SDS is not yet released, Microsoft is nonetheless giving the tech- only a change in connection string will be necessary to turn SQL nology a completely different programming interface than the one Server code into SDS code. it announced more than a year ago. Back then, Microsoft brought So Redmond listened to its customers, and the bizarre obses- us a product that, while based on a modified version of the SQL sion with copying Amazon’s SimpleDB Web service is over. Microsoft Server we all know, had to be programmed through an interface has given us a truly simple offering: the SQL Server technology that and conceptual paradigm that bore very little resemblance to it. most Microsoft developers have been using for a decade and some have been using since even before my first column was published. What’s old is new, I suppose. For in the cloud to SQL on database technologies as well as colum- Aligning SQL nists. Aligning SQL in the cloud to SQL the ground is about more than just common sense. on the ground is about more than just It’s about getting things done. common sense. It’s about getting things done. Yes, the cloud, done right, will dif- fer from on-premises technology. It will offer dynamic scaling and utility-based Rather than giving us a database with tables, columns and pricing. In short, it will lower the barrier to entry for getting applica- T-SQL, Microsoft instead provided us with the “ACE” model: tions up and running, and keeping them running smoothly. Authorities (which were akin to servers), Containers (akin to But the cloud, done right, will reflect and preserve familiar databases) and Entities (a cross between data records and on-premises technology, too. Because the cloud isn’t just about dictionary objects). The ACE model didn’t have tables, didn’t require how cool it is to run your application “up there.” It’s about easily any consistent schema from Entity to Entity and could be accessed provisioning the servers and services you need to run your busi- only through SOAP and REST Web service interfaces. Microsoft ness down here. SDS 1.0 had its head in the clouds; SDS 1.1 is promised us relational capabilities for SDS, but appeared set on appropriately down to earth. A compatibility layer indeed. VSM providing them by enhancing the ACE model, rather than just giving us direct access to the SQL Server behind the curtain. Andrew Brust ([email protected]) is chief, new technology, The ACE model is good for basic storage and retrieval of data. for consultancy twentysix NewYork, as well as a Microsoft regional director Support for BLOBs means ACE works well for content management and MVP. He’s also the co-author of “Programming Microsoft SQL Server too. But for .NET application developers needing to do mainstream 2008” (Microsoft Press, 2008).

        48 VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com Project1 2/24/09 10:18 AM Page 1 Project1 2/25/09 8:40 AM Page 1

        EVOLVE YOUR CODE. Parallelism breakthrough. Find out what your Windows* apps can really do with Intel® Parallel Studio. 7KLVDOOLQRQHWRROVHWVLPSOLÀHVSDUDOOHOLVPIRUPXOWLFRUH³IURPDQDO\VLV DQG FRPSLOLQJ WKURXJK GHEXJJLQJ DQG WXQLQJ 'HVLJQHG IRU WRGD\·V VHULDO DSSVDQGWRPRUURZ·VSDUDOOHOLQQRYDWRUV

        /HDUQPRUHDQGVLJQXSIRU%HWDwww.intel.com/software/parallelstudio

        © 2009, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and other countries. *Other names and brands may be claimed as the property of others.