VisualStudioMagazine.com

PLUS Four ways to synchronize threads with your app’s UI Inside ’s .NET Rx Framework WINDOWS SURFACES Microsoft’s new client OS is fl ying high, but should you 7 rush to migrate your apps to ? OCTOBER 2009 Volume 19, No. 10 2009 Volume OCTOBER Project5 8/24/09 2:17 PM Page 1 Project5 8/24/09 2:18 PM Page 2 Project6 8/13/09 12:37 PM Page 1

ESRI® Developer Network Integrate Mapping and GIS into Your Applications

Give your users an effective way to visualize and analyze their data so they can make more informed decisions and solve business problems.

By subscribing to the ESRI® Developer Network (EDN SM), 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. October 2009 // Volume 19 // No. 10

Contents { FRAMEWORKS } 14

Michael Desmond, Editor in Chief, Visual Studio Magazine All I Really Need to Know In 1986, author Robert Fulghum published FEATURES the series of essays entitled “All I Really 14 Windows 7 Surfaces Need to Know I Learned in Kindergarten.” The book posited that success in adult life Microsoft’s new client OS is flying high, but does it really make sense can, in fact, come by following the guidance to migrate your apps to Windows 7? we were all given as children. Play nicely with BY MICHAEL DESMOND others. Share your toys. Put things away after you use them. Clean up your own messes. It’s taken 30 years, countless lawsuits and more than a few Steve Ballmer tirades, but it seems that Microsoft has taken many of Fulghum’s insights to heart. Since 21 LANGUAGE LAB announcing the Microsoft Interoperability Initiative early last year, we’ve seen the On VB PAGE 21 company move in a consistent and tangible Threading and the UI direction toward greater openness, Four ways to synchronize threads cooperation and interoperability. with your app’s user interface. You don’t have to be a cynic to spy a BY BILL MCCARTHY profi t motive in all of this. Redmond has

Ask Kathleen PAGE26 never been in the business of leaving Getting Current on MEF money on the table, and some of Microsoft’s Readers explore Managed Extensibility most touted interop eff orts—cough, Open Framework, using callback delegates XML, cough—bear the clear marks of intense and how to create the equivalent of a self-interest. More recently, we’ve pondered C# partial interface in . decisions like Microsoft ending support for BY KATHLEEN DOLLARD its Oracle data provider in ADO.NET, forcing dev shops to seek a third-party provider. Yet, for every Machiavellian maneuver, DEPARTMENTS there’s a jQuery, an ASP.NET Model-View- Controller or a Project. Microsoft 8 DevDisasters seems intent on winning developers from OldMail Method every quarter, be they .NET loyalists who BY ALEX PAPADIMOULIS (THEDAILYWTF.COM) can choose between Windows Presentation 6 Letters to the Editor Foundation and Silverlight, or Linux 10 DevInsight DEVELOPER NEWS, REVIEWS, PRODUCT BRIEFS die-hards who can turn to MonoDevelop or News: .NET Rx Framework: A Watershed Advance Eclipse-based Silverlight tooling. in Asynchronous Programming PAGE 10 Ten or even fi ve years ago, these Product Review: Turbo Charge Visual Studio with DevExpress CodeRush PAGE 12 kinds of cross-platform eff orts would have 31 Index of Advertisers been hard to imagine. Today, it’s hard to imagine Microsoft maintaining the loyalty of the developer community without them. COLUMNS Is Microsoft open enough or does it 3 Frameworks BY MICHAEL DESMOND need to go further? What would you like to see Redmond do to ensure the viability of 32 Redmond Review BY ANDREW BRUST your app dev over time and across platforms?

COVER PHOTO: SHUTTERSTOCK PHOTO: COVER E-mail me at [email protected].

VisualStudioMagazine.com · October 2009 · VISUAL STUDIO MAGAZINE 3 Online Contents

Get the complete picture — the latest dev news, analysis and how-to content—at VisualStudioMagazine.com and our partner sites in the Redmond Developer Network.

VISUALSTUDIOMAGAZINE.COM REDDEVNEWS.COM ADTMAG.COM

PHP Cache Accelerator RDN Express: VS2010 and .NET 4 Oracle 11gR2 Database Released for Windows Unveiled Beta 2 Expected Soon BY JEFFREY SCHWARTZ BY KURT MACKIE BY KATHLEEN RICHARDS Oracle Corp. released the fi rst major The new “Windows Cache Extension for Scott Guthrie, Microsoft’s corporate vice update of its fl agship database in two PHP” solution, currently in beta release, is president of the .NET developer platform, years with an upgrade focused on server an accelerator that works with the PHP answered a wide array of developers’ consolidation, improved storage and engine in Windows and Windows Server. questions in a Linked .NET Users Group extended data warehouse performance. webcast. Of particular interest was the But it remains to be seen what percentage FindIT code: Mackie1009 time frame of the Visual Studio 2010 and of Oracle’s installed base or whether other .NET 4 releases. enterprises will move to the latest version. Classic VB Corner Thoughtful UI Tweaks Can FindIT code: Richards1009 FindIT code: Schwartz1009 Make All the Diff erence BY KARL E. PETERSON Microsoft Releases Preview of IBM Launches Cloud-Based Desktop The diff erence between a successful pro- Windows Embedded Standard 2011 BY JEFFREY SCHWARTZ gram and a complete fl op may come down BY KURT MACKIE IBM Corp. released a virtualized client- to how you treat your users. Here’s how Windows Embedded Standard 2011 is computing off ering it touts as a cloud-based to make sure your app’s UI doesn’t annoy Windows 7-based, supporting both 32-bit desktop. The new service will let business users more than it helps them. and 64-bit x86 hardware. users log in to their desktops from either a thin-client terminal or low-end PC. FindIT code: Peterson1009 FindIT code: MackieB1009 FindIT code: SchwartzB1009 Practical ASP.NET RDN Express: In Sync with the Cloud Databinding Without Tables: BY KATHLEEN RICHARDS Red Hat Launches Linux Release Updates and Deletes The Live Framework SDK, tools and with KVM Hypervisor BY PETER VOGEL controls—including Contacts, MessengerChat, BY JOHN K. WATERS A look at the code required to support IDLoginStatus, IDLoginView and Red Hat Inc. released the fourth update of changing and deleting records. It’s here SilverlightStreaming—will no longer be the Red Hat Enterprise Linux (RHEL) plat- you’ll reap the benefi ts of converting XML available. Live Mesh, which is still in beta, form, which the company is calling the data into a DataTable in a DataSet. remains part of the Azure story. foundation of its virtualization portfolio. FindIT code: Vogel1009 FindIT code: RichardsB1009 FindIT code: Waters1009

VisualStudioMagazine.com RedDevNews.com ADTmag.com

4 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com Project2 8/24/09 10:57 AM Page 1 VisualStudioMagazine.com Letters October 2009 • Volume 19 • No. 10

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

Contributing Editors Not So Clear Andrew J. Brust, Ken Cox, Kathleen Dollard, A VSM reader responds to the September 2009 cover Roger Jennings, Jeff Levinson, Bill McCarthy, Karl E. Peterson, Keith Pleas, Peter Vogel, story on how to use the Repository pattern to eliminate Bill Wagner, Dan Wahlin, dependencies in Test-Driven Development. John K. Waters

Art Staff This approach makes a ton of sense to me if you’re doing Creative Director Scott Shultz data access in the traditional ADO.NET fashion. But I’m not Graphic Designer Erin Horlacher

as clear about how to use it when you’re using something Online/Digital Media like the (EF) for your data access (which Editor, VisualStudio Becky Nagel is obviously another Microsoft-recommended best practice). It Magazine.com Executive Editor, New Media Michael Domingo seems to me that you’d need to throw another two layers on top of the EF- Online News Editor Kurt Mackie generated objects for this to work (the repository plus the object facades), and that Associate Editor, Web Gladys Rama sort of misses the point behind letting the EF do the work for you. In other words, Web Producer Shane Lee I’d appreciate any suggestions on how to use database mocking with the EF. Ken Smith

Woodinville, Wash. President Henry Allain Posted online Vice President, Publishing Matt N. Morollo Director of Marketing Michele Imgrund Online Marketing Director Tracy S. Cook ‘New’ and ‘Diff erent’ Is Windows 7 a fresh start for Microsoft and developers, asked VSM Editor in Chief Michael Desmond in his September Frameworks column. Here are a few of the responses that we received from VSM readers: President & Neal Vitale Chief Executive Offi cer Senior Vice President Richard Vitale How can a company that reinvents its products ever hope to make something & Chief Financial Offi cer work? Had development continued on XP, it could have evolved into Vista and Executive Vice President Michael J. Valenti

everyone would use it. However, it was “new” and “diff erent,” one of which customers fear. Personally, I think Apple has it right. Continue working on your Vice President, Finance Christopher M. Coates & Administration product and refi ne it instead of starting “fresh.” Then, charge a small amount for Vice President, Digital Media, Abraham M. Langer that newer version of what they already know. Watch, OS X users will be Audience Development running 10.6 in a very high percentage. Vista uptake was what ... 26 percent? Vice President, Information Erik A. Lindgren Technology & Web Operations and that was mostly due to forced upgrades when purchasing a new computer Vice President, Digital Media, Doug Mashkuri (no choice but run Vista). My two cents. Advertising Vice President, Carmel McDonagh Jeff , California Attendee Marketing Posted online Chairman of the Board Jeff rey S. Klein

Win7 is defi nitely an improvement, but Vista was never as bad as the media REACHING THE EDITORS made it out to be. The problem was that Microsoft and PC makers misled the Editors can be reached via e-mail, fax, telephone or mail. public into thinking that it could work on hardware that couldn’t really handle it. A list of editors and contact information is available at VisualStudioMagazine.com. So, in the end, I guess it was just poetic justice that Vista got smeared. E-mail: E-mail is routed to individuals’ desktops. Please use ESB the following form: [email protected]. Posted online Do not include a middle name or middle initials. Telephone: The switchboard is open weekdays 8:30 a.m. to 5:30 p.m. Pacifi c Time. After 5:30 p.m. you will be directed to individual extensions. Visual Studio Magazine wants to hear from you! Send us your thoughts San Francisco Offi ce 415-814-0950; Fax 415-814-0961 about recent stories, technology updates or whatever’s on your mind. Irvine Offi ce 949-265-1520; Fax 949-265-1528 E-mail us at [email protected] and be sure to include Corporate Offi ce 818-734-1520; Fax 818-734-1528 your first and last name, city and state. Please note that letters may be edited for form, fit and style. They express the views of the individual Visual Studio Magazine authors, and do not necessarily reflect the views of the VSM editors or The opinions expressed within the articles and other contents herein do not necessarily express those of the publisher. 1105 Media Inc.

