VisualStudioMagazine.com

AZURERE-ARCHITECTING ’s Platform as a Service is launching this month with forklift changes based on developer feedback.

PLUS Developers Dig into VS 2010 and .NET 4 Beta 2

Redmond Review: SQL Server 2008 R2 NOVEMBER 2009 Volume 19, No. 11 2009 Volume NOVEMBER Project5 8/24/09 2:17 PM Page 1 Project5 8/24/09 2:18 PM Page 2 Project2 10/7/09 10:35 AM Page 1

“Intel® Parallel Amplifier pointed me to the right source line that was taking much of the time. I made the change and voila, our app is now almost 10x faster.”

DAT CHU, RESEARCH ASSISTANT COMPUTATIONAL BIOMEDICINE LAB UNIVERSITY OF HOUSTON

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. November 2009 // Volume 19 // No. 11 Contents { FRAMEWORKS } 14

Michael Desmond, Editor in Chief, Visual Studio Magazine Return to Values A few months back, VSM columnist Andrew Brust wrote about Microsoft moving away from building the type of products that fueled its early success (“Remembrance of Code Past,” May 2009): That is, affordable, value-minded tools that prioritized productivity. As he wrote at the time: “The very simplicity and productivity of classic VB, ASP and earlier data-access models is what made the Microsoft developer ecosystem so huge. As FEATURES important and successful as .NET has been, 14 Re-Architecting Azure the framework has pushed Microsoft to A year after the first technical previews of Azure, Microsoft is launching a abandon much of that simplicity and less-ambitious platform with forklift revisions based on developer feedback. de-prioritize the wants and needs of the BY KATHLEEN RICHARDS developers who once flocked to it.” 23 LANGUAGE LAB So I’m intrigued by a streamlined alternative to Visual Studio Team C# Corner PAGE 23 Foundation Server (TFS) called TFS Basic The Azure Factor Profile. The tooling will work with Visual How factoring out common patterns in your Azure worker roles can Studio Team System 2010 and promises improve development. BY BILL WAGNER to address the product’s high cost and complex installation. Ask Kathleen PAGE 27 Matt Carter, director of Visual Studio Stable Composition in MEF product management, discussed TFS Basic Learn how to work through debugging challenges posed by stable composition in MEF Preview 7, and get insight into using MEF with Silverlight. Profile at the VSLive! conference in BY KATHLEEN DOLLARD Orlando, and noted that the new product will appeal to developers who have stuck DEPARTMENTS with Visual SourceSafe, Microsoft’s 6 Letters to the Editor venerable source code-management offering. Unlike server-based TFS, TFS 8 DevDisasters Basic Profile will run on a Windows Vista or Trans-Atlantic Time Trap BY ALEX PAPADIMOULIS (THEDAILYWTF.COM) Windows 7 client box. TFS Basic Profile should appeal to 10 DevInsights DEVELOPER NEWS, REVIEWS, PRODUCT BRIEFS current Visual SourceSafe users, but will it News: Developers Dig into Visual Studio 2010 and .NET 4 Beta 2 PAGE 10 lure back those who left for open source Product Review: ANTS Performance Profi ler PAGE 12 alternatives like CVS or Subversion? More 31 Index of Advertisers important, might we expect a renewed focus by Microsoft on developers who COLUMNS value productivity over complexity? Drop 3 Frameworks BY MICHAEL DESMOND me a line at [email protected].

32 Redmond Review BY ANDREW BRUST COVER ILLUSTRATION BY RANDY LYHUS RANDY BY ILLUSTRATION COVER

VisualStudioMagazine.com · November 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

Scaled-Down Team Foundation Server Sam Ramji Assesses Adobe Mobile Flash Blitz BY JEFFREY SCHWARTZ Microsoft’s Open Source Ascent Includes iPhone Support Microsoft hopes to convince dev shops to BY JEFFREY SCHWARTZ BY JOHN K. WATERS move from its Visual SourceSafe version Former Microsoft Senior Director Sam Adobe Systems’ Flash Player 10.1 will control-management system to the more Ramji, who served as Redmond’s open support the Apple iPhone, Microsoft modern Visual Studio Team Foundation source thought-leader since 2007, has Windows Mobile, Palm webOS and, early Server (TFS) by off ering a scaled-down left the company to cloud infrastruc- next year, Google Android and Nokia version of TFS called TFS Basic Profi le. ture vendor Sonoa Systems. We spoke Symbian OS. Adobe and Research in Motion with Ramji about his eff orts to champion have agreed to co-develop a version of FindIT code: Schwartz1109 open source activity at Microsoft. Flash that will run on the BlackBerry. Inside VSTS: FindIT code: SchwartzB1109 FindIT code: Waters1109 Unit Testing with Visual Studio Team System 2008 Microsoft Launches ‘Spark’ Program Mashup Interoperability Alliance BY MICKEY GOUSSET BY KATHLEEN RICHARDS BY JOHN K. WATERS This three-part series on unit testing in Microsoft has kicked off another “Spark” In a bid to foster interoperability among Visual Studio Team System 2008 guides program to seed the development audi- enterprise mashups, a group of 11 IT compa- developers through the process of adopting ence for its Web tools and platforms. The nies has launched Open Mashup Alliance, an a unit test, extending it to provide code global program lowers the barrier to entry industry body that will promote and support coverage and ultimately improving it by for Web professionals and smaller com- Enterprise Mashup Markup Language, a enabling data-driven unit tests. panies, and allows Microsoft to compete common markup language. with open source software. FindIT code: Gousset1109 FindIT code: WatersB1109 FindIT code: Richards1109 Classic VB Corner: Alfresco Cloud Developer Program Finding the Right Tool for the Job RDN Express: BY JEFFREY SCHWARTZ BY KARL E. PETERSON More Bandwith for Microsoft AJAX Leading open source enterprise content- Tired of wondering which version of BY KATHLEEN RICHARDS management software provider Alfresco dumpbin or link is executing? Would you Microsoft’s new Content Delivery Network has launched the Alfresco Cloud Developer like to copy that tool you use all the time provides ASP.NET AJAX programmers the Program to support programmers looking to another machine, but can’t seem to ability to host static content for free across to build electronic content-management fi nd it? Here’s a little utility that can help. thousands of edge servers worldwide. apps that can run in the cloud. FindIT code: Peterson1109 FindIT code: RichardsB1109 FindIT code: SchwartzC1109

VisualStudioMagazine.com RedDevNews.com ADTmag.com

4 VISUAL STUDIO MAGAZINE · November 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 Firefox, Safari, 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. VisualStudioMagazine.com Letters November 2009 • Volume 19 • No. 11

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 Andrew J. Brust, Ken Cox, Kathleen Dollard, Roger Jennings, Jeff Levinson, Bill McCarthy, Karl E. Peterson, Keith Pleas, Peter Vogel, Bill Wagner, Dan Wahlin, A reader responds to Redmond Review columnist John K. Waters Andrew J. Brust’s contention that Entity Art Staff Framework isn’t helping .NET developers (“The Creative Director Scott Shultz Value of Known Entities,” September 2009). Graphic Designer Erin Horlacher

Online/Digital Media My own sentiments rarely resonate with Editor, VisualStudio Becky Nagel commentary from the “talking heads” in our fi eld. Magazine.com But with regard to the “impedance mismatch” Executive Editor, New Media Michael Domingo Online News Editor Kurt Mackie between objects and relational—and all the Associate Editor, Web Gladys Rama hype that’s built around trying to connect the Web Producer Shane Lee two worlds—I couldn’t agree more with every word Brust packed into this paragraph:

“But I question how well Entity Framework serves the majority of President Henry Allain developers who enjoy the power of relational technology and want access to Vice President, Publishing Matt N. Morollo it. Such developers want to write their own queries, or may want to let their Director of Marketing Michele Imgrund database administrators do so and then call the stored procedures that result. Online Marketing Director Tracy S. Cook These developers appreciate the cooperative diversity of programming and relational query; they’re not ‘impeded’ by the distinction between them, nor do they see a mismatch.” President & Neal Vitale Chief Executive Offi cer In the applications I build—demand planning, pricing systems and Senior Vice President Richard Vitale sell-through analysis—I usually must deal with not only the relational structures & Chief Financial Offi cer and the object structures, but the representation of that entity and its related Executive Vice President Michael J. Valenti

entities on the screen. This often resembles neither the object nor the and its relations. Instead, it needs to be rendered in a way that accommodates Vice President, Finance Christopher M. Coates & Administration the user’s “view” of the entity and all of its relevant, and usually de-normalized, Vice President, Digital Media, Abraham M. Langer data in the context of that particular application—much like a virtual set of Audience Development objects built specifi cally for a task. ADO.NET gives me most of the tools I need Vice President, Information Erik A. Lindgren Technology & Web Operations to construct a data layer in which to build these views with a high degree of Vice President, Digital Media, Doug Mashkuri fi delity to the application’s purpose. Advertising Vice President, Carmel McDonagh Sure, I have some complaints about features and capabilities that I feel are Attendee Marketing lacking in ADO.NET. But instead of solving these issues, I see newer technologies coming out that are more ambitious and are imposing other constraints because Chairman of the Board Jeff rey S. Klein they’re taking me a step further away from the database. This forces me to REACHING THE EDITORS adopt the new tool’s scope as a range of what I can and can’t do to get my Editors can be reached via e-mail, fax, telephone or mail. application close to the user’s perspective. A list of editors and contact information is available at VisualStudioMagazine.com. Walter J. Zielenski E-mail: E-mail is routed to individuals’ desktops. Please use President, Applied Business Systems Inc. the following form: [email protected]. Teterboro, N.J. 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 1105 Media Inc. herein do not necessarily express those of the publisher.

6 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com Project2 8/24/09 10:57 AM Page 1

{ SOFTWARE DEVELOPMENT GONE WRONG }

Trans-Atlantic Time Trap

obody believed the French. Not number became the day number Nthe entire country, or Frenchmen in and the day number became general, but rather the folks who the month number. worked at the European Branch Offi ce in With no apparent Paris. The bug they described—their root cause, Moe computer’s internal date was randomly off ered up a simple changing—reeked of user error and seemed workaround: run far too implausible to be caused by the single-page reports corporate reporting system. twice and, if that But the French employees relent- fails, reboot the lessly called app support whenever their computer. Pierre clock would mysteriously change. It was wasn’t thrilled, but always a predictable dialog. was content that a “Ca me fait chier,” Pierre would non-French employee grumble. “The date! It just changed again!” had fi nally witnessed Moe T. was often the support the problem. After another hour of digging through developer on the other line. sub-routine after sub-routine and script “Did you try changing it back, Pierre?” Back to Basic after script, he fi nally found the off ending he would ask. “You could also reboot.” Moe went back and dug through the code, code buried in the page header macro: but couldn’t fi nd a thing. He looked at the ' format the date Random Bug report itself, the report generator, the Date = month & "/" & day & _ Moe simply could not reproduce the report printer and the report runner ... and "/" & year problem. It only seemed to happen at still, nothing. With other things taking On most computers, including the random, and only a few times a month. precedence, and a workaround in place, the developers’, the code simply set the system That is, until two years later, when Pierre date issue fell onto the backburner. date to the current month, day and year. On noticed a pattern. That is, until a year later, when Moe the French computers—where dates use the “If we print the GL-DLG-ADM report just happened to fl ip through some VBA DD/MM/YYYY format—the code swapped on the fi fth day of the month,” he documentation and noticed this: the months and the days. And then, on the explained in an e-mail, “it will ‘swap’ the Date: returns the current system date second page, it swapped them back. After day and the month on our computer. So, if Note: assigning a value to Date will the twelfth day of the month, when most my computer says it’s Oct. 5, then the change the current system date to the value reports were run, the line silently failed. report will change my computer date to He did a double take. It took just a few minutes to fi x. And May 10. But, this only will happen if the “Wait a sec,” he said to himself. “VBA after three years, the French employees report is one page long.” lets you set the system date by setting a could fi nally stop counting forms before It sounded like a superstitious value to the function?” His mind immediately printing, and always making sure to print an diagnosis to an even stranger problem, and jumped to the bizarre French date bug. The even number of pages per workstation—or none of the developers believed it. No report used VBA Macros and must have failing that, rebooting after printing, which matter how many times they ran a somehow been assigning a value to Date. set the PC time to network time. VSM one-page GL-DLG-ADM on their machines, their computer date remained the same. Tell Us Your Tale But Pierre was insistent and demanded that Moe log in to his machine Each issue Alex Papadimoulis, publisher of the popular Web site The Daily WTF (thedailywtf.com), to watch the problem fi rsthand. Sure 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 enough, running GL-DLG-ADM did, in fact, to Executive Editor Kathleen Richards at [email protected] and put “DevDisasters” change Pierre’s system date. The month as the subject line.

8 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com 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. DEVELOPER NEWS /// REVIEWS

DEVELOPER NEWS

“Performance of the WPF [Windows Presentation Foundation] code editor is supposed to be much better,” says Bill Wagner, founder of SRT Solutions and a VSM contributor. Also welcome news, Wagner adds, is the second preview release of Microsoft’s ASP.NET Model-View-Controller 2 (MVC 2), which will be featured in VS 2010 beta 2, rather than as a separate component. “You won’t need to go anywhere else, it’ll just be there waiting for you,” wrote Microsoft Senior Program Manager Phil Haack, in a blog posting last month announcing the ASP.NET MVC 2 preview. “Likewise, the RTM [release to manufacturing] of ASP.NET MVC 2 will be included with the RTM of Visual Studio 2010.” That decision may indicate that Microsoft believes ASP.NET VS 2010 and VS .NET 4 Beta 2 .NET 4 Beta MVC will have wider appeal than the company originally anticipated, Wagner says. “Microsoft has been saying [MVC] may or may not have a long future,” he explains. “Since MVC is going to be a part of Visual Studio, that’s a pretty clear statement it will be around for a while.” Improvements in VS 2010 beta 2 will go beyond MVC and the code editor, Microsoft offi cials suggest. “A lot of people are saying, ‘I’ve seen beta one,’ but they haven’t seen everything. There are defi nitely new things coming that we’ll be talking about in our Developers Dig into track,” said Visual Studio and .NET Technical Evangelist Drew Robbins in a Channel 9 video. Visual Studio 2010 and Michele Leroux Bustamante, chief architect at Los Gatos, Calif.- based iDesign Inc., says she’s looking forward to the beta 2 of .NET 4. .NET 4 Beta 2 Bustamante, who will be giving an overview of Microsoft’s technology roadmap at PDC09, wants to see what’s new in the Entity Framework 4 BY JEFFREY SCHWARTZ (EF 4). EF 4 will include support for Plain Old CLR Objects (POCOs) and Microsoft’s fl agship IDE is taking an incremental step forward T4 templates, which Bustamante says will help more easily control with the second beta release of Visual Studio 2010 and the .NET how models are produced from the database schema. “I’m hoping for Framework 4. Microsoft released the second beta of VS 2010 and improved support for offl ine change tracking,” she adds. .NET 4 on Oct. 19, giving developers a month to test the latest fi x of Also, she expects to see improved F# templates in the the company’s next-generation IDE a month before its Professional framework. “I’ve come to believe that F# is something developers Developers Conference 2009 (PDC09), set to take place in Los should try with an open mind, to gain a new perspective on how Angeles this month. Testers have been working with the fi rst beta to write C# code better, and possibly to leverage it in appropriate since May. Microsoft is expected to talk up a bevy of new technolo- layers of the application,” she notes. gies at PDC09. Among them will be cloud services Improvements to Windows Communication Foundation (WCF) (see “Re-Architecting Azure,” p. 14), which Microsoft Chief Software Workfl ow Services in combination with Application Server Extensions Architect Ray Ozzie will offi cially launch at the conference, one year should off er a viable way to build enterprise WCF services and after he outlined Redmond’s cloud vision at PDC 2008. enhance visibility into problems during development and while Ozzie will be joined by Bob Muglia, president of Microsoft’s services run in production, Bustamante adds. Server and Tools business unit. Muglia is expected to reveal more VS 2010 extensibility is another theme Microsoft is advancing. about developer hooks for the recently launched Windows 7 oper- Gabriel Torok, CEO of PreEmptive Solutions, will lead a session ating system and to discuss planned upgrades to key platforms in about the VS 2010 code editor extensions. Torok says he’ll demon- the Microsoft stack, including Offi ce, SharePoint, SQL Server, BizTalk strate a built-in editor that functions as an extension of VS 2010. and Application Server Extensions, which is code-named “Dublin.” The code editor provides in-line visualization of usage and stability data collected from applications in production via PreEmptive’s The 411 on VS 2010 Runtime Intelligence Services. “The idea that you can take data For developers attending PDC, VS 2010 and the .NET Framework 4 from production code that’s usage data, performance data, stability will take center stage. (For more on VS 2010, see “IDE Evolution,” data, and surface it inside the code editor is revolutionary,” Torok April 2009, and for more on the .NET Framework, see “.NET 4 says. “No one has seen anything like that before.” VSM Revealed,” June 2009.) By all accounts, VS 2010 beta 2 is expected to show a healthy improvement over the fi rst release. Jeff rey Schwartz ([email protected]) is news editor of VSM. ILLUSTRATION BY SHUTTERSTOCK.COM BY ILLUSTRATION

10 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com Project1 10/9/09 10:18 AM 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 Windows Server 2008. 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 Windows Forms 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 Microsoft Excel 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 AdminStudio & Application Orion Network Modeling with CA ERwin 7.3 Virtualization Pack Performance Monitor In our last webinar series, we looked at CA by Acresso by Solarwinds ERwin’s core functionality. In this second series, One Application Software Deployment Tool Orion Network Performance Monitor is a we’ll provide a grounding in how CA ERwin r7.3’s for Reliable MSI Packaging, Application comprehensive fault and network performance new features help you with Master Data Management, Metadata Virtualization, and Operating System Migration. management platform that scales with the Management, Data Warehousing, Data Governance and Business Intelligence. Top choice of Microsoft®, Novell®, LANDesk® rapid growth of your network and expands There will be six sessions in the series: and other software management solutions. with your network management needs. • What’s New in CA ERwin 7.3 Cut MSI packaging time by up to 70%, It offers out-of-the-box network-centric views Professional • MDM (Master Data Management) with CA ERwin and Data Deploy software to desktops with 99% that are designed to deliver the critical Profiling tool Upgrade from success or better. AdminStudio is the only information network engineers need. • Collaborative model management with CA ERwin ModelManager any Active AS MSI packaging solution to support multiple Orion NPM is the easiest product of its Paradise # Pro + Silver Mtn virtualization formats, including Microsoft® kind to use and maintain, meaning you • Validate the integrity of your model with CA ERwin Validator ™ ® ™ S4A 08201E02 Paradise # App-V , VMware ThinApp and will spend more time actually managing • Reporting: Crystal Reports, PDF, HTML I21 09201S06 Citrix® XenApp™. networks, not supporting Orion NPM. $4,606.99 • SAPHIR Option: light at the end of the metadata tunnel $4,228.99 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.

REVIEW

ANTS Performance Profi ler ANTS Performance Profi ler 5.1 Discover what your application is really doing—method by method, line by line— with Red Gate ANTS Performance Profi ler. Red Gate Software Ltd. Web: www.red-gate.com BY PETER VOGEL Th is will start both the profi ler and the Phone: 866-997 0397 Your application is behaving poorly. application. However, not all applications Price: $395; $494 with support You’d think that having written the can be profi led directly; Web Projects or and upgrades application yourself, you could diagnose Windows Services are two such applica- Quick Facts: A performance the problem. Unfortunately, any tions. For those applications, ANTS profi ler for analyzing performance ler real-world program is complex enough Performance Profi ler must be started as a bottlenecks