6 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com Project2 8/28/09 1:18 PM Page 1

Your best source for software development tools! ®

LEADTOOLS Recognition dtSearch Engine for Win & .NET VMware vSphere SDK v16.5 Add dtSearch‘s “blazing speeds” Put time back into your day. by LEAD Technologies (CRN Test Center) searching and New Your business depends on how you spend file format support Develop robust 32/64 bit document 64-bit your time. You need to manage IT costs Version! imaging and recognition functionality into • dozens of full-text and fielded without losing time or performance. With your applications with accurate and data search options proven cost-effective virtualization solutions high-speed multi-threaded OCR, OMR, and • file parsers/converters for hit-highlighted from VMware, you can: 1D/2D barcode engines. display of all popular file types • Increase the productivity of your existing staff VMware • Supports text, OMR, image, and • Spider supports dynamic and static web data; three tmes over Advanced barcode fields highlights hits with links, images, etc. intact • Control downtime—whether planned or not Acceleration Kit • Auto-registration and clean-up to • API supports .NET, C++, Java, SQL and more; • Save more than 50% on th cost of managing, for 6 processors improve recognition results new .NET Spider API 3 Server Pack • Provided as both high and low Paradise # powering and cooling servers Paradise # level interface V55 78101A01 Paradise # “Bottom line: dtSearch manages a terabyte of D29 02101A08 Make your time (and money) count for more • Includes comprehensive confidence text in a single index and returns results in $ 99 with virtualization from VMware. $ 99 L05 26301A01 reports to assess performance 2,375. 9,234. $ 99 less than a second.” —InfoWorld 3,214. programmers.com/LEAD programmers.com/dtsearch programmers.com/vSphere Pragma Fortress SSH Enterprise Architect 7.5 TX Text Control 15 —SSH Server for Windows Visualize, Document and Word Processing Components NEW RELEASE! by Pragma Systems Control Your Software Project TX Text Control is royalty-free, Contains Windows SSH & SFTP Servers. Certified by Sparx Systems robust and powerful word processing for . Works with PowerShell. Enterprise Architect is a comprehensive, software in reusable component form. integrated UML 2.1 modeling suite • Full-featured server with centralized • .NET WinForms control for VB.NET and C# providing key benefits at each stage of & graphical management • ActiveX for VB6, Delphi, VBScript/HTML, ASP system development. Enterprise Architect • GSSAPI Kerberos & NTLM authentication • File formats DOCX, DOC, RTF, HTML, XML, TXT New 7.5 supports UML, SysML, BPMN and • Fastest SFTP & SCP file transfer other open standards to analyze, design, • PDF and PDF/A export, PDF text import Professional Edition Gen2 Corporate Edition Paradise # Release! • Supports over 1000 sessions test and construct reliable, well under- • Tables, headers & footers, text frames, bullets, 1-4 Users T79 02101A02 • Runs console applications & allows history stood systems. Additional plug-ins are Paradise # structured numbered lists, multiple undo/redo, scroll back within the same session also available for Zachman Framework, sections, merge fields, columns $848.99 Paradise # MODAF, DoDAF and TOGAF, and to SP6 03101A02 • Runs in Windows 2008/2003/Vista/XP/2000 $ 99 • Ready-to-use toolbars and dialog boxes P35 04100A01 integrate with Eclipse and Visual Studio 182. Download a demo today. $ 99 2005/2008. 698. programmers.com/pragma programmers.com/sparxsystems programmers.com/theimagingsource FarPoint Spread Unify SQLBase CA ERwin r7.3 for Embedded Database The Best Grid is a Spreadsheet. Give your users by Unify CA ERwin® Data Modeler the look, feel, and power of Microsoft® Excel®, SQLBase is an easy to deploy database r7.3 – Product Plus 1 Year without needing Excel installed on their machines. for building desktop and Web applications Enterprise Maintenance Join the professional developers around the in server environments without a DBA. world who consistently turn to FarPoint Spread CA ERwin Data Modeler is a data modeling • Small footprint solution that enables you to create and to add powerful, extendable spreadsheet solu- NEW tions to their COM, ASP.NET, .NET, BizTalk Server • Zero admin deployment RELEASE! maintain databases, data warehouses and SharePoint Server applications. • GUI admin and enterprise data resource models. These models help you visualize data • World’s #1 selling development spreadsheet Paradise # • Embed it and forget it structures so that you can effectively • Read/Write native Files P26 04201E01 For applications with encrypted security, Paradise # organize, manage and moderate data • Cross-sheet formula referencing $ 99 Paradise # we offer SQLBase Treasury. C15 03101A01 complexities, database technologies and 3,951. F02 01101A01 • Fully extensible models $ 99 the deployment environment. Reduce your database costs and simplify 143. programmers.com/ca $ 99 • Royalty-free, run-time free 936. maintenance with Unify SQLBase. FREE WEBINAR SERIES: programmers.com/farpoint programmers.com/unify MORE Maximum Data InstallShield 2010 Orion Network Modeling with CA ERwin 7.3 Professional (Windows) Upg Performance Monitor In our last webinar series, we looked at CA by Acresso by Solarwinds ERwin’s core functionality. In this second series, If your software targets Windows®, InstallShield® Orion Network Performance Monitor is a we’ll provide a grounding in how CA ERwin r7.3’s is your solution. It makes it easy to author comprehensive fault and network performance new features help you with Master Data Management, Metadata reliable (MSI) and InstallScript management platform that scales with the Management, Data Warehousing, Data Governance and Business Intelligence. installations and App-V™ virtual packages for rapid growth of your network and expands There will be six sessions in the series: NEW RELEASE! Windows platforms, including the new with your network management needs. • What’s New in CA ERwin 7.3 Windows 7, keeping your customers happy It offers out-of-the-box network-centric views • MDM (Master Data Management) with CA ERwin and Data and your support costs down. that are designed to deliver the critical Profiling tool Upgrade from information network engineers need. InstallShield is the industry standard for MSI • Collaborative model management with CA ERwin ModelManager Active IS Pro + Orion NPM is the easiest product of its IS Pro Silver Mtn installations. Deployed on over 500 million Paradise # • Validate the integrity of your model with CA ERwin Validator desktops worldwide, InstallShield technology lets kind to use and maintain, meaning you Paradise # S4A 08201E02 • Reporting: Crystal Reports, PDF, HTML you author high-quality installations for Windows will spend more time actually managing I21 02301S01 $ 99 and extend them to configure database servers, networks, not supporting Orion NPM. 4,606. • SAPHIR Option: light at the end of the metadata tunnel $1,399.99 Web services, mobile devices, and more. programmers.com/acresso programmers.com/solarwinds REGISTER TODAY: programmers.com/MDM_2009 866-719-1528 programmersparadise.com Prices subject to change. Not responsible for typographical errors.

{ SOFTWARE DEVELOPMENT GONE WRONG }

OldMail Method

fter three long 2004-12-06 13:36 Ainterviews for a Check-in another custom .NET developer e-mail class that interops position, Maxim received a the Microsoft Outlook fairly generous off er and automation objects. accepted it on the spot. 2004-12-06 13:51 Deploy “Now, I don’t to scare to the server and learn that you off ,” Maxim’s soon-to-be Outlook has an anti- boss told him. “But the fella hijacking feature that you’re replacing was good. I requires the user to mean, really good. He could click “Yes” to send an code his way out of anything, e-mail. Learn that, as a and I just don’t want you Web app, the Web user isn’t feeling overwhelmed when you presented with a dialog come in and people are window that pops up on the server. expecting the world from you.” 2004-12-07 07:18 Check-in an attempt Maxim was a little anxious, but he 2004-12-02 13:29 Check in code that to automatically click yes. felt comfortable standing on the shoulders does the following: Programmatically 2004-12-07 09:03 Check-in another of giants. After all, it was a great opportu- execute outlook.exe and wait fi ve seconds attempt to automatically click yes. nity for him to learn how his predecessor for it to load up. With the outlook process 2004-12-07 10:28 Check-in yet another did things. in the foreground, send the following attempt to automatically click yes. When his first day on the job finally keystroke combination to outlook: {ctrl+n}, 2004-12-07 16:22 Install, on the server, came, Maxim loaded up the “Developer [email protected], {tab}, {tab}, Some a newly purchased program called Workstation” instructions and proceeded Subject Line, {tab}, The Message Body, ClickYes that automatically clicks “Yes” to to follow the steps needed to get the {ctrl+enter}. Close the outlook process. those dialogs. company’s flagship application running 2004-12-02 14:07 Deploy to the server on his computer. and learn that it doesn’t work so well. Go NewMail Method As he made his way through the back to the drawing board. Instead of going through the trouble to document, there was one step that 2004-12-03 11:18 Check-in a custom install ClickYes on his workstation, Maxim completely threw him off : “To make sure e-mail class that wraps around the decided to make one more revision to the that e-mails can be sent, install ClickYes, CDONTS [Collaboration Data Objects for SendEmail method. which can be found on the T: drive.” Windows NT Server] . 2009-08-10 11:31 Replace entire method 2004-12-03 12:39 Deploy to the server body with a call to SmtpClient.SendMessage Problematic Execution and learn that, because it’s Windows in System.Web.Mail. Maxim had no idea why such a dependency 2003, it doesn’t have CDONTS installed. After that, Maxim was no longer worried existed for sending e-mail, so he dug into Go back to the drawing board. about being dwarfed by the .NET whiz. VSM the CommonUtils class and navigated to the SendEmail() function. What he found horrifi ed and amazed him. With the change log and source Tell Us Your Tale control history, Maxim was able to reconstruct the trials and tribulations his Each issue Alex Papadimoulis, publisher of the popular Web site The Daily WTF (thedailywtf.com), predecessor, “the .NET whiz,” must have recounts fi rst-person tales of software development gone terribly wrong. Have you experienced the darker side of development? We want to publish your story. E-mail your tale gone through to fi nally master program- to Executive Editor Kathleen Richards at [email protected] and put “DevDisasters” matic e-mail. as the subject line.

8 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com Project1 9/11/09 10:33 AM Page 1

“Intel® Parallel Studio globally speeds up our software products’ time-to-market.”

ERIC ROSIER, VICE PRESIDENT, ENGINEERING, ENVIVIO

Parallelism is not just for HPC. Create rich apps from desktop to device.

Evolve your code.

Free eval version: www.intel.com/go/parallel

© 2009–2010, 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. DEVELOPER NEWS /// REVIEWS