Profi that it’s unlikely that even the application stand-alone program and attached to the Pros: Easy to use with detailed author himself can fully understand how application. I found that when working information organized for ready access ANTS Performance Performance ANTS the code performs under live fi re. with complex solutions containing Th at’s where Red Gate Soft ware’s multiple projects, some of which couldn’t Cons: Integration with Visual Studio ANTS Performance Profi ler 5.1 becomes be profi led directly, I couldn’t use the not fully realized an important part of your toolkit. Th e Profi le Performance menu choice and tool enables developers to determine had to start the tool in stand-alone mode. where their applications are really Aft er you start the ANTS Profi ler, to providing you with an overview of spending their time. ANTS Performance the Project Profi ler Settings dialog where your application spends its time, Profi ler can be used either within the displays, allowing you to select the the tool also allows you to drill down to Visual Studio IDE or as a stand-alone executable you want to profi le. You can individual methods and even lines within application to analyze your application in also attach ANTS to IIS to profi le an methods. You can see how many times its runtime environment. ASP.NET application or attach it to a any method or line was called and how Windows Service. You can then start long, on average, each took to execute Integration with Visual Studio your profi ling session, which triggers (see Figure 1). Aft er downloading and installing ANTS ANTS to launch your executable. Performance Profi ler, you’ll fi nd a new During the profi ling session, ANTS Customization ANTS 5 menu added to the Visual Studio Performance Profi ler displays a graph ANTS Performance Profi ler will probably menu bar. For many Windows Forms showing key performance variables such do everything you need out of the box. applications you’ll be able to profi le your as I/O and CPU usage. But it’s when you However, you can pick and choose which application just by selecting Profi le stop your profi ling session that the performance measures you’re interested Performance from the ANTS 5 menu. soft ware reveals its full power. In addition in or insert instrumentation into your application to add markers to the log created by the soft ware. You can also have ANTS Performance Profi ler keep an updated log of your application’s activity, which is useful for problems that only occur when an application is running for long periods of time. Not every application needs ANTS Performance Profi ler. However, if you’re not getting the performance or behavior that you want from your application and you’re not sure where the problem is, this tool will help you fi nd it. VSM

Peter Vogel ([email protected]) is a principal in PH&V Information Services, specializing in ASP.NET development with expertise in SOA, Figure 1. The top part of the Profi ler window lets you select a time range to review; XML, database and UI. He’s written several books the middle part provides a high-level overview of time spent in the application’s objects; on application development using Microsoft tech- and the lower part lets you look at time spent executing individual lines. nologies and presents at conferences worldwide.

12 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com Project2 9/8/09 11:39 AM Page 1 14 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com CREDIT ????????????????? IMAGE Azure FEATURE

RE-ARCHITECTING AZURE

A year after the fi rst technical previews of Azure, Microsoft is launching a less-ambitious platform with forklift revisions based on developer feedback. BY KATHLEEN RICHARDS

icrosoft will reach a promised milestone when it commercializes the Windows Azure Platform at its Professional Developers Conference 2009 (PDC09) in Los Angeles later this month. The work that has gone into the Windows Azure Platform over the past Myear is impressive by all accounts. At PDC 2008, the company said it would rely on devel- oper feedback to help shape the roadmap. A year after the first technical previews of Azure, Microsoft is launching a platform with major technology revisions. The good news is that a lot of the forklift changes are based on developer feedback. “It’s very encouraging that they’re taking feedback in mid-flight and changing it,” says Ranjith Ramakrishnan, co-founder and chief technology officer of Cumulux. An early adopter of Azure, the startup company ported its MobileAxis application, built on the .NET Framework 3.0 and Microsoft Office SharePoint Server 2007, to Azure. The service provides a unified gateway to enterprise applications for smartphone users. It’s expected to debut in the PDC09 time frame.

VisualStudioMagazine.com · November 2009 · VISUAL STUDIO MAGAZINE 15 FEATURE Azure

New Business Portal As advertised at PDC 2008, Microsoft has expanded Azure PDC09 marks the unveiling of the gateway to the consumption- beyond managed code to support native code and PHP. Windows based pricing model that’s driving Microsoft’s cloud-computing Azure Storage has also been improved in the last year with sup- platform. With the new “business” portal, managers can determine port for limited transactions, among other features. The support how to purchase the Windows Azure Platform, agree to terms of for field streams, caches and locks talked about at PDC 2008 have use, provide payment authorization such as credit-card informa- yet to appear. tion and then assign the platform to a developer or development “When we went out with the CTP last October, it was .NET code team by entering their respective IDs. only and it was partial trust, and so you couldn’t really run any- Developers then have access to the entire Windows Azure Platform thing you wanted to. You had a little bit of a sandbox,” says Steve through a newly unified (common) interface to the Azure Services Marx, a technical strategist for the Windows Azure team. “And developer portals. This allows them to use whatever is needed from the we opened that up around our MIX conference and said: ‘You can Platform as a Service (PaaS), which at launch will consist of the run native code if you want; you can run PHP and you can run in Windows Azure cloud operating system, SQL Azure relational data full trust.’” storage and .NET Services connectivity. The Windows Azure for PHP SDK on CodePlex targets Windows The meter starts running once a developer deploys an applica- Azure Storage and provides programming interfaces for Windows tion or storage account to the Azure staging environment, made up Azure’s compute and management services. With the Simple Cloud of virtual machines (VMs). Usage and billing metrics are pushed to API, a Zend Technologies Ltd.-sponsored open source project the business portal in near-real time, according to Microsoft, and launched in September, PHP developers can use three reference developers are largely shielded from the financial and legal aspects interfaces to target multiple cloud vendors’ file storage. of Azure. “The business model drives the technology,” asserts George Moore, Shaped by Developer Feedback a Microsoft software architect, who gave an overview of the new busi- Microsoft did listen to developers and changed course dramatically ness portal in a Channel 9 interview in September. “To a large extent, on SQL Data Services (SDS)—formerly SQL Server Data Services the shape of the final product—like how the fabric actually works, (SSDS)—evolving it from a schema-less data source to a fully rela- how it’s deployed, how they count things, how the service-level agree- tional data storage called SQL Azure. “That was a very good move, ments [SLAs] work—all that stuff is driven by the business team.” mostly because SSDS and SDS really duplicated many of the fea- Maybe that explains some of the head-spinning changes since tures of conventional Azure tables,” says Jennings. PDC 2008. Windows Azure and the Azure Services Platform are Jennings hopes to see support for encryption in SQL Azure, par- now referred to as the Windows Azure Platform. The Windows ticularly transparent data encryption for commercial and regulatory Azure operating system, hosted on Windows Server 2008 in privacy. SQL Azure is on target for release quality at PDC, he says. Microsoft’s data centers, brandishes some of the technology At press time, SQL Azure had a storage limit of 10GB, and Azure improvements floated at PDC 2008. The higher-level developer Storage Blobs could scale to 50GB. “When you talk about scaling services—.NET Services, SQL Data Services (now SQL Azure), beyond 10GB, where your app owns the logic, I think it would be Live Services, SharePoint Services and Dynamic CRM Services— really nice to be able to get some of that partitioning baked into the have been whittled down to two at launch: .NET Services and the platform so that I don’t have to own that as a developer,” says Vishwas revamped SQL Azure. Lele, chief technology officer at Applied Information Sciences Inc. (AIS) and a Microsoft regional director. Unlocking New Capabilities AIS is working with several customers on Azure prototypes, By most accounts, the Windows Azure OS, which consists of VMs including a client who has to do a lot of number crunching. “They (compute), fabric controller (resource management) and unstruc- can spin up the worker role when they have to do all these calcula- tured data storage (Blobs, tables and queues), is stable. Developers tions,” says Lele. Unlike Google App Engine, the worker roles and can expect announcements around the VMs, an Azure version of queues in Azure can run 24x7 for background processing. Microsoft’s Hyper-V, at PDC09 later this month. An early criticism of the Azure technology by Tom Bittman, chief of research, infrastructure and operations at Gartner Inc., was that Tale of Two Platforms the community technology previews (CTPs) did not support scaling up “fixed-size” VMs. Automatic provisioning of elasticity, essen- How does the Windows Azure Platform integrate with the Windows tially the ability to spin up virtual servers as demand increases and Live platform? If you’re developing in Azure, do you still have decrease their number as it subsides, is expected in the first com- access to Live Services? Microsoft doesn’t have answers to these mercial release. questions at this juncture. “It’s always been planned to have scaling out, they just haven’t What’s the future of Live Mesh? According to a Microsoft spokes- implemented it,” says Roger Jennings, a developer and author of woman: “Live Mesh is a sample application that takes advantage of the OakLeaf Systems blog and “ with the Windows synchronization technology in Live Services. As we announced at Azure Platform” (Wrox, 2009). “That’s supposed to be implemented PDC last year, the next generation of Live Services will be the first in the Web release at PDC. It’s a manual process now.” major ship vehicle for Mesh technologies.” When the commercial version is launched, Jennings also expects How synchronization will be handled in the Windows Azure to see final provisioning APIs so that developers can provision Platform remains unclear, despite some presentations that show their VM instances with code, as well as minimum and maximum a “Data Hub,” known as “Project Huron,” which is based on the instance limits. Microsoft Sync Framework. —K.R.

16 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com Project3 3/18/09 9:10 AM Page 1 FEATURE Azure

.NET Services, which originally consisted of a service bus, access Binding was discontinued, with WS2007Relay Binding suggested as control and workflow, has had a tumultuous year. Workflow was a workaround. External Endpoint Registration is no longer avail- taken offline in the summer because developers indicated that able, but Microsoft expects to reinstate it at some point in the future. they wanted the workflow engine to be consistent with Windows The reshuffling of Live Services—which included the Live Workflow Foundation 4, expected in .NET 4. Framework and Live Mesh synchronization beta—out of the In the October CTP, access control was re-jiggered, with support Azure Platform occurred in late August. David Treadwell, Microsoft for WS-* protocols “temporarily” suspended. The team indicated corporate vice president of Live Services, announced in the Live a decision to focus on secure access to Web REST services as more Services blog that the Live Framework CTP would end on Sept. 8. enterprises move to REST. The idea was floated at MIX and devel- The Windows Live Web Role template for Azure won’t be supported oper feedback indicated that it was the right move, according to in future tooling. the .NET Services Team blog. The October CTP, which closely “Largely, what this is, is that Live Framework and the team building it mirrors what will appear at launch, according to Microsoft, all sort of merged with Windows Live and just became part of that includes support for simple Web trust; two token exchange broader team,” says Windows Azure technical strategist Marx. endpoints, including SAML extensions and Active Directory Federation Services (AD FS) 2.0; claims transformation; and Developer Experience Security Token Service. A major selling point of Azure for Microsoft developers is the ability to According to the Sept. 18 blog posting by the .NET Services use their existing skill sets and familiar tooling to program cloud Team that detailed planned October CTP changes: “Once this in- services: Windows Azure Tools for Visual Studio 2008 and Visual frastructure is in place, we will work on future version features of Studio 2010 beta 1 CTP, which includes the Windows Azure SDK. .NET Services, like Web single sign-on and rich WS-* support. In Windows Azure currently supports .NET 3.5 even if you’re using future releases, we will reinstate full support for the WS-* proto- VS 2010. cols, Web single sign-on, and round out the .NET Access Control To run code in the cloud, developers use the Azure Services Service offering in a way that spans the REST/SOAP spectrum.” Developer Portal to launch application code and a service model More information on how Windows Identity Foundation (worker and Web roles). The service model during the CTPs was and AD FS fit with Azure is likely at PDC09. In August, Microsoft quite limited, with multiple worker roles as the back-end and Web released Project Riviera on CodePlex, the first Azure line-of-business roles as the front-end just introduced in the July CTP. “The funda- reference application, developed in collaboration with Cumulux. mental communication model and the kinds of things you could Designed to support a Customer Loyalty Management program, run in those [roles] didn’t really expand, and that’s what you can the sample code uses multi-tenant storage via the Windows Azure look for coming to this PDC09 and even beyond, is to just open up Table and SQL Azure, Silverlight 3 and several other technologies. that box and enable more and more complex services,” says Of particular interest is Project Riviera’s use of AD FS, formerly Microsoft’s Marx. Geneva Framework, and the Security Token Service. The Azure Tools provide a developer fabric and storage services The October CTP also saw drastic changes to the service bus, for creating, debugging and packaging cloud services on your local which is designed to securely connect on-premises and cloud apps desktop using C# and VB project templates. “I’ve found that the through WCF endpoints. Routers have temporarily been dropped. developer fabric has gotten better,” says Lele, who has been working Queues were changed to simpler message buffers. WSHttpRelay with the Azure technologies since PDC 2008. Developers can run

Patterns and Practices for the Cloud

Look at your existing applications and to work,” says Steve Marx, a technical developer and Visual Studio Magazine identify what makes sense to move to strategist on the Windows Azure team. “It contributor. “You want your front-end to be the cloud. “If you have Web apps, ASP.NET also gives you reliability and availability: If close to the data for performance.” or PHP, you can benefit almost instantly a server goes down, you can replace it with Revisit Service-Oriented Architecture with the high availability that Azure an identical one.” (SOA) and Software as a Service (SaaS). provides. You can get two Web roles and Take a look at Windows Azure Tables. “If you use SOA and SaaS design techniques, you can get 99.5 percent uptime, without “Certainly you have SQL capability now, but you should be able to move your storage to having to do much in terms of infrastruc- it makes sense to take advantage of Azure the cloud fairly easily,” says Jennings. “But ture,” says Vishwas Lele, chief technology tables because they’re designed to scale there’s no real data portability between officer at Applied Information Sciences Inc. and you’re forced to think about partitioning Azure and any other cloud.” The Microsoft cloud is scale-out: from the ground up,” says Lele. “The pricing Learn cloud architecture patterns. Make the mind shift from working with model is really attractive. In SQL Azure, you “Think about these patterns, and the REST independent servers to the stateless pay $99 for 10GB, and Azure Tables are API, so that if a client is ready to deploy to Web. “All servers have to be identical and only 15 cents a GB.” the cloud down the road, you aren’t they all have to work in exactly the same Learn how to build a Web front-end. prevented from doing so because the way. That enables scale, because then I “Anything you develop in Azure is going to architecture has something that won’t gel can just add another server and load have a Web front-end that’s your primary with the cloud,” advises Lele. balance across them and I know it’s going communication,” says Roger Jennings, —K.R.

18 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com Project5 10/13/09 1:32 PM Page 1 FEATURE Azure

“My goal is that, if it works on your laptop, it’s going to work in the cloud, and we’re some 80 percent to 90 percent of the way there, but I’d like see us just ratchet it up as we go.” Steve Marx, Technical Strategist, Windows Azure Team, Microsoft

their code and storage locally using a mixed mode, where they run AZURE PRICING their code locally and use SQL Azure, Azure Storage or host every- Windows Azure thing in the Azure fabric. ■ Compute: $0.12/hour A Service Management API and upgrade option released to the ■ Storage: $0.15/GB stored/month Web in September enables programmatic improvements. “So now ■ Storage Transactions: $0.01/10K people can do things like automate their build process and deploy ■ Bandwidth: $0.10 in/$0.15 out/GB to the cloud and run some tests, or something like that,” says Marx. Early on, some developers complained about the need to create SQL Azure a Visual Studio solution for the cloud, particularly if they wanted ■ Web Edition, up to 1GB relational database: $9.99/month to use some existing code. “We actually cleaned some of that up in ■ Business Edition, up to 10GB relational database: the past year, so now it’s a little easier to share code between some- $99.99/month thing that you’re deploying to Windows Azure with something ■ Bandwidth: $0.10 in/$0.15 out/GB that you’re not, or make that decision later in the development cycle,” says Marx. .NET Services As early adopters like Kevin Marshall, director of product man- ■ Messages: $0.15/100K message operations, including agement for Clarity Consulting Inc., have noted, there are also Service Bus messages and Access Control tokens slight differences between what works locally on your desktop in ■ Bandwidth: $0.10 in/$0.15 out/GB Window Vista or Windows 7 and the cloud because it’s a Windows SOURCE: MICROSOFT Server environment. “My goal is that, if it works on your laptop, it’s going to work in Numerous Azure prototypes and enterprise apps are in the works. the cloud, and we’re some 80 percent to 90 percent of the way TriSys Business Software Ltd. is using SQL Azure for its TriSys there, but I’d like see us just ratchet it up as we go,” says Marx. “In Recruitment Software as a Service (SaaS). Epicor Software Corp. is the storage service, in particular, there are some features that migrating the enterprise search component of its ERP to Azure. we’ve released to the cloud that we haven’t put in the developer “I really want to see what they’re going to do around the small and version of those services yet.” [midsize] space,” says Bill Wagner, founder of SRT Solutions and a Deployment to the staging environment in the previews was Visual Studio Magazine contributor. “I think the current pricing “brutally slow,” says Clarity Consulting’s Marshall, who has hosted model works well for a large enterprise, but I really don’t think it’s apps on Azure and Google App Engine. Making changes to even competitive against PHP and LAMP stack hosting for smaller busi- one line of code, once an app or service has been deployed, is ness. I think they need an offering to get into that space.” tedious. Azure requires that you recompile and deploy the whole Marx expects many ISVs to look at Azure for building and hosting app instead of making changes on the fly and patching it. SaaS. “I think there’s a lot of benefit to these small development During the previews, developers had to go through an arduous teams that don’t have centers—and don’t want to have big process of copying their logs locally just to view them. In early data centers—but want to be able to develop and deliver software October, Microsoft announced on the Windows Azure blog that over the Internet,” he explains. it was disabling the ability to retrieve logs through the Azure One of those ISVs, Cumulux, would like to see integrated billing. “I portal because an improved logging system is going to be intro- want to give one bill to my customer,” says Ramakrishnan. duced at launch. Jennings hopes to see pricing that’s competitive with Google App Not all that much has changed since the Windows Azure tools Engine, but he doesn’t think that’s going to happen. “Microsoft were first introduced at PDC 2008. Microsoft is primarily working thinks [it’s] competing with Amazon,” he says. on performance improvements and “fit and finish” of the tooling, However, like many developers, Jennings is impressed with all says Marx. that has happened during the year since the first Azure previews For those concerned about security issues, Microsoft is working were released. “It’s very encouraging,” he says. “I think they’ve kept on a whitepaper for the PDC09 time frame that explains what is most of their commitments. They’ve listened to their developers happening “under the hood,” says Marx. The cloud isn’t introducing and they had the courage to make the changes when they needed to.” new security concepts, he asserts, especially if users understand Later this month, if everything goes as planned, the Windows the virtualization model. Azure Platform will become real. As one Fortune 100 developer remarked at the Azure introduction a year ago: “We haven’t seen a Hello Real World lot of the application lifecycle, so there’s a promise and it’s very easy The first external Azure app from Microsoft appeared in beta in late to get in—but what happens then?” We’re about to find out. VSM June. Called Microsoft Hohm, it’s designed to help consumers mon- itor their home energy consumption and ultimately save money. Kathleen Richards ([email protected]) is executive editor of VSM.

20 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com Project1 10/9/09 9:35 AM Page 1

Easy, Fast Mapping of Your Data Silverlight™ t SharePoint ® t SQL Server® 2008