DEVELOPER NEWS .NET Rx Framework “This is a completely new way of perceiving event handlers, delegates and asynchronous programming,” says Julie Lerman, a .NET mentor and the author of the recently released book “Programming Entity Framework” (O’Reilly Media Inc., 2009). “I’m reacting like most programmers. We’re uttering a collective, ‘Oh my god.’ They just peeled something open and showed us something new that has always been there.” Andrew Brust, chief of new technology at twentysix New York, says the Rx Framework solves the challenges inherent in asynchronous programming, which is the model employed in , Silverlight, Microsoft’s Azure, cloud-based services and multi-core/ multi-processor/multi-threaded programming. “It’s an important Framework .NET Rx step in making the delicate parts of AJAX, rich Internet applications, and cloud computing less disruptive to line-of-business program- mers,” Brust says. “Asynchronous programming is really hard,” Lerman notes. “It’s hard for programmers to get their heads around it. Microsoft has been trying to fi nd a way to make it more accessible to developers. In the same way that LINQ has made interacting with data objects easier, the Reactive Framework is going to make interacting with .NET Rx Framework: A events easier. But not only that, it’s going to give us a new level of access to working with events.” Watershed Advance in Microsoft included components of the Rx Framework in the latest version of its Silverlight Toolkit. The biggest chunk is a new Asynch Programming assembly called system.reactive.dll, located in the bin folder of the Silverlight Toolkit Unit Tests. Jafar Husain, a software developer BY JOHN K. WATERS who works on Microsoft’s Presentation Platform Controls team, has This summer Microsoft quietly released the fi rst key components of posted bits of sample code on his blog that can be downloaded and its .NET Reactive (Rx) Framework, which allows developers to write run inside Visual Studio 2008 via the Silverlight SDK. Language Integrated Query (LINQ) expressions against events. “Just by thinking about events and asynchronous complica- Components of the Rx Framework were included in the latest drop tions as collections, I know I have this very powerful mechanism to of the Silverlight Toolkit. A complete version is expected to be part glue these things together,” Meijer said at OSCON. “Really, I’ve just of Visual Studio 2010 and will be supported by .NET Framework 4. sort of rephrased stuff that people have been doing for a long time.” According to language designer Erik Meijer, the Rx Framework He pointed to the Unix shell as an example. “Unix pipelines consists of a pair of interfaces (IObserver/IObservable) that are also an observable collection, because each stage of the represent “push-based” observable collections, along with a library pipeline pushes the value to the next stage,” he said. “The way you of extension methods that implement Microsoft’s LINQ Standard glue these things together is by wiring up these data-fl ow Query Operators and other stream-transformation functions. Meijer networks.” Another example: event-driven state machines in runs the Data Programmability Languages Team at Microsoft, and Windows Workfl ow, which is also a concrete type that implements he outlined the .NET Rx Framework during a session at the recent the Observable interface. O’Reilly Open Source Convention (OSCON) in San Jose, Calif. Meijer has been involved in the development of a wide range Observable collections capture the essence of the subject/observer of languages, including Haskell, Mondrian, X#, Cw, C# and even design pattern, Meijer said, and are especially useful for dealing Visual Basic. He also led development of LINQ, which adds native with event-based and asynchronous programming. data-querying capabilities to .NET languages such as C# and VB. Meijer and software design engineer Wes Dyer have designed As for .NET Rx Framework, Lerman says it will take some what Meijer described as a major breakthrough in asynchronous time to understand. “Be patient while you wrap your head programming: “Of all the work I’ve done in my career so far, this is around this thing,” she suggests. “Once it clicks, it will make the most exciting,” Meijer told session attendees. “I know it’s a bold perfect sense, and it will change the way you think about event statement, but I really believe that the problem of asynchronous handlers and delegates.” VSM programming events has been solved.” Veteran .NET developers agree that the Rx Framework is likely John K. Waters ([email protected]) is a freelance writer based in to change the way developers deal with asynchronous programming. Silicon Valley, Calif. Illustration by Byron Scott by Byron Illustration

10 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com Project7 8/7/09 3:43 PM Page 1

CRYSTAL REPORTS® IT JUST WORKS

A LEADER IN REPORTING More than 5 million units shipped to developers since 1992. THAT WORKS Integrate reports with Java or .NET, access virtually any database, and publish to the Web with support for , , and Internet Explorer. WITH THE LATEST INNOVATIONS Embed Flash to create compelling mashups, manage dashboards and reports on a single server, and share interactive reports affordably via new licensing options. TEST DRIVE IT TODAY: Visit us at sap.com/crystalreports/dev or contact us at 1-888-333-6007. 1996 to 2008

Copyright © 2009 Business Objects SA. All rights reserved. Business Objects and the Business Objects logo and Crystal Reports are trademarks or registered trademarks of Business Objects SA or its affi liated companies in the United States and/or other countries. Business Objects is an SAP company. SAP is a registered trademark of SAP AG in Germany and in other countries.

REVIEW

Turbo Charge Visual Studio with DevExpress CodeRush CodeRush Developer Express Inc. BY PETER VOGEL ture allows you to enter an abbreviation— Web: www.devexpress.com In the September issue of Visual Studio “mb,” for example—and have CodeRush Phone: 818-844-3383 Magazine, we reviewed JetBrains ReSharp- write out the code you need for a message Price: $250; discounts available er, a Visual Studio add-in that provides a box. When you enter the name of a class, when purchasing multiple licenses full range of developer productivity tools. CodeRush will add the Using or Imports Quick Facts: Visual Studio add-in This month, we look at another productivi- statement for the namespace that class be- that provides code analysis, ty-boosting tool for .NET developers: Dev- longs to, provided it isn’t already present. refactoring and other programmer- Express CodeRush 9.2, which includes the And I haven’t discussed the refactoring productivity tools

CodeRush 9.2 CodeRush powerful Refactor! Pro tools from Devel- support included with Refactor! Pro. Pros: Wide range of tools for oper Express Inc. (DevExpress). CodeRush does require commitment. making developers more CodeRush adds several new navigation Many features are accessible through key- productive; includes Refactor! Pro; features to Visual Studio, some of which stroke combinations or through abbrevia- supports both Visual Basic and C# you’ll use once or twice a day, and others tions entered in your code. While the Cons: May be too intrusive; you’ll use dozens of times in an hour. My keystrokes and abbreviations are custom- requires a computer that supports favorite feature could be the “next issue” izable, you’ll have to remember—and re- Visual Studio comfortably function, which lets you cycle through member to use—them. DevExpress does problem areas in your code with just two help you get up to speed with the tool, in- keystrokes. But the feature I might use most cluding a dockable training window, on- ments for Visual Studio, CodeRush worked could be CodeRush’s ability to complete If screen reminders of features you can use fine for me. statements for me. I type in the If key- and mini-training movies (you can turn Because of all the feedback CodeRush word, enter a test, and finish the statement these aids off). offers through icons embedded in your by hitting the Enter key. CodeRush not Installing CodeRush was a snap: I shut code, you may find your screen looks clut- only finishes the statement, but moves my down Visual Studio, double-clicked the tered—and it is, compared to the basic Vi- mouse to the interior of the new If block. DxExperience executable that I down- sual Studio display. I had one co-worker CodeRush also shows you your code in loaded from the DevExpress site, and picked object to structural highlighting new ways. Structure highlighting displays a CodeRush from the tools in the package. because it made the screen too hard to set of brackets that shows where each code To stress-test CodeRush, I installed it on a read. Fortunately, if you don’t find value in block begins and ends, as well as how the slow machine that just barely supported any CodeRush feature, you can turn it off blocks are nested. CodeRush arrows appear standard Visual Studio functionality. I did or customize it. beside any continue, break or Exit state- have responsiveness issues. I’d occasional- CodeRush is more expensive than ment. Click one and it takes you to the code ly find, for instance, that after entering a equivalent programmer-productivity tools, to which the statement transfers control. Namespace, I didn’t get Visual Studio’s In- but it also provides more refactoring sup- Given a chance, CodeRush will even telliSense list of classes. On a computer port than its competitors. It provides com- generate code for you. The template fea- that went beyond the minimum require- parable support to both Visual Basic and C# programmers, a boon for developers using both languages. If you want to see if the tools fit your programming style and you’re using Visual Studio 2008, you can install CodeRush Xpress for free. There’s also a 30-day free trial version of the com- plete package that works with any version of Visual Studio. VSM

Peter Vogel ([email protected]) is a principal in PH&V Information Services, specializing in ASP.NET development with expertise in SOA, XML, database and UI. He’s written several books Click the arrow after the “return” statement, and CodeRush shows where control is on application development using Microsoft tech- transferred to. The popup table at lower-right displays available keystroke commands. nologies and presents at conferences worldwide.

12 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com Project3 3/18/09 9:10 AM Page 1 WINDOWS

14 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com ISTOCKPHOTO.COM Windows 7 FEATURE

SURFACES

Microsoft’s new client OS is flying high, but does it really make sense to migrate your apps to Windows 7? BY MICHAEL DESMOND

VisualStudioMagazine.com · October 2009 · VISUAL STUDIO MAGAZINE 15 FEATURE Windows 7