Locate your best customers by ZIP Code® to conduct store-specific promotions.

ESRI® MapIt™ is software plus online services

that enables you to create and share dynamic Discover trade area overlap to maximize sales and improve customer service. maps from your SQL Server 2008 and Excel® data. Discover previously hidden patterns and opportunities that will drive success.

Extend your mapping capabilities with access “Using MapIt helped us reduce our to high quality online imagery, basemaps, development costs and deliver a geocoding and routing services. Visualize new product in record time.” your data in stunning detail through Mark Seward Silverlight and SharePoint. Vice President, Software Development EtSPONDER, LLC

Download a 60-day free trial of MapIt at www.esri.com/mapit.

ESRI serves over 350,000 organizations worldwide that rely on our software to create, manage, visualize, and analyze information.

Copyright © 2009 ESRI. All rights reserved. The ESRI globe logo, ESRI, MapIt, 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. Project2 10/7/09 10:39 AM Page 1

Coming to a desktop nearr you – 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 vvirtualirtual event on one of the most anticipated software releases – SharePoint 2010 – live fromm the convenience of your offi ce.

Keynote Address: Arpan Shah, Director,irector, 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’llll get the full-fidelity experience of a real conference,e, w iwithoutthout all the travel! Learn more and Register for Freeree at SharePointVCX.com Use Promo Code NQ9P03

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

IN THIS SECTION: C# Corner · 23 // Ask Kathleen · 27 ////////////////////////