[the problem] by downloading and extracting the [installation] package on an XP machine, then moving the folder that contained it to a flash drive and carrying it over to Vista,” he explained. “The install on Vista worked fine after that.” Windows 7 has tackled many of the problems that stalled Vista. Stephen Chapman, publisher of the UX Evangelist blog, has been investigating Windows 7 since its early days as a private community technology preview (CTP). “To put it in terms dev shops would like to hear, Windows 7 is Windows XP with the best of ’s visuals and the addi- tion of revolutionary usability components, such as the new Taskbar,” Chapman says. “There’s no negative stigma following around Windows 7. Development went smoothly and Microsoft ran a tight ship to see to it that a Windows Vista snafu wasn’t revisited.” Foley credits the leadership of Division President , who was brought over from the Office group to establish a more disciplined and incremental develop- ment philosophy in the wake of Vista. he Siamese fighting fish that has graced the desktop “Instead of continuously changing the Windows code base— of beta versions of Windows 7 has come to symbolize making the platform a moving target for developers—Microsoft with Microsoft’s latest operating system for many developers. Windows 7 stabilized the product very early. It was API-complete last Like the betta fish itself, Windows 7 is hardly the fall,” Foley explains. “Sinofsky’s discipline and rigor around this Tbiggest marauder in the sea. As prominent industry blogger and approach paid off with Windows 7.” Redmond magazine columnist Mary Jo Foley notes: “Windows 7 is basically—in spite of Microsoft’s claims—a minor update. It is Compelling Case Vista, fixed.” Microsoft touts a host of Windows 7 improvements, including refine- For developers and beta testers, the released to manufacturing ments to the security infrastructure and User Account Control (RTM) of Windows 7 in September marked an overdue watershed. (UAC), optimized I/O handling and trigger-start services that can It has taken three years and untold millions of dollars in lost sales cut down on the number of constantly open background processes and additional development, but Microsoft has finally launched consuming system resources. In fact, performance under Vista was the successor to Windows XP. The question now is, will developers so bad that surveyed developers cited the improved performance flock to it? of Windows 7 as the most exciting aspect of the new OS. The most visible change, however, comes in the form of the Fishing for Insight retooled and feature-laden Taskbar. Under Windows 7, Chapman If readers of Visual Studio Magazine are any indication, the answer says, the Taskbar becomes a focal point for application interaction. to that question is “yes.” We surveyed 450 developers to get their That has major implications for application developers tuning their feedback on Microsoft’s new OS, and were struck by the over- apps for the new OS. whelmingly positive response. Two-thirds of respondents found “Jump Lists, Progress Bars, Custom Switchers, Thumbnail Tool- Windows 7 to be either very or somewhat impressive, while only a bars and Overlay Icons are all pieces of the new Taskbar that you little more than 2 percent described the OS as disappointing. should familiarize yourself with,” Chapman explains. “It may seem What’s more, nearly 60 percent of respondents said they’re either like a lot to take on, but just take a week or two to play with already developing for Windows 7 or expect to start doing so within Windows 7’s new Taskbar. In essence, one could interact completely the next 12 months. Another 18 percent expect to start developing with an application solely through its Thumbnail Toolbars and for the OS in the next 12 to 24 months. Jump Lists.” Those figures are striking when compared to the reported uptake In our survey, respondents asked to name the most compelling of Windows Vista, launched in November 2006. Forrester Research characteristic of Windows 7 singled out fundamental issues like Inc., in its annual hardware survey published in January 2009, found system performance, stability and compatibility. However, the that only 10 percent of PCs in the enterprise were running Vista. enriched Taskbar environment emerged as the most frequently cited In our survey, respondents cited customer install base, lack of feature upgrade in Windows 7. hardware compatibility and problems with the Vista OS as reasons One survey respondent summed it up well: “The user interface for staying with XP. Slightly more than 20 percent of respondents is most impressive, but the added security and stability that we’ve said they were actively supporting Vista. Notably, when survey par- seen with the testing we’ve conducted have been extremely impres- ticipants were asked to specify the one aspect of Windows 7 that sive, to say the least.” they were most excited about, a large number basically responded: Developers also singled out the new Multi-Touch user inter- “It’s not Vista.” face, which provides a standard way to enable rich, touch-screen One respondent claimed interoperability issues with SQL Server interaction with Windows applications. “We write software for a CE 2.0 forced his shop to stay on XP, while another described manufacturing environment, with exclusive use of touch screens installation and program download issues with Vista machines for user I/O, so we’re extremely excited about Multi-Touch UI,” that ultimately reduced his shop to sneaker net. “We got around wrote one respondent.

16 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com Project2 9/8/09 11:39 AM Page 1 FEATURE Windows 7

For her part, Foley says she hasn’t seen a lot of grassroots IF YOU’VE WORKED WITH WINDOWS 7, WHAT’S YOUR developer interest in Multi-Touch. In fact, she says, developers OPINION OF THE NEW OS AS A DEV TARGET? seem focused on making sure their current bits will work under Very Impressive 38.7% the new regime. Somewhat Impressive 27.4% “Microsoft is trying to drum up support for new apps that will Somewhat Disappointing 2.0% use the touch/gesture/sensor capabilities built into Windows 7, Very Disappointing 0.2% 31.7% but I haven’t heard developers clamoring to get on board that No Opinion/Don’t Know train,” Foley says. “I think most folks are more fixated on making sure apps that work on Vista still work on 7, and apps that work on HOW SOON—IF EVER—DO YOU EXPECT YOUR DEV SHOP TO START DEVELOPING FOR WINDOWS 7? XP can run at least via XP Mode, if not via some kind of port or update to Win 7.” Already Underway 13.1% The situation is somewhat reminiscent of Microsoft’s effort to Next 3 Months 25.8% 19.8% promote Windows Presentation Foundation (WPF), Windows Com- Next 3-12 Months Next 12 to 24 Months 18.0% munication Foundation (WCF) and Windows Workflow Foundation Later than 24 Months 6.0% (WF) development on Windows Vista. Foley says she hasn’t seen Never 4.0% many WPF-, WCF- or WF-optimized apps. “It’ll be interesting to see Don’t Know 13.1% if rich, fat-client apps materialize for Win 7,” she notes. WHAT IS YOUR LEVEL OF EXCITEMENT ABOUT THESE Native Son SPECIFIC WINDOWS 7 FEATURES? *

Even as Microsoft touts new features of Windows 7, the tooling to Improved Security Infrastructure 100 take advantage of these improvements remains in progress. Windows Optimized I/O Handling 98 7 ships with .NET Framework 3.5 Service Pack 1 (SP1), but many Power-Efficient Infrastructure 92 new features in Windows 7 aren’t supported in this iteration of Updated Graphics Stack and High DPI Support 92 Microsoft’s managed-code framework. .NET-based support for Extended Taskbar Functionality 91 Jump Lists, Multi-Touch UI, Sensor and Location platform and Multi-Touch Gesturing UI 83 81 other new functionality will arrive with .NET 4, expected to ship Trigger-Start Services 77 alongside Visual Studio 2010 early next year. Sensor and Location Platform In the meantime, Microsoft has provided the Windows 7 API *WEIGHTED-VALUE SCORE Code Pack for .NET for free download. The successor to the Windows Vista Bridge project, this library of managed-code wrappers lets form ; and Direct 3D 11.0, as well as earlier versions. The .NET developers access native code libraries in Windows 7 that Code Pack also addresses Windows 7 Libraries and Shell, the aren’t recognized by the current .NET Framework. Explorer browser, and Windows 7 and Vista Common File and Among the supported features in the API Code Pack: Taskbar Task dialogs. Support for ribbon toolbars and Multi-Touch is features like Jump Lists, Progress Bar and Overlay; Sensor Plat- not present.

Windows 7: Thick or Thin

For better or for worse, Windows 7 could be All About Microsoft blogger Mary Jo Foley Strategies at analyst firm Directions on the first major desktop OS of the Internet doesn’t think so. She says Google’s Chrome Microsoft, says interest in building new thick- application age. OS effort for a Web-optimized OS has client apps from scratch is fading. “Although Microsoft has tuned Windows 7 with developers intrigued, but until something Windows 7 and WPF [Windows Presentation plenty of rich functionality and impres- tangible ships, it has little impact on decision Foundation] will get attention, it won’t be sive application-integration opportunities. making. “It seems the RIA dev community enough to change the momentum toward From Taskbar Jump Lists and Progress and the .NET/Windows dev community are Web apps and RIAs,” Sanfilippo says. Bars to advanced power management building different kinds of apps with different “Microsoft is doing as much as they can and flexible file and content access via goals,” she says. technology-wise to allow cutting-edge Libraries, Windows 7 is as impressive as Bola Rotibi, principal analyst for research thick-client development with the improve- it is deeply featured. firm Macehiter Ward-Dutton Ltd., agrees ments in WPF, and [with] the Visual Studio But these innovations come at a time that browser- and RIA-based environments 2010 RAD tools that will allow developers when developers are increasingly turning have grown sophisticated, but they’ve to do WPF design,” he explains. “In-process, to Web-deployed apps that offer a smaller yet to close the gap on desktop environ- side-by-side support in .NET 4 will help the footprint and much easier deployment and ments. “The desktop still provides a level of .NET Client Profile be usable in many more management. With Silverlight 3 and other processing and sandboxing that has not yet scenarios. WinForms will get continued sup- rich Internet application (RIA) platforms been fully achieved in the aforementioned port as well, and Direct2D is an interesting enabling rich interaction and robust code technologies,” Rotibi explains. non-WPF play that will keep GDI alive for delivery, might dev shops fail to target Not everyone agrees. Rob Sanfilippo, some time.” Windows 7? research VP for Development Tools and —M.D.

18 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com PureVisual Studio and .NET

GET TIPS GET CODE GET THE BEST HOW-TO ARTICLES ON THE NET

Visit VisualStudioMagazine.com and RedDevNews.com FEATURE Windows 7

“Instead of continuously changing the Windows code base—making the platform a moving target for developers—Microsoft with Windows 7 stabilized the product very early.” Mary Jo Foley, All About Microsoft

Rob Sanfilippo, research vice president for Development Tools “Even though it’s my understanding that the Multi-Touch UI and Strategies at analyst firm Directions on Microsoft, says the API will be available in .NET 4, we can continue to build our busi- lack of .NET support for new Windows 7 features won’t blunt ness objects using .NET 3.5 and implement the UI in .NET 4,” said early development. one developer. “Regarding the Windows 7 API Code Pack, I think this is an acceptable stopgap between Windows 7 and .NET 4 RTM for the Swimming Upstream first wave of Windows 7 developers. It provides access to many of In fact, Microsoft has been aggressive in managing the inevitable the interesting new features in Windows 7, such as Jump Lists and transitions that are part of the Windows 7 launch. Windows 7 Pro- other new Taskbar functionality, although it does miss a couple of fessional, Ultimate and Enterprise editions offer Windows XP Windows 7 features like ribbon toolbars and Multi-Touch,” Mode, a virtual instance of XP that allows XP-compatible apps to Sanfilippo says. “The Code Pack, along with the available .NET 4 run natively on Windows 7 desktops. The capability should enable beta and Windows 7 SDK, should get .NET and native code devel- dev shops to maintain a single app code base for XP and Windows opment teams ramped up before the Visual Studio 2010 wave of 7 clients. products ships by the middle of 2010. So I don’t think there’s a Microsoft is also touting the ability for .NET developers to need to delay planning and initial development on the new plat- write Windows 7-savvy applications that scale across all three form,” he adds. contemporary OSes: XP, Vista and Windows 7. In a blog post, Some developers, however, were upset to learn that .NET Microsoft Senior Product Manager Scott Hanselman describes coders must wait to gain access to features available to native C PhotoView, an XP to Windows 7 (XP2Win7) reference applica- and C++ programmers. tion that taps the available features and resources of each OS to “This is a bugbear of mine,” wrote Kevin Daley, a New Zealand- provide an optimal experience without requiring discrete code. based developer. “I attended PDC [the Microsoft Professional PhotoView is a WPF-based image viewer that runs on XP. Developers Conference] 2003 where we were given a very clear When running on Vista, the app is able to hook into the UAC message that Microsoft expected developers to go with .NET infrastructure for security configuration. When running on over native code for everything above the level of device drivers Windows 7, the app provides Jump Lists, interacts with and so on. This was an excellent idea, but sadly it was abandoned. Windows 7’s robust power management, enables rich Taskbar Vista shipped with more native libraries, and Windows 7— iconography and takes advantage of Windows 7 Libraries— which I love, by the way—with a truckload. The .NET wrappers essentially metafolders that provide flexible and intelligent file are an afterthought.” and content storage. The sample app and source code can be Has Microsoft turned its back on managed-code development? found at http://tinyurl.com/ltxfrd. Not a chance, says Sanfilippo. The upshot is that dev shops can successfully write apps that span “The support for native code libraries that continues for Windows XP, Vista and Windows 7, while taking advantage of the extended 7 isn’t surprising, since a large portion of new Windows applica- features and capabilities available in the newest Windows OS. tions, including Microsoft’s own offerings, don’t employ the .NET The combination of Windows 7’s XP Mode and scalable feature Framework,” he explains. “I wouldn’t go as far to say this is a support should help dev shops struggling with legacy code to reversal of Microsoft’s .NET vision, but the reality is there are move forward more decisively. many development teams that will take more time to gradually “To be honest, we love XP. In our opinion, Vista was just not cut adopt .NET—and some that will never adopt it.” out to be a business-oriented operating system,” wrote one devel- Bola Rotibi, analyst for U.K.-based research firm Macehiter oper. “We agree that it’s time to retire XP. The question is: Can Ward-Dutton Ltd., says any effort by Microsoft to iron out all Windows 7 reach that goal?” interdependencies between the OS and framework would result UX Evangelist’s Chapman says absolutely. “Windows 7 is every- in very long release cycles—the very thing that helped tank Vista. thing great about both XP and Vista. All it needs is exposure,” he Like Sanfilippo, she says the API Code Pack offers a sound transi- says. “Having used it for my main OS since beta 1, I can vouch for tion for .NET coders. its stability, capabilities and what will hopefully be longevity.” “So long as Microsoft is able to ensure that there’s a smooth tran- Between the emphatic feedback from Visual Studio Magazine sition from those using the API Code Pack to .NET 4 when it readers and the positive insight of industry watchers, it seems that becomes available, as well as minimize the potential for rework, [it with Windows 7 Microsoft may have finally created a desktop OS will be OK],” says Rotibi, who adds that developers must architect worth targeting again. their applications to streamline this transition. Perhaps we were all wrong about the little betta fish on the The developers we surveyed seemed generally unconcerned Windows desktop background image. The play on words may not about the delay. Only 26 percent of surveyed respondents said have been on “beta,” but on “better.” As in, a better Windows. VSM they were disappointed that .NET 4 was not part of the Windows 7 launch. Many simply want Microsoft to ensure that its platforms Michael Desmond ([email protected]) is editor in chief of Visual and frameworks are fully cooked before they ship. Studio Magazine.

20 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com

IN THIS SECTION: On VB · 21 // Ask Kathleen · 26 ////////////////////////