{ C#CORNER }

The Azure Factor // build a request and remove those that //don't work StorageAccountInfo accountInfo = How factoring out common patterns in your Azure worker roles StorageAccountInfo. can improve development. GetAccountInfoFromConfiguration BY BILL WAGNER ("TableStorageEndpoint"); LinkDataServiceContext context = Azure Every Azure worker role you write will have some common code new LinkDataServiceContext blocks. The fact is that Azure worker roles will always follow a (accountInfo); few well-known patterns. Because of these common well-known patterns, it’s easy to fall into the trap of copying the code from foreach (var weblink in context. your fi rst application, and modifying it to create your second. WebLinkDataCollection) I look at copy/paste/modify reuse as an opportunity to create a { better library. You need to factor out the common parts from the if ((!weblink.LinkValid) parts that aren’t common. Sometimes that’s easy. Sometimes, as || (DateTime.Now - weblink. with worker roles, you’ll need to reach into your bag of tricks and LastVisit > TimeSpan.FromDays(1))) use Action<>, Func<>, LINQ queries and extension methods to CheckLink(weblink); create the library you want. In this article, I’ll take a sample Azure context.SaveChanges(); application and show you how to create reusable algorithms that } you can work with in all your worker roles. } The sample download is a simplifi ed version of an app I use } to keep track of my library of Web links. There’s an Azure Web role that displays the library of links. You can see a description of private void CheckLink(WebLinkData weblink) the site and the URL, and you click on the link to visit the site in a { new window. Of course, you can also add new links to the library. WebClient client = new WebClient(); One consistent problem I have is that some old Web links don’t try work anymore. I always had stale links in my favorites folder. I just { didn’t take the time to keep visiting all my links, and remove the var answer = client. ones that no longer worked. Azure has an architecture that makes DownloadData(weblink.Url); it easier to avoid that problem. An Azure worker role can periodi- RoleManager.WriteToLog("Information", cally attempt to download all the links. It marks any links that string.Format("link {0} is valid", don’t work as possibly bad. The worker role class is shown here: weblink.Url)); weblink.LastVisit = DateTime.Now; public class WorkerRole : RoleEntryPoint weblink.LinkValid = true; { } public override void Start() catch (WebException) { { // This is a sample worker implementation. RoleManager.WriteToLog("Information", //Replace with your logic. string.Format("link {0} FAIL", RoleManager.WriteToLog("Information", weblink.Url)); "Worker Process entry point called"); weblink.LinkValid = false;

while (true) public override RoleStatus GetHealthStatus() { { Thread.Sleep(TimeSpan.FromSeconds(30)); // pretty simple, we’re healthy. RoleManager.WriteToLog("Information", return RoleStatus.Healthy; "Checking Link Database"); } } // Look at every link.

VisualStudioMagazine.com · November 2009 · VISUAL STUDIO MAGAZINE 23

{ C#CORNER }

This is the idiomatic code you’ll see in many Azure applications. LEARNING REFACTORING TECHNIQUES The Start() method is an infi nite loop that sleeps for a while, Refactoring is more than a useful approach to improving the then does some work, then goes back to sleep. The work being design of existing code. It should be an important part of your done is written in a very imperative style. The end result is that regular development process. Adding features and fi xing bugs this code has practices that lead to programs that are hard to makes code harder to read, and it’s only natural to try and maintain and enhance. First of all, the actual logic for this appli- produce value by changing the smallest amount of code to limit cation is mixed in with boilerplate code that would be common accidental regressions. But over time, these small changes pile on almost every worker role you’ll create. Second, there’s too up, making code less readable and ultimately incomprehensible. much emphasis on how a worker role should be coded when you It doesn’t have to be that way. want your code to show what your worker role does. Finally, It’s a good practice to refactor existing code before adding you know that when you need to create a new worker role, new features or fi xing bugs. Your goal should be to modify the you’ll copy this code. You’ll paste it into your new worker role, structure of your code, improving it, so that it still clearly communi- and you’ll modify it to suit the needs of the new worker role. cates your design when you’ve fi nished fi xing the bug or added the The goal of modifying this class is to separate the parts that new feature. It takes practice to develop that skill. You may feel like are specifi c to this worker role with the code you’ll use in any you’re just moving code when you perform refactorings, and that

Azure worker role. To make it easier to integrate into any Azure appli- can certainly be one outcome. The key is to have a goal in mind that cation, you can design the API using extension methods on the ensures you’re actually improving the quality of your code. Microsoft.ServiceHosting.ServiceRuntime.RoleEntryPoint class. If you’re not familiar with refactoring techniques, I strongly The fi rst step is to create a method that can handle the common recommend reading “Refactoring: Improving the Design of Existing functionality in your Start() method. The common actions are to Code” by Martin Fowler (Addison-Wesley Professional, 1999) sleep for some period, perform some action, and then determine and “Working Eff ectively with Legacy Code” by Michael Feathers if you continue processing requests. That functionality can be (Prentice Hall PTR, 2004). These two references explain several easily represented by this extension method: diff erent techniques and the motivation behind many of the refactorings you may use to improve your code. public static void RunWorker( One of the best ways to get practice refactoring code is to this RoleEntryPoint role, work with samples and labs. The labs are designed to show a TimeSpan sleepTime, particular technique or library feature. While not intended to be Func method) production code, they can be adapted for your own use and can { save you time by giving you working code to start from. do While creating the sample app for this month’s column, I { started with one of the Azure samples provided by Microsoft. I Thread.Sleep(sleepTime); modifi ed the sample to add the features I needed, then started } while (method()); refactoring to get the structure I wanted. The advantage is that } you start with a working application, and at every step you keep a working application. Each step should improve the quality of Next, you should look at what’s being done at each step. This worker the code, and each step should make the code more general and role does its work using items located in Azure Table Storage. That’s easier to reuse in many diff erent applications. When do you stop? going to be a common pattern: run some query against an Azure When you can’t think of changes that would improve the sample Table, process some elements, and then save the changes back to in ways that make it easier to use in your applications. —B.W. that same table. That’s another useful extension method. Azure Table items are accessed from a Service Context as an IQueryable, for some T. An extension method to take some action against items in a action(item); table and then save those changes looks like this: }

public static void ProcessTableData( ForAll is a help method that provides a simple interface to take this IQueryable sequence, action against all items in a sequence. ProcessTableData isn’t Action action, that complicated of a method, because you can form your query TableStorageDataServiceContext context) in the calling code. Any LINQ code would work to fi lter the { table (where, take, skip, orderby, or any other LINQ method). In sequence.ForAll(action); fact, that’s what I’m doing in my Start() method. The refactored context.SaveChanges(); Start() method looks like this: } public override void Start() public static void ForAll(this IQueryable { sequence, Action action) RoleManager.WriteToLog("Information", { "Worker Process entry point called"); foreach (T item in sequence) StorageAccountInfo accountInfo =

24 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com Instantly Search

StorageAccountInfo.GetAccountInfoFromConfiguration( Terabytes of Text "TableStorageEndpoint"); LinkDataServiceContext context = N 25+ full-text new LinkDataServiceContext(accountInfo); and fielded data search this.RunWorker(TimeSpan.FromSeconds(30), () => options (with { RoleManager.WriteToLog("Information", Unicode "Checking Link Database"); support for context.WebLinkDataCollection. hundreds of Where((link) => international (!link.LinkValid) || DateTime.Now - languages) link.LastVisit > TimeSpan.FromDays(1)). N Built-in file parsers / ProcessTableData((item) => converters CheckLink(item), context); highlight hits return true; in popular }); } file types N Spider The other common pattern for a worker role is to pull messages supports Desktop with Spider off a queue and process each message. For example, one Azure sample has this code: static and Network with Spider dynamic // retrieve messages and write them to the web data; Publish (portable media) //development fabric log highlights WebWeb with Spider includes while (true) hits with { links, Engine for Linux 64-bit Thread.Sleep(10000); formatting Engine for Win & .NET if (queue.DoesQueueExist()) and images { intact Message msg = queue.GetMessage(); N API supports .NET, C++, Java, SQL, etc. if (msg != null) .NET Spider API { RoleManager.WriteToLog("Information", The Smart Choice for Text Retrieval® string.Format( "Message '{0}' processed.", since 1991 msg.ContentAsString())); queue.DeleteMessage(msg); “Bottom line: dtSearch manages a terabyte } of text in a single index and returns results } } in less than a second” — InfoWorld dtSearch “covers all data sources … That’s hardly reusable, and you know hundreds of developers powerful Web-based engines” — eWEEK have already copied this method many times. Just like with the table storage, you can create an extension method that abstracts “Lightning fast ... performance was away the common portions of the code, and use lambda expres- unmatched by any other product” sions for the specifi c bits of work. Here’s the extension method — Redmond Magazine that contains the processing that’s common to every queue: See www.dtsearch.com for hundreds public static void ProcessQueue(this MessageQueue more reviews, and hundreds of developer queue, TimeSpan timeout, Func action) case studies { bool more = true; while (more) Fully-Functional Evaluations { Thread.Sleep(timeout); if (queue.DoesQueueExist()) 1-800-IT-FINDS • www.dtsearch.com

VisualStudioMagazine.com · November 2009 · VISUAL STUDIO MAGAZINE 25 { C#CORNER }

{ Statement of Ownership, Management and Circulation Message msg = queue.GetMessage(); (Required by 39 U.S.C. 3685, United States Postal Service)

1. Title of Publication: Visual Studio if (msg != null) 2. Publication No. 1537-002X { 3. Filing Date: 09/30/09 more = action(msg); 4. Frequency of Issue: Monthly queue.DeleteMessage(msg); 5. No. of issues published annually: 12 6. Annual Subscription Price: US $34.97, Canada/Mexico $52.97, International } $78.97 } 7. Mailing address of known office of publication: 9121 Oakdale Ave., Ste. 101, } Chatsworth, CA 91311 8. Mailing address of the headquarters of general business offices of the publisher: } Same as above. 9. Name and complete mailing address of Publisher, Editor, and Managing Editor: And here’s how you’d use it in the sample shown earlier: Henry Allain, President, 16261 Laguna Canyon Rd., Ste. 130, Irvine, CA 92618 Matt N. Morollo, Publisher, 600 Worcester Rd., Ste. 204, Framingham, MA 01702 queue.ProcessQueue(TimeSpan.FromSeconds(10), Doug Barney, VP/Editorial Director, 600 Worcester Rd., Ste. 204, Framingham, (msg) => MA 01702 { Wendy Gonchar, Managing Editor, 16261 Laguna Canyon Rd., Ste. 130, Irvine, CA 92618 RoleManager.WriteToLog("Information", 10. Owner (s): 1105 Media, Inc.: 101 Holdings, 9121 Oakdale Ave., Ste. 101, string.Format( Chatsworth,CA 91311. Listing of shareholders in 1105 Media, Inc. "Message '{0}' processed.", 11. Known Bondholders, Mortgagees, and Other Security Holders Owning or Holding 1 Percent or more of the Total Amount of Bonds, Mortgages or Other msg.ContentAsString())); Securities: return true; Nautic Partners V, L.P., 50 Kennedy Plaza, 12th Flr., Providence, RI 02903 }); Kennedy Plaza Partners III, LLC, 50 Kennedy Plaza, 12th Flr., Providence, RI 02903 Alta Communications 1X, L.P., 1X-B, L.P., Assoc., LLC, 200 Clarendon St., You may be thinking that these changes don’t really add any value. Flr. 51, Boston, MA 02116 In one sense, that’s true. The sample has the exact same functionality 12. The tax status has not changed during the preceding 12 months. 13. Publication Title: Visual Studio now that it had before I started. But that’s not the same as saying 14. Issue date for Circulation Data Below: September 2009 these changes didn't produce value. These methods have factored 15. Extent & Nature of Circulation: out common algorithms you’ll use in every worker role you create.

No. Copies of That result in itself has value: These extension methods have been Average No. Copies Single Published fully tested on the fi rst use. Copy/paste/modify reuse often Each Month During Nearest to introduces bugs, especially in the modify phase. A common source of Preceding 12 Months Filing Date those bugs is the Azure Queue processing. Notice how the extension a. Total Number of Copies (Net Press Run) 83,588 80,834 methods get the message, process it and then fi nally delete it. Often, b. Legitimate Paid/and or Requested Distribution 1. Outside County Paid/Requested Mail developers make the mistake of deleting the message as they get it, Subscriptions Stated on PS Form 3541 68,214 63,479 rather than after processing. That can create the kind of bugs that 2. In-County Paid/Requested Mail only show up very rarely, when your worker process fails to process Subscriptions Stated on PS Form 3541 573 657 3. Sales Through Dealers and Carriers, the message. That’s the kind of change that causes bugs months later. Street Vendors, Counter Sales, and Azure is very new, so it’s hard to believe we know the best Other Paid or Requested Distribution practices for Azure development. We know many of our ideas ® Outside USPS 2,270 1,203 on what’s best will change. That’s why I’m very adamant about 4. Requested Copies Distributed by Other Mail Classes Through the USPS 0 0 factoring out common algorithms. When you fi nd a better way c. Total Paid and/or Requested Circulation 71,057 65,339 to solve a particular problem, you only have one location to fi x. d. Nonrequested Distribution If you’ve duplicated—or worse, duplicated and modifi ed—code, 1. Outside County Nonrequested Copies Stated on PS Form 3541 11,080 14,757 you have to make the same fi xes in many places. That increases 2. In-County Nonrequested Copies your chance for errors and omissions. C# gives you a wealth of Distribution Stated on PS Form 3541 0 0 tools to factor out these common algorithms, and you end up being 3. Nonrequested Copies Distribution able to see your specifi c algorithms more clearly. Through the USPS by Other Classes of Mail 0 0 4. Nonrequested Copies Distributed Bill Wagner ([email protected]), author of “Eff ective C#: 50 Outside the Mail 1,198 481 Specifi c Ways to Improve Your C#” (Addison-Wesley Professional, 2004) and e. Total Nonrequested Distribution 12,278 15,238 f. Total Distribution 83,335 80,577 “More Eff ective C#: 50 Specifi c Ways to Improve Your C#” (Addison-Wesley g. Copies not Distributed 253 257 Professional, 2008), has been a commercial soft ware developer for the past 20 h. Total 83,588 80,834 years. He’s a Microsoft regional director and a Visual C# MVP. His interests i. Percent paid and/or Requested include the C# language, .NET Framework and soft ware design. Circulation 85.27% 81.09% GO ONLINE 16. Publication of Statement of Ownership for a Requester Publication is required and will be printed in the November 2009 issue of this publication. Use this FindIT code at VisualStudioMagazine.com to go directly 17. I certify that all information furnished on this form is true and complete: to these related resources. Abraham Langer, Senior Vice President, Audience Development and Digital Media READ & DOWNLOAD Wagner1109 Read and download the sample code for this article.

26 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com _ I know isthere, but it’s not being imported. Ican’t fi (September 2009)and “Working (April with MEF” 2009).Stable in MEF stable composition inMEFPreview 7, andget insight into using your missing the case, may part due be to anumber of issues: Stable Composition MEF from failing bugs when or deployment errors make aplug-in composition off container ClassInitialize inthe method: A: Stable composition wasintroduced inMEFPreview 7,and it also resulting inasilent failure. stable composition Because causes unusable. However, it creates also signifi cant debugging problems. In use mefxoruse asimilar tool. cover I’ll unit testing fi sition, Ask the see Kathleen columns “Getting Current on MEF” sition “Deploying (see Unit Tests for MEF,” p. 28).Initialize the up aunitSet test environment that mimicsyour normal compo- appears 2of .NET4.For inbeta more on MEFand stable compo- available, no exception is thrown. MEF only valid parts, exposes Q: Ihave aManaged Extensibility Framework that (MEF)part the best approach, best the and to solve deployment problems you can failurethe During development, occurs. unit testing isprobably contain, nestedthe they parts fi the missing toparts from be container the ifthere are problems in MEF withSilverlight. Learn how to work through debuggingchallengesposedby BY KATHLEEN DOLLARD Th • Th • • Th • Th eassembly isn’t deployed directory into the expected • Th • A.NETerror composing when occurs anested part • Any of problems these inanested part occur reset the AllowMultiple attribute usage namespaces e Export uses acustom uses metadata eExport attribute and doesn’t attribute eExport name ismissing, or amisspelled uses eImportis by name, and name the isincorrect especifi A .NETerror generally { ASKKATHLEEN } when it inanestedwhen Th part. occurs is tokeep applications from failing ed contract isan interface existing indiff ers stability that keeps applications that are relying on rst step isto where determine because of abadly behaved part. rst. gureout why. erent ... "UserServices not found") EndSub Assert.AreEqual(1,z.Count(),_ PublicSubMef_found_user_services() _ "DatabaseNamenotfound" ) EndSub Assert.AreEqual(1,u.Count(),_ PublicSubMef_found_database_name() _ OfIUser,Guid)) PrivatezAsIEnumerable(OfIUserServices) _ PrivateyAsIEnumerable(OfIPersistenceSync(_ _ PrivateuAsIEnumerable(OfString) _ 'Mimicnormalcomposition PrivateCompose() EndSub Finally, provide tests that the anticipated assert number of parts: where failure the and, occurs, more importantly, once they’re in If you’re doing custom composition, you may need to pull the of MEFsolution. the You can it use to of check aset direc- whether either ImportMany or Import(AllowDefault:=True): Because UserServices hasan importBecause of persistence the service, hasan import on database the persistence the service Because name, it willfail to appear database ifthe name isn’t exported. marked aspre-beta 2.It from runs command the lineand evalu- Set up non-failingSet imports for eachof anticipated the using parts service isn’tservice fails composi- exported,or persistence the service along with instructions on information the you’d like to receive. ates of aset parts. You’ll fi application, possibly deployment. inpart tories willcompose asintended. You passone or more directories place give they you confi tion. Th it willfail database ifthe name isn’t persistence exported,the iultdoaaiecm·Nvme 09· November 2009 · VisualStudioMagazine.com Th emefxtool isavailable asasample inPreview 7,also is series of unit isseries tests allow you to level determinethe causes composition to quietly fail dence thatissues are inyour elsewhere nd it bin/Diagnostics inthe directory IULSUI AAIE27 VISUAL STUDIO MAGAZINE

MEF Update { ASK KATHLEEN }

relevant parts out of mefx and include them in your application or DEPLOYING UNIT TESTS FOR MEF in a custom tool that matches your custom composition. Visual Studio unit testing creates a separate directory where it Th ere are several reasons a part may fail composition. A deploys your application to run tests. Among other things, this .NET error generally causes composition to quietly fail when it allows Visual Studio to morph your application code to include occurs in a nested part. Th is is to keep applications from failing the instrumentation code necessary to determine code coverage. because of a badly behaved part. However, it can make debugging If you’re doing unit testing on the .NET platform with Managed your application diffi cult. Th e unit test exposes the underlying Extensibility Framework (MEF), you’ll need to ensure your part problem when it explicitly creates the nested part. directories are available to the test environment. A particularly obtuse issue can occur when custom metadata You can do this by editing the local test run confi guration attributes derive from ExportAttribute: and supplying fi les and directories on the deployment tab. List all the directories that contain parts. To allow other developers on [MetadataAttribute()] your team to use the same test confi guration, you’ll want to use public class ProcessWrapperAttribute : a directory relative to the current solution: / ExportAttribute, IProcessWrapperComposition ServerBin. { If your tests fail, you’ll want to ensure correct deployment public ProcessWrapperAttribute() to the test environment before exploring other issues. Within the : base(typeof(IProcessWrapper)) solution directory, you’ll fi nd a directory named TestResults. The { } most recent directory will have an Out subdirectory that contains public string Group { get; set; } your applications deployed for testing. You can ensure the } deployment is as expected. Your test composition will often need

MEF Update to refl ect diff erent confi gurations for the test environment. Th is custom attribute allows you to hide MEF from implementing While it’s a bit troublesome to set up unit testing to resolve programmers. It also allows you to combine the export attribute stable composition errors, there’s also a real payoff . Throughout and the metadata attribute. Implementing programmers merely the rest of your development, you’ll be confi dent in the basics need to decorate their class with the single descriptive Process- of composition. And when problems occur, you’ll have a venue to Wrapper attribute: explore them outside the complexities of your application. —K.D.

[ProcessWrapper(Group = "DatabaseScripts")] to classes. You can also create an ExportCustomAttribute, which derives from ExportAttribute and resets AllowMultiple to false. Th is is a very nice enhancement. However, there’s some unfore- Th e remainder of your custom metadata attribute classes can seen quicksand here. ExportAttribute is defi ned as: derive from this ExportCustomAttribute.

[AttributeUsage( Q: I’ve seen blog posts about MEF that mention PartCreator, AttributeTargets.Class | PartInitializer and SatisfyImports. What do they do, and why can’t AttributeTargets.Field | I fi nd them in the Visual Studio betas or in MEF Preview 7? AttributeTargets.Property | AttributeTargets.Method, A: You don’t see these features because they’re only available on AllowMultiple = true, Inherited = false)] Silverlight in the current cycle. Th ese features are part of a new public class ExportAttribute : Attribute abstraction for managing the container. In an ideal, decoupled world, your code wouldn’t only be decoupled from the other AllowMultiple is set to true so you can export the same class parts, it would also be decoupled from the container itself. Using with many contracts—oft en a useful technique. But when MEF Import and Export attributes, you can remove coupling to the encounters metadata attributes that have AllowMultiple set to container, except during composition and dynamic part retrieval. true, it anticipates that you may need to store more than one Th e Silverlight version of Preview 7 introduces a new model, value for a single contract. To accommodate this, MEF stores the which abstracts the container in both of these scenarios. Instead metadata as an array, not the declared type. When MEF attempts of directly composing with 20 or so lines code, you simply call to match metadata, a type mismatch occurs and the part fails to the shared—static in C#—PartInitializer.SatisfyImports method. compose. With stable composition, the part—and any containing Th is method passes the class you wish to compose, oft en the parts requiring it—fail to appear. entry class. Imports defi ned in this class, and other imports and While that’s a rather esoteric reason, the fi x is quite simple. Your exports accessed during composition, are resolved within the custom metadata attributes should almost always be decorated with current package. It’s really that easy. One line of code instead of the AttributeUsage attribute resetting AllowMultiple to False: 20 is defi nitely a win. An example of dynamic part retrieval occurs if you’re creating [MetadataAttribute()] a new invoice page or user control. Th e GetExportedValue [AttributeUsage(AttributeTargets.Class, method of the CompositionContainer creates a new instance, AllowMultiple = false)] assuming the underlying part has a non-shared creation policy. public class ProcessWrapperAttribute : But it explicitly uses the underlying container. Th e new model ExportAttribute, IProcessWrapperComposition introduces a factory class called PartCreator(Of T). To use this class, create a fi eld for the factory and decorate To save space and illustrate additional ways you can fi ne-tune the it with the Import attribute. When you wish to create a new allowed usage of your custom attribute, I’ve also restricted usage instance, call the CreatePart method of this fi eld:

28 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com "System.ComponentModel.Composition")> Dimuser=userContext.ExportedValue() DimuserContext=userCreator.CreatePart() PrivateSubCreate_Click( FrienduserCreatorAsPartCreator(OfIUser) _ System.FieldAccessException wasunhandled simple import, Iget the following error: wide scope usingwide scope Friend the inVBor scope internal MEF scoping inSilverlight.) rules which candonewhich be by adding an EditorBrowsable data into a private fi didn’t make it into .NET4timeframe. the can mitigate by this from hiding field the IntelliSense, toclasses alter data the you intended asprivate. You of your class within assembly the and allows other eventually support container the abstraction. It just A: Thbecause isalmostcertainly you have by usercode scope inC#—andscope you InternalsVisibleTo addthe Silverlight places on refl feature won’t in.NET4.Th be cycles e didn’t release sharing Silverlight between code and .NET. At this attribute to your AssemblyInfo fi le—you’ll expose Th attribute. stated they intend to unify their models, so .NET will stated .NETwill intend so they models, their to unify an import on aprivate fi eld. MEFcan’t import accessing container. the nextquestion the (See for of adiscussion attribute to field: the Q: Iwant to useMEFin Silverlight, but when Idoa ated. Creation of theactual part is guaranteed not that solves problem, the you’ll want asolution that have to stick with direct the accessto composi- the the fi the tion container. point, ifyou needshared platform you’ll code, to fail of because unavailable imports. asLazy, same rules the means which issuescreated line up to allow it included. to be Th better your respects desired scope. by temporarily making imported fi by unfulfi isabstraction allows you to create parts without new directly eld to MEF: You might needaunifi Th Importing an instance of PartCreator follows Silverlight respectsInternalsVisibleTo the is is a very niceabstraction. Unfortunately isavery this ByVal eAsSystem.Windows.RoutedEventArgs) ByVal senderAsSystem.Object, lled parts surface when the factory iscre- factory the when surface lled parts us, if you give your fi eld because ofeld because restrictions ection. You can test this ed model ifyou’reed model e MEF team has eMEFteam has eld assembly elds public. If When I’m debugging, Visual Studio just stops while loading the the loading while stops just VisualStudio I’mWhen debugging, Frienduser _ _ If you want to ensure that outside nocode class the alters the Q: Blend 3opens my project correctly. VisualStudio 2008doesn’t. iultdoaaiecm·Nvme 09· November 2009 · VisualStudioMagazine.com importing constructor, but importing the constructor must then imported fi be visible tobe MEF. eld, you can give it private and scope include an As IUser IULSUI AAIE29 VISUAL STUDIO MAGAZINE { ASKKATHLEEN }

MEF Update { ASK KATHLEEN }

page. It never displays the Silverlight startup graphic with the circle In Visual Basic, the word GetType is used for both the and the percentage. It’s just blank, dead, frozen. What’s up? operator that returns the type (typeof in C#) and the GetType method of the .NET type Type. Th is can be confusing. eTh A: Th e most likely cause is that Blend is picking a diff erent GetType operator is fundamentally diff erent than the method, startup page. Check that the default page is set to the page that and it’s only the method that returns the underlying type of contains your Silverlight application, not a blank default page. nullables. Th e same utility function in VB looks like: Visual Studio will also sometimes display a blank screen when the XAML is invalid, but in this case, Blend wouldn’t display the Private Shared Function IsNullable(Of T)( _ application. Sometimes one tool or the other gives better mes- ByVal value As T) As Boolean sages pointing you to the solution. Dim type = GetType(T) If (Type.IsValueType) Then Q: I want to fi nd the core type of a Nullable. How do I do that? Return (Nullable.GetUnderlyingType(type) _ IsNot Nothing) A: Th ere are two scenarios, and it’s not clear which situation you’re End If working with. If you have the type available, you can simply check if Return False the return value of Nullable.GetUnderlyingType is null: End Function

private static bool IsNullable(Type type) Q: I’m getting a compiler error when I attempt to convert some C# { code containing attributes to Visual Basic. Why doesn’t this work? return Nullable.GetUnderlyingType(type) MEF Update != null; Error 1 Name 'AllowMultiple' is not declared. It’s a bit trickier if you have a variable and wish to determine whether it’s of a generic type. Th e problem arises because .NET returns A: Visual Basic uses := to assign named parameters. Th e compiler information on the underlying type of nullables. For example, attempts to fi nd a constant named AllowMultiple to compare IsValueType returns True and the GetType() method returns the with the Boolean value False. It can’t fi nd a fi eld or property by underlying type. So, GetUnderlyingType will always return null if this name so it produces the error. you retrieve the type using the GetType method. So, if you call this IsNullable method using GetType, it will always return false: Q: I’m getting this error:

Console.WriteLine(IsNullable(i.GetType())); Error 67 Argument not specified for parameter 'creationPolicy' of 'Public Sub New(creationPolicy As Microsoft MVP Deborah Kurata showed me a solution to this System.ComponentModel.Composition.CreationPolicy)'. problem, adjusted by Microsoft MVP Joacim Anderson. Th is ap- proach uses generics to grab the type, rather than using GetType(), Th e error points to a line of code that obviously has a parameter and thus sidesteps the issue of using GetType() with nullables: named creation policy. Even though it’s VB, I thought it might be a case problem because the report has a lowercase c and it keeps private static bool IsNullable(T value) resetting it to an uppercase C. { var type = typeof(T); _ { return (Nullable.GetUnderlyingType(type) A: Th e problem is there are no named parameters, only positional !=null); parameters for this attribute. VB provides a confusing error. VSM } return false; Kathleen Dollard is the chief technologist for AppVenture (www.appventure.com). } She has been a Microsoft MVP for 11 years and is a member of the INETA Speaker’s Bureau. Dollard has worked extensively with application code While GetType() works well in most situations, generic type generation and is the author of “Code Generation in Microsoft .NET” (Apress, inference of method parameters off ers an alternative approach. 2004). She speaks at dozens of conferences and user groups each year, and is In addition to solving this issue, you can use this approach when also active in the Northern Colorado .NET SIG, Denver Visual Studio User working with anonymous types. Group, Northern Colorado Architect’s Group and IASA Denver.

Using Import and Export attributes, you can remove coupling to the container, except during composition and dynamic part retrieval.

30 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com Advertising Sales Ad Index

ID Statement Advertiser Page East Visual Studio Magazine (ISSN 1537-002X) is published monthly by 1105 Media, Inc., 9121 Oakdale /n Software Inc. 17 www.nsoftware.com Matt Morollo Avenue, Ste. 101, Chatsworth, CA 91311. Periodicals VP, Publishing postage paid at Chatsworth, CA 91311-9998, and Accusoft Pegasus 29 www.accusoft.com Phone: 508-532-1418 at additional mailing offi ces. Complimentary subscrip- [email protected] Aspose C3 tions are sent to qualifying subscribers. Annual www.aspose.com subscription rates for non-qualifi ed subscribers are: ComponentArt, Inc. C2, 1 West U.S. $34.97, Canada $52.97 (U.S. funds); International www.componentart.com $78.97 (U.S. funds). Subscription inquiries, back Chris Kourtoglou dtSearch 25 issue requests, and address changes: Mail to: www.dtsearch.com Regional Sales Manager Visual Studio Magazine, P.O. Box 2166, Skokie, IL ESRI 9, 21 Phone: 650-579-0121 60076-7866, email [email protected] or call www.esri.com [email protected] toll free (888) 768-8759, fax number 847-763-9564. FarPoint C4 International calls 847-763-9135. POSTMASTER: www.fpoint.com National Accounts Director Send address changes to Visual Studio Magazine, Intel Corporation 2 www.intel.com William Smith P.O. Box 2166, Skokie, IL 60076-7866. Canada Publications Mail Agreement No: 40612608. Return LEAD Technologies, Inc. 13 Phone: 603-886-3466 www.leadtools.com [email protected] Undeliverable Canadian Addresses to Circulation Dept. or Bleuchip International, P.O. Box 25542, London, ON SAP 5 www.sap.com N6C 6B2. Microsoft Account Manager SharePoint Virtual Conference & Expo 22 http://sharepointvcx.com Danna Vedder Copyright Statement Phone: 253-514-8015 TechExcel 19 © Copyright 2009 by 1105 Media, Inc. All rights www.techexcel.com [email protected] reserved. Printed in the U.S.A. Reproductions in whole Visual WebGui 7 or part prohibited except by written permission. Mail www.visualwebgui.com Director, Print Production requests to “Permissions Editor,” c/o Visual Studio Wayside Technology Group, Inc 11 Jenny Hernandez-Asandas Magazine, 230 California St. Suite 302, San Francisco, www.waysidetechnology.com CA 94111. Phone: 818-734-1520 ext 101 Editorial Index Fax: 818-734-1528 Legal Disclaimer [email protected] Cumulux 15 Production Coordinator The information in this magazine has not undergone www.cumulux.com any formal testing by 1105 Media, Inc. and is distrib- Epicor Software Corp. 20 Serena Barnes uted without any warranty expressed or implied. www.epicor.com Phone: 818-734-1520 ext 164 Implementation or use of any information contained Google Inc. 20 [email protected] herein is the reader’s sole responsibility. While the www.google.com [email protected] information has been reviewed for accuracy, there is iDesign Inc. 10 no guarantee that the same or similar results may be www.idesign.net achieved in all environments. Technical inaccuracies PreEmptive Solutions 10 www.preemptive.com may result from printing errors and/or new develop- ments in the industry. Red Gate Software Ltd. 10 www.red-gate.com TriSys Business Software Ltd. 20 Corporate Address www.trisys.biz Corporate Headquarters: Zend Technologies Ltd. 16 1105 Media www.zend.com 9121 Oakdale Ave. Ste 101, Chatsworth, CA 91311 www.1105media.com Media Kits Direct your Media Kit requests to Matt Morollo, VP Publishing, 508-532-1418 (phone), 508-875-6622 (fax), [email protected]

Reprints For single article reprints (in minimum quantities of 250-500), e-prints, plaques and posters contact: PARS International Phone: 212-221-9595 E-mail: [email protected] www.magreprints.com/QuickQuote.asp

List Rental This publication’s subscriber list, as well as other lists from 1105 Media, Inc., is available for rental. For more Media Kits information, please contact our list manager, Merit GO TO Direct your Media Kit requests to Matt Morollo, Direct. Phone: 914-368-1000; E-mail: 1105media@ VisualStudioMagazine.com VP Publishing, 508-532-1418 (phone), meritdirect.com; Web: www.meritdirect.com. to access the stories in this 508-875-6622 (fax), [email protected] issue, plus read exclusive online-only content.

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

Fast Data at Redmond High

After the much-delayed release of SQL Server 2005 fi nally the barrier to entry is too high. So StreamInsight could provide a came to pass at the end of its namesake year, Microsoft made a real solution. promise to release a new version of SQL Server every two to three years, from that point on. The company made good on Questions Remain that promise with SQL Server 2008. And it looks set to make What about integration between StreamInsight and other good on it again with SQL Server 2008 R2, expected sometime Microsoft technologies and products? For example, could BizTalk next summer. use StreamInsight, in some fashion, to process and buff er large, Don’t let the R2 moniker fool you: This release is no mere high-speed data streams? The BizTalk message bus provides service pack. It will contain many new features as well as new reliability, but not in a low-latency fashion. Could StreamInsight components that are practically products in their own right. One mitigate this shortcoming and take advantage of the strength? of those new components is StreamInsight, which until recently StreamInsight, BizTalk and WCF all have adapter models. Are was known by its code name, “Orinoco.” StreamInsight is there adapters in the works that could make BizTalk or WCF into Microsoft’s fi rst entry into Complex Event Processing (CEP), a StreamInsight clients? class of product that handles high-volume, low-latency data Certainly, BizTalk is a server that needs a low-latency streams. In plain English, StreamInsight handles data feeds that engine. And it appears that StreamInsight will be a low-latency are big and fast. engine that lacks an industrial-strength server/host. These products would seem made for each other, so their integration A Good Foundation, A Market Need must be imminent, right? I can’t be sure. Despite earnest inquiry As I understand it, StreamInsight is written in native code, and on my part with people on the relevant product teams, it’s not thus runs “close to the metal,” a quality that’s essential in clear that StreamInsight will make its way into, or federate with, low-latency processing. As much as I love .NET and Windows BizTalk, Dublin, WCF or anything else. It isn’t even really Communication Foundation (WCF), you still need unmanaged integrated with SQL Server; that’s just the ship vehicle. code if you want to handle mission-critical, high-speed data. It I fi nd this all a tad worrisome. If Microsoft wants to compete would seem the StreamInsight team knows this and planned against the likes of TIBCO in the fi nancial services world, or any their architecture accordingly. So far, so good. other industry where the data comes fast and furious, it needs Meanwhile, .NET is supported as a client interface. In other something like StreamInsight. But StreamInsight needs a host, words, .NET code can query the streams and process what’s in manageability and a UI, or it needs to be a value-added embedded them, and there’s actually a LINQ provider for StreamInsight to component within products that have these features. Without such facilitate this. This gives the best of both worlds: You can use fl esh and bones, StreamInsight will wither and die. Don’t believe the engine from your favorite programming environment and me? I have four words for you: SQL Server Notifi cation Services. have that engine be written in fast, native code. So the good I’m concerned that Microsoft is building something good and news continues. backing it up with marketing and planning that’s bad. And I’m That’s why, when I learned about StreamInsight, I was further worried that this is emblematic of bigger problems: pretty excited. I help run a technology consultancy in New York, a defi cient communication between product groups, lousy market city chock-full of fi nancial services clients who have applications analysis and a fascination with engineering that trumps that need StreamInsight’s kind of speed. But we’re not a C++ commercial viability. I hope my worries are unfounded, and that shop, and the middleware technologies we use today—namely StreamInsight has real insight behind it. But until I see tangible WCF and BizTalk—don’t have the ability to handle the kind of evidence of this, I’m inclined to expect otherwise. VSM workloads StreamInsight is designed for. And I know our fi rm’s not alone. High-speed, high-volume data processing has applications in operational systems, business Andrew J. Brust ([email protected]) is chief of new technology for intelligence, audit and compliance, sales and marketing and consultancy twentysix NewYork, as well as a Microsoft regional director numerous other lines-of-business and IT functions. There are and MVP. He’s also the co-author of “Programming Microsoft SQL Server plenty of fi rms that want to play in these spaces, but for many, 2008” (Microsoft Press, 2008).

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