{ C#CORNER }

Threading and the UI Private Sub SomethingChanged( _ Four ways to synchronize threads with your app’s user interface. ByVal sender As Object, _ BY BILL MCCARTHY ByVal ev As EventArgs)

When Visual Basic moved to the .NET platform it gained support If Me.InvokeRequired Then for free threading, allowing you to easily spawn new threads in Me.Invoke( _ Sync and Sync

your application, control synchronization and—most importantly— New EventHandler(Of EventArgs) _ UI Thread be able to debug multi-threaded applications. But two old adages (AddressOf SomethingChanged), _ apply here: “There’s no such thing as a free lunch” and “With great sender, ev) power comes great responsibility.” As long as UI’s remain limited Return to the one thread, there remains the need to synchronize thread End If notifications back to the UI thread. MsgBox("this is on the UI thread") For those familiar with VB6, you probably remember the End Sub Coffee sample application that shipped with VB6 demonstrating how to use an active thead for background threading. Com- If the SomethingChanged method is called on the UI thread, the pared to .NET it was a lot of rigmarole. You had to call an InvokeRequired property of the Form returns False and the code ActiveX .EXE, and in that spawn a timer or something similar to jumps straight to the message box call. If, however, the method is then start your second thread. And you had to use multiple called from another thread, then InvokeRequired would be True instances of the VB6 IDE to get any semblance of debugging to and the Form’s Invoke method is used to call the Some- work. These limitations, which are manifestations of the VB6 thingChanged method again, this time on the UI thread. You can apartment-threading model, made creating threads painful. But apply this simple pattern in any event handler or method you at the same time, they allowed VB6 to hide the marshalling that expect might be called from a non-UI thread. was going on: In your main application the event notifications A second approach you can employ is to use the Background- were all on the UI thread. Worker component. The BackgroundWorker component first Fast forward to Visual Basic.NET, where you can easily create shipped with .NET 2.0 and is in the Windows.Forms namespace. threads: The VB.NET compiler and runtime don’t force you to It wraps the threading by exposing events DoWork, Progress- work on a single thread. The power and freedom to control Changed and RunWorkerCompleted. The DoWork event is raised threads puts the onus back on you to ensure that notifications are on a new thread allocated from the thread pool, whereas the Pro- marshaled to the UI thread when necessary. gressChanged and RunWorkerCompleted events are raised on the You need to be aware of the different ways you can achieve context of the initialization of the component, which when used synchronization with the UI and apply the right technique on an with a control or form will be the UI thread. as-needed basis. There are a number of techniques you can use, You launch the BackgroundWorker process by calling its Run- but I’ll show you four that cover the vast majority of cases you’ll WorkerAsync method: come across. The first and perhaps simplest technique is to use the Control. BackgroundWorker1.RunWorkerAsync Invoke method to marshal the call over to the UI thread. You first check to see if InvokeRequired is true, and if it is you call Control. In the DoWork event handler, you write the code you want to run Invoke. You can pass to Control.Invoke a delegate, which points to on the background thread. In that code you can opt to raise prog- the same method you’re currently in, but when it gets called via ress changed events by calling ReportProgress. You can also opt to Invoke it will be on the UI thread. handle any cancel request and terminate the thread early:

The power and freedom to control threads put the onus back on you to ensure that notifications are marshaled to the UI thread when necessary.

VisualStudioMagazine.com · October 2009 · VISUAL STUDIO MAGAZINE 21

{ C#CORNER }

Private Sub BackgroundWorker1_DoWork( _ Public Class BindingSourcePlus ByVal sender As Object, _ Inherits BindingSource ByVal e As DoWorkEventArgs) _ Handles BackgroundWorker1.DoWork Protected Overrides Sub OnListChanged( _ ByVal e As ListChangedEventArgs) 'do the async work here 'Your code to synchronize the threads goes here For i As Int32 = 1 To 100 End Sub If BackgroundWorker1.CancellationPending Then e.Cancel = True End Class e.Result = Nothing Return There are a few options available to you to synchronize the threads. End If One approach you can use is to examine the BindingSource’s Cur- BackgroundWorker1.ReportProgress(i) rencyManager property, then from the CurrencyManager get the Next Bindings property, then enumerate the bindings and get the Con- e.Result = "anything you want to pass to" + _ trol property of each and see if InvokeRequired is True. If so, you

Sync and Sync "the completed event" UI Thread use the control’s invoke method: End Sub Private Function GetInvokeRequiredControl() _ You then handle the ProgressChanged and RunWorkerCompleted As Control events, updating the UI as required. If Me.CurrencyManager IsNot Nothing AndAlso _ These two techniques, Control.Invoke and use of the Back- Me.CurrencyManager.Bindings IsNot Nothing Then groundWorker, are suitable for cases where you’re imperatively For Each bind As Binding In _ modifying the UI from an event or notification that occurs on Me.CurrencyManager.Bindings another thread. If the BackgroundWorker pattern suits your Dim cntl As Control = bind.Control application model—when, for example, you have control over the If cntl IsNot Nothing AndAlso _ thread start—it makes your code a lot clearer and easier to main- cntl.InvokeRequired Then tain compared to making calls to Control.Invoke. Save calls to Return cntl Control.Invoke for the cases where you don’t have control over the End If thread start. Next Control.Invoke and BackgroundWorker only come into play End If when you’re directly intercepting the events or notifications. You Return Nothing marshal that notification to the UI thread and then, as needed, End Function alter the control’s properties. That’s imperative style coding. In the case where you’re data binding and the properties of your data Protected Overrides Sub OnListChanged( _ change on another thread, you don’t have the methods in your ByVal e As ListChangedEventArgs) form’s code to intercept. For data binding, you need to take a Dim cntl As Control = GetInvokeRequiredControl() slightly different approach. If cntl IsNot Nothing Then In .NET 2.0 Microsoft added the BindingSource component cntl.Invoke(New Action(Of ListChangedEventArgs) _ to serve as a brokerage between your data and the form’s data ( AddressOf OnListChangedInvoke), e) bindings. When you drag and drop data from the data window Else onto a form, a BindingSource is added to the form’s components. OnListChangedInvoke(e) The BindingSource is the perfect place to intercept change noti- End If fications from your data and ensure that notification is bubbled End Sub up onto the UI thread. The BindingSource provides notifications to the form’s data bindings via the IBindingList interface. IBind- Private Sub OnListChangedInvoke( _ ingList only has one event notification: ListChanged. Hence the ByVal e As ListChangedEventArgs) perfect place to intercept the thread is in the BindingSource’s MyBase.OnListChanged(e) OnListChanged method. End Sub You can do this by deriving from BindingSource and overriding the base OnListChanged method: Although this code works, it’s far from optimal. The problem is it looks at each binding and its control property. In the cases where Imports System you aren’t using threading, the code would have to cycle through Imports System.ComponentModel all the bindings. You could optimize it by making assumptions Imports System.Threading such as: If the first control doesn’t require invoke, none of the Imports System.Windows.Forms others will. You can’t cache whether the control requires invoke or not, because the notification could come on a different thread _ and the controls might be added or removed. A trap for the

22 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com { C#CORNER }

unwary is that the OnListChanged method is raised when the Alternatively, you can use Quick Replace to replace all binding source is first instantiated, before any of the bindings instances of “System.Windows.Forms.BindingSource” with have been added. “BindingSourcePlus.” Make sure your search options include In the custom binding source component that I use these searching in hidden files. You should have two replacements days, I don’t iterate through the bindings at all. Rather, I make per binding source. the assumption that binding source is instantiated on the UI Another technique to use instead of a custom binding source thread. Based on that assumption, I store a Synchronization- is to make your data raise change notifications on the Synchroniza- Context in the constructor, and later I use it to invoke the tionContext. This approach takes the onus off anyone developing ListChanged notification. UIs for your data; however, it does require adding code to your The SynchronizationContext class was added to .NET Frame- data class. work in version 2.0 to simplify asynchronous operations. You In particular, this method requires that you declare the Prop- use the SynchronizationContext’s Post method to invoke notifi- ertyChanged event using custom events. This requirement cation asynchronously. That is to say, if the notification is on a means you have to put the synchronization code in the base class different thread from the UI’s SynchronizationContext, the Post that implements INotifyPropertyChanged. method will invoke that notification asynchronously back to the The PropertyChanged event is at the heart of the data binding UI thread. change notification. Typically a simple implementation pattern Using the SynchronizationContext, the custom binding source checks to see if the underlying value of a property is changed, and class can be written thus: if so it raises a PropertyChanged event: Sync and Sync UI Thread Imports System Public Class TestDataObject Imports System.ComponentModel Implements INotifyPropertyChanged Imports System.Threading Imports System.Windows.Forms Private _Name As String

_ Public Property Name() As String Public Class BindingSourcePlus Get Inherits BindingSource Return _Name End Get Private _context As SynchronizationContext Set(ByVal value As String) Private _postback As New SendOrPostCallback( _ If _Name <> value Then AddressOf Me.OnListChangedPost) _Name = value OnPropertyChanged("Name") Public Sub New(ByVal container As IContainer) End If MyBase.New(container) End Set _context = AsyncOperationManager _ End Property .SynchronizationContext End Sub Protected Sub OnPropertyChanged( _ Protected Overrides Sub OnListChanged( _ ByVal propertyName As String) ByVal e As ListChangedEventArgs) RaiseEvent PropertyChanged(Me, _ If _context Is Nothing Then New PropertyChangedEventArgs(propertyName)) MyBase.OnListChanged(e) End Sub Else _context.Post(_postback, e) End If Public Event PropertyChanged As _ End Sub PropertyChangedEventHandler Implements _ INotifyPropertyChanged.PropertyChanged Private Sub OnListChangedPost(ByVal e As Object) MyBase.OnListChanged( _ End Class TryCast(e, ListChangedEventArgs)) End Sub To make the PropertyChanged event fire on the Synchroniza- tionContext of the listening code, you will need to modify the End Class PropertyChanged event declaration to a custom event handler. To do this, simply put the keyword Custom before the Event key- Once you’ve added the BindingSourcePlus component to your word and then hit enter at the end of the line. The IDE will add project, you need to modify any designer-generated binding the custom AddHandler, RemoveHandler and RaiseEvent stubs sources to be of your custom binding source type. To do this you for you: can click on the “Show All Files” button in Solution Explorer, expand the forms in the tree view, open their .designer.vb file and Public Custom Event PropertyChanged As _ manually make the changes in there. PropertyChangedEventHandler Implements _

VisualStudioMagazine.com · October 2009 · VISUAL STUDIO MAGAZINE 23

{ C#CORNER }

INotifyPropertyChanged.PropertyChanged End If AddHandler(ByVal value As _ _context.Post(propertyChangedPost, _ PropertyChangedEventHandler) New Args(sender, e)) End AddHandler End If End Sub RemoveHandler(ByVal value As _ PropertyChangedEventHandler) Private Sub OnPropertyChangedPost( _ ByVal state As Object) End RemoveHandler Dim args = CType(state, Args) _handler.Invoke(args.sender, args.ev) RaiseEvent(ByVal sender As Object, _ End Sub ByVal e As PropertyChangedEventArgs) Private Class Args End RaiseEvent Public sender As Object End Event Public ev As PropertyChangedEventArgs

Sync and Sync Public Sub New(ByVal senderObject As Object, _ UI Thread In the AddHandler block you need to store the handler being ByVal e As PropertyChangedEventArgs) passed in, and at that point in time also store the Synchronization- Me.sender = senderObject Context to be used later when raising the event. As each handler Me.ev = e may have a different context, you’ll need to have a storage class for End Sub each handler and its context: End Class End Class Public Class PropertyChangedEventContext Private _handler As PropertyChangedEventHandler The PropertyChangedEventContext class exposes a Raise method Private _context As SynchronizationContext that does all the checking to see if the SynchronizationContext is nothing or not, and invokes the delegate accordingly. After you Public Sub New(ByVal handler As _ add the PropertyChangedEventContext class to your project, go PropertyChangedEventHandler) back to your custom PropertyChanged event code and modify _handler = handler as follows: _context = SynchronizationContext.Current End Sub Private _propertyChangedHandlers As _ New List(Of PropertyChangedEventContext) Public ReadOnly Property Handler() As _ PropertyChangedEventHandler Public Custom Event PropertyChanged As _ Get PropertyChangedEventHandler Implements _ Return _handler INotifyPropertyChanged.PropertyChanged End Get AddHandler(ByVal value As _ End Property PropertyChangedEventHandler) _propertyChangedHandlers.Add(New _ Public Sub Raise(ByVal sender As Object, _ PropertyChangedEventContext(value)) ByVal e As PropertyChangedEventArgs) End AddHandler Static propertyChangedPost As SendOrPostCallback If _context Is Nothing Then RemoveHandler(ByVal value As _ _handler.Invoke(sender, e) PropertyChangedEventHandler) Else Dim i as Int32 If propertyChangedPost Is Nothing Then For i = _propertyChangedHandlers.Count - 1 _ propertyChangedPost = New _ To 0 _ Step -1 SendOrPostCallback( AddressOf OnPropertyChangedPost) If _propertyChangedHandlers(i).Handler _

An alternative to using a custom binding source is to make your data raise change notifi cations on the SynchronizationContext. This approach takes the onus off anyone developing UIs for your data.

24 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com Instantly Search Terabytes of Text Is value Then _propertyChangedHandlers.RemoveAt(i) N 25+ full-text Return 'remove only the last one and fielded End If data search Next options (with End RemoveHandler Unicode RaiseEvent(ByVal sender As Object, _ support for ByVal e As PropertyChangedEventArgs) hundreds of For Each item In _propertyChangedHandlers international item.Raise(sender, e) languages) Next End RaiseEvent N Built-in file End Event parsers / converters Your class will now raise its PropertyChanged events on the highlight hits same context from which the event listeners were added. For a in popular Windows.Forms application this will typically be the UI thread, as the binding is all done in the form’s designer- file types generated code. N Spider Although this last approach seems to be a bit of code, once supports Desktop with Spider you have added the PropertyChangedEventContext to your project, you only need write the custom event code. To make static and Network with Spider your life even easier, you can use a snippet for the custom dynamic Publish (portable media) event code: I’ve included one such snippet with the sample web data; code that accompanies this article, which you can find online highlights WebWeb with Spider includes at VisualStudioMagazine.com. hits with In this article you’ve learned about four different ways to links, Engine for Linux 64-bit achieve threading synchronization with your application’s UI: formatting use Control.Invoke or the BackgroundWorker when coding Engine for Win & .NET imperatively; use a custom binding source when you’re data and images binding and you can’t modify the actual data classes; or modify intact your data classes to raise the PropertyChanged event using a N API supports .NET, C++, Java, SQL, etc. SynchronizationContext. In the future some of this maybe further simplified. Concurrent .NET Spider API Basic, which is an experimental version of VB designed with threading at its heart, has a nice declarative way to mark a method The Smart Choice for Text Retrieval® as being invoked on the UI thread. You simply add a attri- bute to the method declaration and the compiler will add the since 1991 necessary code to marshal calls back to the UI thread when calling that method. “Bottom line: dtSearch manages a terabyte For more on some of the exciting new frontiers of VB with of text in a single index and returns results concurrency, check out the Concurrent basic research site at in less than a second” — InfoWorld http://tinyurl.com/lkuuzm. dtSearch “covers all data sources … Bill McCarthy ([email protected]) is an independent consultant powerful Web-based engines” — eWEEK based in Australia and is one of the foremost .NET language experts specializing in Visual Basic. He has been a Microsoft MVP for VB for the “Lightning fast ... performance was last nine years, and sat in on internal development reviews with the unmatched by any other product” Visual Basic team for the last five years, where he helped to steer the — Redmond Magazine language’s future direction. See www.dtsearch.com for hundreds GO ONLINE more reviews, and hundreds of developer VisualStudioMagazine.com Use this FindIT code at to go directly case studies to these related resources.

READ & DOWNLOAD Fully-Functional Evaluations McCarthy1009 Read this article and download the sample code online. 1-800-IT-FINDS • www.dtsearch.com

VisualStudioMagazine.com · October 2009 · VISUAL STUDIO MAGAZINE 25

{ ASK KATHLEEN }

Getting Current on MEF be confusing if the target was a derived type. Because of the open Readers explore Managed Extensibility Framework, using source release of early MEF previews, this design issue was discov- callback delegates and how to create the equivalent of a C# ered and addressed. partial interface in Visual Basic. The Import attribute now refers only to single imports—zero- BY KATHLEEN DOLLARD to-one and exactly-one cardinalities. A new ImportMany attribute declares zero-to-many cardinality. If you use the Import attribute Q: I read your article on Managed Extensibility Framework (MEF), on a type declared as IEnumerable, MEF will search for but I heard there have been changes to the way MEF works. Can you exactly one IEnumerable list. If you use the ImportMany attribute explain these changes? on an IEnumerable type, MEF will supply an IEnumerable that contains all parts that export the type T. The second approach A: Microsoft’s Managed Extensibility Framework in general still of filling the IEnumerable with matching parts is the more common works the way I described in my earlier article (“Working with case. Listing 1 (p. 28) illustrates this distinction. MEF Update MEF,” April 2009). That article used one of the CodePlex pre- This version of MEF also changes composition behavior with a views. It looks like MEF Preview 6 is getting close to the final new feature called Stable Composition when there are nested .NET 4 feature set, so it’s worth looking at how these changes parts. A nested part is simply an import within another part. In affect your code. MEF continues to work in .NET 3.5 as well. earlier versions, if a cardinality rule with a nested part couldn’t be There have been syntax changes and a major change to how MEF met—for example, if a part was not available for a cardinality of behaves when parts are missing. exactly one—an exception occurred with a plethora of informa- I’ll review a couple aspects of MEF as groundwork for explaining tion on what was causing the issue. A nested part is simply an these enhancements, but if you’re new to MEF please read my import on a part. This stopped composition and would generally April article, which you can find on VisualStudioMagazine.com block proper function of your application. With Stable Composition, using FindIT code Dollard1009. You’ll see these changes in MEF parts that have missing nested parts won’t appear in the catalog. Preview 6 and beyond, and they’ll also be reflected in Visual Information about the missing part is retained, and if the nested Studio 2010 starting with beta 2. While MEF is moving close to part later becomes available through additional composition, the lockdown for .NET 4, additional changes may still occur. containing part will appear in the catalog. The reverse doesn’t Note that Visual Studio 2010 beta 1 is based on an older MEF occur. If a part is in the catalog and may be in use, an exception preview than the one that I’m describing here. You can use MEF occurs if you attempt to remove a required nested part. Preview 6 with beta 1 if you download and explicitly reference While Stable Composition is a step forward, it’s a sword that its assemblies. cuts two ways. It keeps systems from crashing on certain types of Before looking at recent changes, I need to cover an aspect of errors in composed parts—parts that might not be under the con- MEF I touched on lightly in the earlier article. Cardinality refers to trol of the application. On the other hand, errors that would have how many of something is legal—in other words, the legal count. appeared as exceptions with full information are now silent fail- MEF supports cardinality of zero or one, exactly one, and zero to ures with the containing part simply missing from the catalog. many. Some of the recent syntax changes involve how MEF man- If you’ve been working with an earlier version of MEF, including ages cardinality. Visual Studio 2010 beta 1, the combination of changing how With a cardinality of zero to many, MEF returns anything that Import works with an IEnumerable and Stable Composition may matches the request—which generally means matching a specific cause some debugging headaches. The team is working on tools interface. In early previews, MEF used the target type to for tracing and debugging, but the core issue is that you’ll see the determine whether the intended cardinality was exactly one or failure at a high level in a missing part, while the real issue is zero to many. If the target was an IEnumerable, MEF assumed buried rather deep in composed parts. It’s important to search zero-to-many cardinality. If the target type was not an IEnumerable, projects that use MEF from earlier previews and beta 1 for the MEF assumed a cardinality of exactly one. This was a flawed combination of the Import attribute and an IEnumerable, and design. The major issue is that this excludes import of a list as a change these to ImportMany. You must also ensure any IEnumerable single import—it prohibits you saying, “there should be exactly parameters on a constructor marked with the ImportingCon- one list available.” In addition to being overly restrictive, it could structor attribute have the ImportMany attribute as well.

If you’ve been working with an earlier version of MEF, including Visual Studio 2010 beta 1, the combination of changing how Import works with an IEnumerable and Stable Composition may cause some debugging headaches.

26 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com { ASK KATHLEEN }

Although it’s tedious to ensure this change manually, it’s easier Q: I’m creating an application using code generation and I want to than debugging a complex system under Stable Composition. add new features to a generated interface. However, interfaces don’t The updated version of MEF also has naming changes. support partial method—at least in Visual Basic. I want to do this Export becomes Lazy to clarify its purpose of late cre- because I’m using an IoC container in a Model-View-ViewModel ation of the contained part. The GetExportedObject method design, and I want to generate the properties and known methods. is replaced with a functionally equivalent Value property. However, I also need to add additional items to the interface to sup- The ExportCollection is removed in favor of the simpler port custom behavior. How can I work around this limitation? approach of using an IEnumerable>. It may at first seem odd to see a nested generic like this, and FxCop/ A: C# supports partial interfaces and VB does not. But in this case, Code Analysis has traditionally complained about the com- you need some control of the template in either language, and the plexity of such constructs in your code. They certainly don’t result is similar. Because C# supports partial interfaces, you can deserve wide use, but this is one example of where the direct directly create a partial interface. However, because C# requires inclusion of the nested generic provides more clarity than a wrapping type. If you’re faced with a similar situation in your own generics, consider whether the person reading the code is aided by understanding the nested generic type—which, in this case, they are. In my April article I demonstrated the use of custom metadata attributes. In this newest version of MEF, there’s a subtle but important change that can lead to clearer code for people creating exports of parts you define. The ExportAttribute class was unsealed. If you create a custom ExportAttribute with a MetadataAttributeAttribute and a meaningful name in the context of your system, exporting classes will be marked with their actual intent. The MEF usage will be hidden. For example, if Tem- plateData includes the MetadataAttributeAttribute, the Export attribute is no longer needed:

_ _ Partial Public Class Validation

In my April article I discussed accessing the raw metadata dictionary. This capability is gone. If you need this specific capability, you’ll need to create your own dictionary. Another exciting change in the MEF Preview 6 available on CodePlex is the inclusion of an early preview of MEF for Silverlight. The Silverlight version of MEF will probably not be released with .NET 4 but wait for Silverlight 4, which will release a bit later because they’re on independent release cycles. This preview is intended for use with Silverlight 3. One of the features of MEF for Silverlight is a Package Directory to supply MEF parts via XAP packages. If you’re working with Silverlight, MEF capabilities for Silverlight 3 are an exciting addition, although there are likely to be some changes prior to the Silverlight 4 release. Most of these changes are likely to be in the Silverlight- specific pieces such as the API for the Package Catalog. If you’re interested in seeing MEF run on Silverlight, you can explore a new picture viewer sample Silverlight application available with the preview.

VisualStudioMagazine.com · October 2009 · VISUAL STUDIO MAGAZINE 27 { ASK KATHLEEN }

the partial keyword on each partial piece, you’ll need to include LISTING 1 the partial keyword in the generated portion of the interface—this Starting with Managed Extensibility Framework Preview (MEF) 6 will probably require altering the template. and .NET 4 beta 2, MEF distinguishes between request for a single You can accomplish the same thing in VB, although the item, a single item that happens to be an IEnumerable, and an approach is different. Here you can create a custom base interface ¡IEnumerable of matching parts. Understanding this distinction and a generated interface for use, or the reverse: will help keep you out of nasty debugging situations.

Interface IFooCustom [Export(typeof(Class1))] ' Put custom interface elements here public class Class1 End Interface { // x contains an empty IEnumerable supplied from Interface IFoo //class C Inherits IFooCustom [Import()] Property Name() As String private IEnumerable x; ' Other properties End Interface // y contains two elements supplied by class B1 //and B2 Interfaces allow multiple inheritance, so this doesn’t interfere with [ImportMany()] any other inheritance in your design. private IEnumerable y; There are a couple of differences with the VB approach. Primarily, } MEF Update the C# partial class is optional—you can include the partial or not as your needs change. In the VB approach you must include the public interface IB custom interface whether or not you’re using it. You also have an {} extra interface in your solution, which a programmer could implement or use, even though its use is inconsistent with the [Export(typeof(IB))] intention of the architecture. There’s no parallel to MustInherit— public class B1 :IB abstract in C#—for interfaces. { } If the interface is queried via inheritance, the partial interface in C# will appear as a single interface, while the inheritance aspect of [Export(typeof(IB))] the VB approach will be evident. This is potentially a feature. In public class B2 :IB the partial interface approach, it’s impossible to determine whether { } a particular interface member is a custom item. Via reflection, you can make this distinction by exploring the inherited interface public class c design. If this distinction is valuable to your overall architecture, { you can also use the inheritance approach in C#. [Export()] IEnumerable z = new List(); Q: When should I use a callback delegate and when should I use } an event?

A: Events and callback delegates both allow communications between elements of your application. There’s also a third approach when there are zero or one interested parties. Once the call- using MEF. back is originally passed, this delegate can be passed on with An event allows a subscription model. A class can inform the no dependencies other than the signature of the delegate. This rest of your application that something happened without con- is also a loosely coupled scenario where the dependency is only cern over how many other portions of the application actually on the delegate being passed around the system, with the care that the event happened—specifically not caring whether listener aware of the specific instance it called to pass the call- anything is listening for the event. The event generally has an back delegate. argument, but the calling code can accept the argument as any base The third approach relies on a composable system such as MEF. type. This is a fairly loosely coupled scenario where the listener is A MEF part can request a list of all other parts in the system that aware of the specific item it subscribed to, but the broadcaster is support a particular contract. The contract can contain a delegate entirely unaware of who’s listening. to call when something happens. The contract effectively subscribes A callback delegate provides a specific delegate that will be the listener as interested in a particular occurrence, without the called in a logically consistent manner. This approach is useful formal dependencies. This is less coupled because, from a logical

A callback delegate provides a specifi c delegate that will be called in a logically consistent manner. Th is approach is useful when there are zero or one interested parties.

28 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com Project2 8/28/09 12:56 PM Page 1

Coming to a desktop nearr youy – it’s the SharePoint 2010 Virtual Conference & Expo … and it’s FREE!

We’ve heard from you that it’s hard too get out of the office these days and trainingd ollarsdollars are are limited, so we’re bringing you a FREE virtual event on one of the most anticipated ssoftwareoftware releases – SharePoint 2010 – live fromm the convenience of your offi ce.

Keynote Address: Arpan Shah, Director,rector, SharePoint Product Management team,m, Microsoft Enjoy Sessions On: • The SharePoint 2010 Roadmap • Your first look at the new SharePointt tools tools • Integrating Silverlight with SharePointnt 2010 With a revolutionary Virtual Expo Hall you’lll get the full-fidelity experience of a real conference,e, without without all the travel! Learn more and Register forr FreFreee at SharePointVCX.comm Advisory Council Ted Pattison Andrew Connell Conference Chair, Co-Founder, Co-Founder, Author, Author, Critical Path Training Critical Path Training

Doug Barney Paul Stubbs VP/Editorial Director, Technical Evangelist for SharePoint 1105 Enterprise Computing Group and Office, Microsoft Corporation { ASK KATHLEEN }

If you lose your local test run confi guration, you can recreate it by creating a new test project. This creates the fi les you need, and then you can delete the dummy project.

perspective, the listener effectively says: “Hey, if anyone out there Q: I was using a local test run configuration to copy some files into does this, I want to know.” It cares about the occurrence unrelated my test environment. These tests began to fail and Visual Studio to the thing that caused the occurrence. said there was no local test run configuration. How do I get it back? Events are a good solution when you have an item that will inherently be known by the subscriber, but the item raising the A: If you lose your local test run configuration, you can recreate it communications has no dependency on who’s listening—for by creating a new test project. This creates the files you need, and example, in a user interface where containers are interested in then you can delete the dummy project. One way this appears to state changes of contained parts. happen is manually down-revving from .NET 4 to .NET 3.5. Callbacks are a good solution when there’s generally a single listener and the relationship is predictable. For example, an asyn- Q: I know this is a small thing, but I find it very annoying to try to chronous process called by an application element is generally read output in the Immediate window which has //n embedded in interested in knowing that the process completes. it. How do I display output in the immediate window with the stupid MEF Update MEF parts are a good solution when actions will occur within /r/n? the system, but the design doesn’t require any details or couple. This is a good approach for decoupled systems where a logical A: To force formatting you should use a WriteLine method such state change can be generated by any mechanism and be recog- as System.Diagnostics.Debug.WriteLine. For example, if the mes- nized by any combination of parts—or no parts. MEF parts are a sage in an exception is long and contains these characters, you’re great approach for applications that are already using a compos- currently using: able system. However, it may not in itself be sufficient reason to adopt a ? ex.Message composable approach. Instead use: Q: I have a solution with a half dozen projects that works fine on most of my group's machines, but we get the following error when we ? System.Diagnostics.Debug.WriteLine(ex.Message) run the application on a new development machine: Could not load file or assembly 'MyLibraryName, Version=1.0.0.0, Or, if you have imported (using in C#) System.Diagnostics, you Culture=neutral, PublicKeyToken=null' or one of its dependencies. can simplify this to: An attempt was made to load a program with an incorrect format. ? Debug.WriteLine(ex.Message) A: This error almost always occurs because you have a mixed build environment: the selected options for building different Q: I’m getting an error in a Windows Presentation Foundation assemblies in the application aren’t compatible in the CPU they application that just says: System.ExecutionEngineException. The target. One way this can happen and give inconsistent results is application was previously working. to have most of the projects in your solution target “AnyCPU” and one or more target “x86.” This combination will run without A: Check your App.xaml for a missing TargetType. It’s required in a problem when doing x86 development. However, when you Silverlight. Rick Robinson pointed out one way this might happen run the same application on a 64-bit machine, you’ll encounter in a blog post at http://tinyurl.com/l8ksth. VSM this error. You can fix this by using the same target for all projects in the Kathleen Dollard is the chief technologist for AppVenture (www.appventure.com). solution. I’ve often had to make this change both in the project She has been a Microsoft MVP for 11 years and is a member of the INETA properties and in the build configuration. There are two things Speaker’s Bureau. Dollard has worked extensively with application code that might surprise you as you make this change. There’s a check generation and is the author of “Code Generation in Microsoft .NET” (Apress, box that appears when you change the build configuration asking 2004). She speaks at dozens of conferences and user groups each year, and is whether you want a new solution item. This generally needs to also active in the Northern Colorado .NET SIG, Denver Visual Studio User be unchecked because you already have the correct build defined Group, Northern Colorado Architect’s Group and IASA Denver. for the solution. When you change the target in project properties, Visual Studio GO ONLINE assumes you’re creating a new set of outputs and resets the output Use this FindIT code at VisualStudioMagazine.com to go directly location to the default. If you were building into the default loca- to these related resources. tion, you won’t notice this. However, if you’re building into an alternate location and don’t realize that the output path is reset, READ & DOWNLOAD your application will remain broken because the assembly you’re Dollard1009 Read Kathleen Dollard’s April article on the Managed using hasn’t been updated. Extensibility Framework, “Working with MEF,” online.

30 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com Advertising Sales

Ad Index

Advertiser Page

/n Software Inc. 13 www.nsoftware.com Accusoft Pegasus 27 EAST www.accusoft.com Aspose C3 Andrew Mintz www.aspose.com National Sales Manager ComponentArt, Inc. C2, 1 Phone: 508-532-1433 www.componentart.com [email protected] dtSearch 25 www.dtsearch.com ESRI 2 WEST www.esri.com Chris Kourtoglou FarPoint C4 www.fpoint.com Regional Sales Manager INTEL 9 Phone: 650-787-9515 www.intel.com Director, Print Production [email protected] LEAD Technologies, Inc. 17 Jenny Hernandez-Asandas www.leadtools.com National Accounts Director Phone: 818-734-1520 ext 101 SAP Business Objects 11 William Smith Fax: 818-734-1528 www.sap.com Phone: 603-886-3466 [email protected] SharePoint Virtual Conference & Expo 29 http://sharepointvcx.com/ [email protected] Production Coordinator Visual Studio Magazine 19 visualstudiomagazine.com Microsoft Account Manager Serena Barnes Visual WebGui 5 Danna Vedder Phone: 818-734-1520 ext 164 www.visualwebgui.com Phone: 253-514-8015 [email protected] Wayside Technology Group, Inc 7 [email protected] [email protected] www.waysidetechnology.com

Editorial Index ID Statement Developer Express Inc. 12 Visual Studio Magazine (ISSN 1537-002X) is published herein is the reader’s sole responsibility. While the www.devexpress.com monthly by 1105 Media, Inc., 9121 Oakdale Avenue, information has been reviewed for accuracy, there is Google Inc. 18, 32 Ste. 101, Chatsworth, CA 91311. Periodicals postage no guarantee that the same or similar results may be www.google.com paid at Chatsworth, CA 91311-9998, and at additional achieved in all environments. Technical inaccuracies SAP AG 32 www.sap.com mailing offi ces. Complimentary subscriptions are sent may result from printing errors and/or new develop- to qualifying subscribers. Annual subscription rates ments in the industry. Zoho Corp. 32 www.zoho.com for non-qualifi ed subscribers are: U.S. $34.97, Canada $52.97 (U.S. funds); International $78.97 (U.S. funds). Corporate Address Subscription inquiries, back issue requests, Corporate Headquarters: and address changes: Mail to: Visual Studio Maga- 1105 Media zine, P.O. Box 2166, Skokie, IL 60076-7866, email 9121 Oakdale Ave. Ste 101, Chatsworth, CA 91311 [email protected] or call toll free (888) 768- www.1105media.com 8759, fax number 847-763-9564. International calls 847-763-9135.POSTMASTER: Send address changes Media Kits to Visual Studio Magazine, P.O. Box 2166, Skokie, IL Direct your Media Kit requests to Matt Morollo, VP 60076-7866. Canada Publications Mail Agreement No: Publishing, 508-532-1418 (phone), 508-875-6622 40612608. Return Undeliverable Canadian Addresses (fax), [email protected] to Circulation Dept. or Bleuchip International, P.O. Box 25542, London, ON N6C 6B2. Reprints For single article reprints (in minimum quantities of Copyright Statement 250-500), e-prints, plaques and posters contact: © Copyright 2009 by 1105 Media, Inc. All rights PARS International reserved. Printed in the U.S.A. Reproductions in whole Phone: 212-221-9595 or part prohibited except by written permission. Mail E-mail: [email protected] requests to “Permissions Editor,” c/o Visual Studio www.magreprints.com/QuickQuote.asp Magazine, 230 California St. Suite 302, San Francisco, List Rental Go to CA 94111. VisualStudioMagazine.com This publication’s subscriber list, as well as other lists to access the stories in Legal Disclaimer from 1105 Media, Inc., is available for rental. For more The information in this magazine has not undergone information, please contact our list manager, Merit this issue, plus read any formal testing by 1105 Media, Inc. and is distrib- Direct. Phone: 914-368-1000; E-mail: 1105media@ exclusive online-only uted without any warranty expressed or implied. meritdirect.com; Web: www.meritdirect.com. content. Implementation or use of any information contained

VisualStudioMagazine.com · October 2009 · VISUAL STUDIO MAGAZINE 31 BY ANDREW BRUST

A Winning Campaign: Remain in Offi ce

Since Bill Gates proclaimed Microsoft’s Internet strategy in his conventional databases and SAP, as well as feeds on the Internet Tidal Wave memo of 1995, people have been cynical of Web and even SQL Azure databases in the cloud. When Gemini is Microsoft’s embrace of the public network. Some of the cynicism done importing data, it allows PivotTable and PivotChart analyses has been well-founded: despite Gates’ mandate that Microsoft to be created. And those analyses can be shared with others would become an Internet company, its revenues, to this day, via—you guessed it—Excel Services and SharePoint. (You can read remain driven by Windows and Offi ce. Microsoft can’t turn its more about Gemini in “Selling Self-Service,” my December 2008 back on the desktop, nor should it. Microsoft is the desktop. Any column in Redmond Developer News, at RedDevNews.com.) Microsoft Internet strategy that is divorced from the desktop, When analyses are shared, so are their insights. But Gemini which ignores the very important work done and assets created adds a new twist: those shared spreadsheets themselves there, will always be fl awed. become Analysis Services cubes, to which any client tool can con- How can Microsoft embrace the Internet while remaining nect. Suddenly the roles of data consumer and database provider loyal to its desktop heritage? In reality, Microsoft has focused are blurred, and Gemini facilitates user-generated content for on the PC—its attempts at an Internet strategy have been half- business. Now add hosted SharePoint, which will likely proff er hearted and only marginally successful. To make matters worse, these same features to the entire Internet, and the Offi ce Web Microsoft remains dependent on Offi ce version upgrades when it Applications to boot, and suddenly Offi ce is Microsoft’s Internet has arguably run out of things to add to Word, Excel, PowerPoint, strategy. Now data can move from the cloud to the desktop to Access, Visio and even newer applications like OneNote. To some, the on-premise server, and the documents and analyses that use Redmond would appear to be at a dead end. it can make the round-trip back up to the cloud. But now, with the impending, coordinated release of Offi ce 2010, SharePoint 2010—including the fi rst version of the product If You Can’t Beat Them, Lead Them to be designed with hosted operation in mind—and SQL Server Client-server-cloud distinctions are melting away. We knew this 2008 R2, Microsoft is paving the road ahead. The Offi ce Web would happen, but we never would have predicted Microsoft’s Applications, browser-based versions of Word, Excel, PowerPoint role in this transition. Microsoft isn’t ignoring the change, and and OneNote, are part of the reason why. But there’s more to it isn’t simply welcoming it either. Instead, through Offi ce and the story. SharePoint, Microsoft is actually driving the transformation. No longer content to pursue desktop, enterprise and Internet Software Plus (Excel) Services markets in isolation, Microsoft is joining them and enhancing the With the last version of Offi ce and SharePoint, Microsoft intro- value of each through its federation with the others. duced something called Excel Services, which allowed entire This version of Offi ce, using SharePoint as the substrate, Excel workbooks or components within them to be viewable— brings together the concepts of collaboration, analysis, data while their data remained refreshable—within SharePoint and consumption and data creation, and makes the Internet its the browser. That was a good move, and Microsoft is running venue. That’s a value proposition that Google, Zoho and other with it. Offi ce and SharePoint 2010 will extend that concept so late entrants to the offi ce productivity market seemingly have that Access and Visio can participate as well. That means up-to- not even thought about. Suddenly, the notion of Microsoft as an date Access reports become available to everyone in Internet company has morphed from an awkward contradiction to the organization. And Visio diagrams, including those that are a natural progression. VSM data-driven, become shareable in the same way. Even within Excel, which already enjoyed this power, things Andrew J. Brust ([email protected]) is chief of new technology for are getting far better. That’s because of Gemini, a self-service consultancy twentysix NewYork, as well as a Microsoft regional director business intelligence add-in that brings the power of SQL Server and MVP. He’s also the co-author of “Programming Microsoft SQL Server Analysis Services to the desktop. Gemini can import data from 2008” (Microsoft Press, 2008).

32 VISUAL STUDIO MAGAZINE · October 2009 · VisualStudioMagazine.com Project1 7/16/09 11:06 AM Page 1 Project1 9/11/09 9:36 AM Page 1