re-architectingazurepdf.1105media.com/vsmmag/2009/70031542/vsm_911dg.pdf · 2009-11-19 · november...

36
VisualStudioMagazine.com PLUS Developers Dig into VS 2010 and .NET 4 Beta 2 Redmond Review: SQL Server 2008 R2 Microsoft’s Platform as a Service is launching this month with forklift changes based on developer feedback. NOVEMBER 2009 Volume 19, No. 11 RE-ARCHITECTING AZURE

Upload: others

Post on 11-Jun-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

VisualStudioMagazine.com

PLUSDevelopers Dig

into VS 2010 and .NET 4 Beta 2

Redmond Review: SQL Server 2008 R2

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

NO

VEM

BER

20

09

Vol

ume

19

, No.

11

RE-ARCHITECTING

AZURE

Project5 8/24/09 2:17 PM Page 1

Project5 8/24/09 2:18 PM Page 2

“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 ASSISTANTCOMPUTATIONAL 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 Corporationin the U.S. and other countries. *Other names and brands may be claimed as the property of others.

Project2 10/7/09 10:35 AM Page 1

Contents { F R A M E W O R K S }

Return to ValuesA 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 important and successful as .NET has been, the framework has pushed Microsoft to abandon much of that simplicity and de-prioritize the wants and needs of the developers who once flocked to it.”

So I’m intrigued by a streamlined alternative to Visual Studio Team Foundation Server (TFS) called TFS Basic Profile. The tooling will work with Visual Studio Team System 2010 and promises to address the product’s high cost and complex installation.

Matt Carter, director of Visual Studio product management, discussed TFS Basic Profile at the VSLive! conference in Orlando, and noted that the new product will appeal to developers who have stuck with Visual SourceSafe, Microsoft’s venerable source code-management offering. Unlike server-based TFS, TFS Basic Profile will run on a Windows Vista or Windows 7 client box.

TFS Basic Profile should appeal to current Visual SourceSafe users, but will it lure back those who left for open source alternatives like CVS or Subversion? More important, might we expect a renewed focus by Microsoft on developers who value productivity over complexity? Drop me a line at [email protected].

Michael Desmond, Editor in Chief, Visual Studio Magazine

November 2009 // Volume 19 // No. 11

VisualStudioMagazine.com · November 2009 · VISUAL STUDIO MAGAZINE 3

COV

ER IL

LUST

RAT

ION

BY

RA

ND

Y LY

HU

S

FEATURES

14 Re-Architecting AzureA year after the first technical previews of Azure, Microsoft is launching a less-ambitious platform with forklift revisions based on developer feedback.BY KATHLEEN RICHARDS

23 LANGUAGE LAB

C# Corner PAGE 23

The Azure FactorHow factoring out common patterns in your Azure worker roles can improve development.BY BILL WAGNER

Ask Kathleen PAGE 27

Stable Composition in MEFLearn how to work through debugging challenges posed by stable composition in MEF Preview 7, and get insight into using MEF with Silverlight.BY KATHLEEN DOLLARD

DEPARTMENTS

6 Letters to the Editor

8 DevDisastersTrans-Atlantic Time TrapBY ALEX PAPADIMOULIS (THEDAILYWTF.COM)

10 DevInsights DEVELOPER NEWS, REVIEWS, PRODUCT BRIEFS

News: Developers Dig into Visual Studio 2010 and .NET 4 Beta 2 PAGE 10

Product Review: ANTS Performance Profi ler PAGE 12

31 Index of Advertisers

COLUMNS

3 Frameworks BY MICHAEL DESMOND

32 Redmond Review BY ANDREW BRUST

14

Online Contents

VISUALSTUDIOMAGAZINE.COM

Scaled-Down Team Foundation ServerBY JEFFREY SCHWARTZMicrosoft hopes to convince dev shops to move from its Visual SourceSafe version control-management system to the more modern Visual Studio Team Foundation Server (TFS) by off ering a scaled-down version of TFS called TFS Basic Profi le.

FindIT code: Schwartz1109

Inside VSTS:Unit Testing with Visual Studio Team System 2008BY MICKEY GOUSSETThis three-part series on unit testing in Visual Studio Team System 2008 guides developers through the process of adopting a unit test, extending it to provide code coverage and ultimately improving it by enabling data-driven unit tests.

FindIT code: Gousset1109

Classic VB Corner:Finding the Right Tool for the JobBY KARL E. PETERSONTired of wondering which version of dumpbin or link is executing? Would you like to copy that tool you use all the time to another machine, but can’t seem to fi nd it? Here’s a little utility that can help.

FindIT code: Peterson1109

REDDEVNEWS.COM

Sam Ramji Assesses Microsoft’s Open Source AscentBY JEFFREY SCHWARTZFormer Microsoft Senior Director Sam Ramji, who served as Redmond’s open source thought-leader since 2007, has left the company to join cloud infrastruc-ture vendor Sonoa Systems. We spoke with Ramji about his eff orts to champion open source activity at Microsoft.

FindIT code: SchwartzB1109

Microsoft Launches ‘Spark’ Program BY KATHLEEN RICHARDSMicrosoft has kicked off another “Spark” program to seed the development audi-ence for its Web tools and platforms. The global program lowers the barrier to entry for Web professionals and smaller com-panies, and allows Microsoft to compete with open source software.

FindIT code: Richards1109

RDN Express:More Bandwith for Microsoft AJAXBY KATHLEEN RICHARDSMicrosoft’s new Content Delivery Network provides ASP.NET AJAX programmers the ability to host static content for free across thousands of edge servers worldwide.

FindIT code: RichardsB1109

ADTMAG.COM

Adobe Mobile Flash Blitz Includes iPhone SupportBY JOHN K. WATERSAdobe Systems’ Flash Player 10.1 will support the Apple iPhone, Microsoft Windows Mobile, Palm webOS and, early next year, Google Android and Nokia Symbian OS. Adobe and Research in Motion have agreed to co-develop a version of Flash that will run on the BlackBerry.

FindIT code: Waters1109

Mashup Interoperability AllianceBY JOHN K. WATERSIn a bid to foster interoperability among enterprise mashups, a group of 11 IT compa-nies has launched Open Mashup Alliance, an industry body that will promote and support Enterprise Mashup Markup Language, a common markup language.

FindIT code: WatersB1109

Alfresco Cloud Developer ProgramBY JEFFREY SCHWARTZLeading open source enterprise content-management software provider Alfresco has launched the Alfresco Cloud Developer Program to support programmers looking to build electronic content-management apps that can run in the cloud.

FindIT code: SchwartzC1109

4 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

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

CRYSTAL REPORTS®IT JUST WORKSA LEADER IN REPORTINGMore than 5 million units shipped todevelopers since 1992.

THAT WORKSIntegrate 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 INNOVATIONSEmbed Flash to create compelling mashups, manage dashboards and reports on a single server, and shareinteractive reports affordably via new licensing options.

TEST DRIVE IT TODAY:Visit us at sap.com/crystalreports/devor contact us at 1-888-333-6007.

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 itsaffi 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.

1996 to 2008

Project7 8/7/09 3:43 PM Page 1

6 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

Letters

A reader responds to Redmond Review columnist Andrew J. Brust’s contention that Entity Framework isn’t helping .NET developers (“The Value of Known Entities,” September 2009).

My own sentiments rarely resonate with commentary from the “talking heads” in our fi eld. But with regard to the “impedance mismatch” between objects and relational—and all the hype that’s built around trying to connect the

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 developers who enjoy the power of relational technology and want access to it. Such developers want to write their own queries, or may want to let their database administrators do so and then call the stored procedures that result. 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.”

In the applications I build—demand planning, pricing systems and sell-through analysis—I usually must deal with not only the relational structures and the object structures, but the representation of that entity and its related entities on the screen. This often resembles neither the object nor the table and its relations. Instead, it needs to be rendered in a way that accommodates the user’s “view” of the entity and all of its relevant, and usually de-normalized, data in the context of that particular application—much like a virtual set of objects built specifi cally for a task. ADO.NET gives me most of the tools I need to construct a data layer in which to build these views with a high degree of fi delity to the application’s purpose.

Sure, I have some complaints about features and capabilities that I feel are 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 they’re taking me a step further away from the database. This forces me to adopt the new tool’s scope as a range of what I can and can’t do to get my application close to the user’s perspective.

Walter J. ZielenskiPresident, Applied Business Systems Inc.

Teterboro, N.J.

VisualStudioMagazine.comNovember 2009 • Volume 19 • No. 11

Editorial Staff

Vice President, Doug BarneyEditorial Director

Editor in Chief Michael DesmondExecutive Editor Kathleen Richards

News Editor Jeff rey SchwartzManaging 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,John K. Waters

Art Staff

Creative Director Scott Shultz Graphic Designer Erin Horlacher

Online/Digital Media

Editor, VisualStudio Becky NagelMagazine.com

Executive Editor, New Media Michael DomingoOnline News Editor Kurt Mackie

Associate Editor, Web Gladys RamaWeb Producer Shane Lee

President Henry AllainVice President, Publishing Matt N. Morollo

Director of Marketing Michele ImgrundOnline Marketing Director Tracy S. Cook

President & Neal VitaleChief Executive Offi cer

Senior Vice President Richard Vitale& Chief Financial Offi cer

Executive Vice President Michael J. Valenti

Vice President, Finance Christopher M. Coates& Administration

Vice President, Digital Media, Abraham M. LangerAudience Development

Vice President, Information Erik A. Lindgren Technology & Web OperationsVice President, Digital Media, Doug Mashkuri

Advertising Vice President, Carmel McDonagh

Attendee Marketing

Chairman of the Board Jeff rey S. Klein

REACHING THE EDITORSEditors can be reached via e-mail, fax, telephone or mail. A list of editors and contact information is available at VisualStudioMagazine.com.

E-mail: E-mail is routed to individuals’ desktops. Please use the following form: [email protected]. Do not include a middle name or middle initials.

Telephone: The switchboard is open weekdays 8:30 a.m. to 5:30 p.m. Pacifi c Time. After 5:30 p.m. you will be directed to individual extensions.

San Francisco Offi ce 415-814-0950; Fax 415-814-0961

Irvine Offi ce 949-265-1520; Fax 949-265-1528

Corporate Offi ce 818-734-1520; Fax 818-734-1528

Visual Studio MagazineThe opinions expressed within the articles and other contents herein do not necessarily express those of the publisher.

Visual Studio Magazine wants to hear from you! Send us your thoughts about recent stories, technology updates or whatever’s on your mind. E-mail us at [email protected] and be sure to include your first and last name, city and state. Please note that letters may be edited for form, fit and style. They express the views of the individual authors, and do not necessarily reflect the views of the VSM editors or 1105 Media Inc.

Letters

Project2 8/24/09 10:57 AM Page 1

8 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

SERVED UP BY ALEX PAPADIMOULIS

</DevDisasters>{ S O F T W A R E D E V E L O P M E N T G O N E W R O N G }

Tell Us Your Tale Each issue Alex Papadimoulis, publisher of the popular Web site The Daily WTF (thedailywtf.com), 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 to Executive Editor Kathleen Richards at [email protected] and put “DevDisasters” as the subject line.

Nobody believed the French. Not the entire country, or Frenchmen in general, but rather the folks who

worked at the European Branch Offi ce in Paris. The bug they described—their computer’s internal date was randomly changing—reeked of user error and seemed far too implausible to be caused by the corporate reporting system.

But the French employees relent-lessly called app support whenever their clock would mysteriously change. It was always a predictable dialog.

“Ca me fait chier,” Pierre would grumble. “The date! It just changed again!”

Moe T. was often the support developer on the other line.

“Did you try changing it back, Pierre?” he would ask. “You could also reboot.”

Random BugMoe simply could not reproduce the problem. It only seemed to happen at random, and only a few times a month. That is, until two years later, when Pierre noticed a pattern.

“If we print the GL-DLG-ADM report on the fi fth day of the month,” he explained in an e-mail, “it will ‘swap’ the day and the month on our computer. So, if my computer says it’s Oct. 5, then the report will change my computer date to May 10. But, this only will happen if the report is one page long.”

It sounded like a superstitious diagnosis to an even stranger problem, and none of the developers believed it. No matter how many times they ran a one-page GL-DLG-ADM on their machines, their computer date remained the same.

But Pierre was insistent and demanded that Moe log in to his machine to watch the problem fi rsthand. Sure enough, running GL-DLG-ADM did, in fact, change Pierre’s system date. The month

number became the day number and the day number became the month number.

With no apparent root cause, Moe off ered up a simple workaround: run single-page reports twice and, if that fails, reboot the computer. Pierre wasn’t thrilled, but was content that a non-French employee had fi nally witnessed the problem.

Back to BasicMoe went back and dug through the code, but couldn’t fi nd a thing. He looked at the report itself, the report generator, the report printer and the report runner ... and still, nothing. With other things taking precedence, and a workaround in place, the date issue fell onto the backburner.

That is, until a year later, when Moe just happened to fl ip through some VBA documentation and noticed this:

Date: returns the current system dateNote: assigning a value to Date will

change the current system date to the valueHe did a double take. “Wait a sec,” he said to himself. “VBA

lets you set the system date by setting a value to the function?” His mind immediately jumped to the bizarre French date bug. The report used VBA Macros and must have somehow been assigning a value to Date.

After another hour of digging through sub-routine after sub-routine and script after script, he fi nally found the off ending code buried in the page header macro:

' format the dateDate = month & "/" & day & _ "/" & yearOn most computers, including the

developers’, the code simply set the system date to the current month, day and year. On the French computers—where dates use the DD/MM/YYYY format—the code swapped the months and the days. And then, on the second page, it swapped them back. After the twelfth day of the month, when most reports were run, the line silently failed.

It took just a few minutes to fi x. And after three years, the French employees could fi nally stop counting forms before printing, and always making sure to print an even number of pages per workstation—or failing that, rebooting after printing, which set the PC time to network time. VSM

Trans-Atlantic Time Trap

Give your users an effective way to visualize and analyze their data

so they can make more informed decisions and solve business problems.

By subscribing to the ESRI® Developer Network (EDNSM), you have access to the complete ESRI

geographic information system (GIS) software suite for developing and testing applications on

every platform. Whether you’re a desktop, mobile, server, or Web developer, EDN provides the

tools you need to quickly and cost-effectively integrate mapping and GIS into your applications.

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

ESRI®

Developer Network Integrate Mapping and GIS into Your Applications

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.

Project6 8/13/09 12:37 PM Page 1

</DevInsight>D E VE LO P E R N E WS / / / RE V I E WS

DEVELOPER NEWS

10 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

ILLU

STR

ATIO

N B

Y SH

UTT

ERST

OCK

.CO

M

Developers Dig into Visual Studio 2010 and .NET 4 Beta 2 BY JEFFREY SCHWARTZMicrosoft’s fl agship IDE is taking an incremental step forward with the second beta release of Visual Studio 2010 and the .NET Framework 4. Microsoft released the second beta of VS 2010 and .NET 4 on Oct. 19, giving developers a month to test the latest fi x of the company’s next-generation IDE a month before its Professional Developers Conference 2009 (PDC09), set to take place in Los Angeles this month. Testers have been working with the fi rst beta since May. Microsoft is expected to talk up a bevy of new technolo-gies at PDC09. Among them will be Microsoft Azure cloud services (see “Re-Architecting Azure,” p. 14), which Microsoft Chief Software Architect Ray Ozzie will offi cially launch at the conference, one year after he outlined Redmond’s cloud vision at PDC 2008.

Ozzie will be joined by Bob Muglia, president of Microsoft’s Server and Tools business unit. Muglia is expected to reveal more about developer hooks for the recently launched Windows 7 oper-ating system and to discuss planned upgrades to key platforms in the Microsoft stack, including Offi ce, SharePoint, SQL Server, BizTalk and Application Server Extensions, which is code-named “Dublin.”

The 411 on VS 2010For developers attending PDC, VS 2010 and the .NET Framework 4 will take center stage. (For more on VS 2010, see “IDE Evolution,” April 2009, and for more on the .NET Framework, see “.NET 4 Revealed,” June 2009.) By all accounts, VS 2010 beta 2 is expected to show a healthy improvement over the fi rst release.

“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 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 track,” said Visual Studio and .NET Technical Evangelist Drew Robbins in a Channel 9 video.

Michele Leroux Bustamante, chief architect at Los Gatos, Calif.-based iDesign Inc., says she’s looking forward to the beta 2 of .NET 4. 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 (EF 4). EF 4 will include support for Plain Old CLR Objects (POCOs) and T4 templates, which Bustamante says will help more easily control how models are produced from the database schema. “I’m hoping for improved support for offl ine change tracking,” she adds.

Also, she expects to see improved F# templates in the framework. “I’ve come to believe that F# is something developers should try with an open mind, to gain a new perspective on how to write C# code better, and possibly to leverage it in appropriate layers of the application,” she notes.

Improvements to Windows Communication Foundation (WCF) Workfl ow Services in combination with Application Server Extensions should off er a viable way to build enterprise WCF services and enhance visibility into problems during development and while services run in production, Bustamante adds.

VS 2010 extensibility is another theme Microsoft is advancing. Gabriel Torok, CEO of PreEmptive Solutions, will lead a session about the VS 2010 code editor extensions. Torok says he’ll demon-strate a built-in editor that functions as an extension of VS 2010. The code editor provides in-line visualization of usage and stability data collected from applications in production via PreEmptive’s Runtime Intelligence Services. “The idea that you can take data from production code that’s usage data, performance data, stability data, and surface it inside the code editor is revolutionary,” Torok says. “No one has seen anything like that before.” VSM

Jeff rey Schwartz ([email protected]) is news editor of VSM.

VS

20

10 a

nd

.N

ET

4 B

eta

2

programmersparadise.com866-719-1528

Your best source for software development tools!

Prices subject to change. Not responsible for typographical errors.

®

programmers.com/theimagingsource

Download a demo today.

NEWRELEASE!

Professional EditionParadise #

T79 02101A02$848.99

programmers.com/ca

CA ERwin® Data Modelerr7.3 – Product Plus 1 YearEnterprise MaintenanceCA ERwin Data Modeler is a data modelingsolution that enables you to create and maintain databases, data warehouses and enterprise data resource models. These models help you visualize data structures so that you can effectively organize, manage and moderate data complexities, database technologies andthe deployment environment.

• .NET WinForms control for VB.NET and C#• ActiveX for VB6, Delphi, VBScript/HTML, ASP• File formats DOCX, DOC, RTF, HTML, XML, TXT• PDF and PDF/A export, PDF text import• Tables, headers & footers, text frames, bullets,

structured numbered lists, multiple undo/redo,sections, merge fields, columns

• Ready-to-use toolbars and dialog boxes

TX Text Control 15Word Processing ComponentsTX Text Control is royalty-free, robust and powerful word processing software in reusable component form.

programmers.com/farpoint

FarPoint Spread for Windows FormsThe Best Grid is a Spreadsheet. Give your usersthe look, feel, and power of Microsoft® Excel®,without needing Excel installed on their machines.Join the professional developers around theworld who consistently turn to FarPoint Spreadto add powerful, extendable spreadsheet solu-tions to their COM, ASP.NET, .NET, BizTalk Serverand SharePoint Server applications.

• World’s #1 selling development spreadsheet • Read/Write native Microsoft Excel Files• Cross-sheet formula referencing• Fully extensible models• Royalty-free, run-time free

Paradise # F02 01101A01 $936.99

dtSearch Engine for Win & .NETAdd dtSearch‘s “blazing speeds” (CRN Test Center) searching and file format support• dozens of full-text and fielded

data search options• file parsers/converters for hit-highlighted

display of all popular file types• Spider supports dynamic and static web data;

highlights hits with links, images, etc. intact• API supports .NET, C++, Java, SQL and more;

new .NET Spider API

“Bottom line: dtSearch manages a terabyte of text in a single index and returns results in less than a second.” —InfoWorld

programmers.com/dtsearch

3 Server PackParadise #

D29 02101A08 $2,375.99

New64-bit

Version!

programmers.com/pragma

Pragma Fortress SSH—SSH Server for Windows by Pragma SystemsContains Windows SSH & SFTP Servers. Certifiedfor Windows Server 2008. Works with PowerShell.

• Full-featured server with centralized & graphical management

• GSSAPI Kerberos & NTLM authentication• Fastest SFTP & SCP file transfer• Supports over 1000 sessions• Runs console applications & allows history

scroll back within the same session• Runs in Windows 2008/2003/Vista/XP/2000Paradise #

P35 04100A01 $698.99

Paradise # P26 04201E01$3,951.99

programmers.com/unify

Unify SQLBase Embedded Databaseby UnifySQLBase is an easy to deploy database for building desktop and Web applications in server environments without a DBA.

• Small footprint• Zero admin deployment• GUI admin • Embed it and forget it

For applications with encrypted security, we offer SQLBase Treasury.

Reduce your database costs and simplify maintenance with Unify SQLBase.

Paradise # C15 03101A01

$143.99

programmers.com/vSphere

FREE WEBINAR SERIES:MORE Maximum Data Modeling with CA ERwin 7.3 In our last webinar series, we looked at CAERwin’s core functionality. In this second series,we’ll provide a grounding in how CA ERwin r7.3’snew features help you with Master Data Management, MetadataManagement, Data Warehousing, Data Governance and Business Intelligence.

There will be six sessions in the series:• What’s New in CA ERwin 7.3• MDM (Master Data Management) with CA ERwin and Data

Profiling tool• Collaborative model management with CA ERwin ModelManager• Validate the integrity of your model with CA ERwin Validator• Reporting: Crystal Reports, PDF, HTML• SAPHIR Option: light at the end of the metadata tunnel

CA ERwin r7.3

REGISTER TODAY: programmers.com/MDM_2009

programmers.com/sparxsystems

Enterprise Architect 7.5Visualize, Document and Control Your Software Projectby Sparx SystemsEnterprise Architect is a comprehensive,integrated UML 2.1 modeling suite providing key benefits at each stage ofsystem development. Enterprise Architect7.5 supports UML, SysML, BPMN andother open standards to analyze, design,test and construct reliable, well under-stood systems. Additional plug-ins arealso available for Zachman Framework,MODAF, DoDAF and TOGAF, and to integrate with Eclipse and Visual Studio2005/2008.

Corporate Edition1-4 Users

Paradise # SP6 03101A02

$182.99

programmers.com/LEAD

LEADTOOLS Recognition SDK v16.5by LEAD TechnologiesDevelop robust 32/64 bit document imaging and recognition functionality into your applications with accurate and high-speed multi-threaded OCR, OMR, and1D/2D barcode engines.• Supports text, OMR, image, and

barcode fields• Auto-registration and clean-up to

improve recognition results• Provided as both high and low

level interface• Includes comprehensive confidence

reports to assess performance

Paradise # L05 26301A01 $3,214.99

NEWRELEASE!

programmers.com/solarwinds

Orion Network Performance Monitorby SolarwindsOrion Network Performance Monitor is a comprehensive fault and network performance management platform that scales with the rapid growth of your network and expands with your network management needs. It offers out-of-the-box network-centric views that are designed to deliver the critical information network engineers need. Orion NPM is the easiest product of its kind to use and maintain, meaning you will spend more time actually managing networks, not supporting Orion NPM.

Paradise # S4A 08201E02

$4,606.99

NewGen2

Release!

VMware vSphere Put time back into your day.Your business depends on how you spend your time. You need to manage IT costs without losing time or performance. With proven cost-effective virtualization solutions from VMware, you can:

• Increase the productivity of your existing staffthree tmes over

• Control downtime—whether planned or not

• Save more than 50% on th cost of managing,powering and cooling servers

Make your time (and money) count for morewith virtualization from VMware.

VMware Advanced

Acceleration Kit for 6 processors

Paradise # V55 78101A01

$9,234.99

programmers.com/acresso

AdminStudio & ApplicationVirtualization Packby AcressoOne Application Software Deployment Tool for Reliable MSI Packaging, ApplicationVirtualization, and Operating System Migration.Top choice of Microsoft®, Novell®, LANDesk®

and other software management solutions. Cut MSI packaging time by up to 70%, Deploy software to desktops with 99% success or better. AdminStudio is the only MSI packaging solution to support multiple virtualization formats, including Microsoft®

App-V™, VMware® ThinApp™ and Citrix® XenApp™.

ProfessionalUpgrade from any Active AS Pro + Silver MtnParadise # I21 09201S06

$4,228.99

Project1 10/9/09 10:18 AM Page 1

12 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

AN

TS

Per

form

ance

P

rofi

ler

</DevInsight>REVIEW

BY PETER VOGELYour application is behaving poorly. You’d think that having written the application yourself, you could diagnose the problem. Unfortunately, any real-world program is complex enough that it’s unlikely that even the application author himself can fully understand how the code performs under live fi re.

Th at’s where Red Gate Soft ware’s ANTS Performance Profi ler 5.1 becomes an important part of your toolkit. Th e tool enables developers to determine where their applications are really spending their time. ANTS Performance Profi ler can be used either within the Visual Studio IDE or as a stand-alone application to analyze your application in its runtime environment.

Integration with Visual StudioAft er downloading and installing ANTS Performance Profi ler, you’ll fi nd a new ANTS 5 menu added to the Visual Studio menu bar. For many Windows Forms applications you’ll be able to profi le your application just by selecting Profi le Performance from the ANTS 5 menu.

Th is will start both the profi ler and the application. However, not all applications can be profi led directly; Web Projects or Windows Services are two such applica-tions. For those applications, ANTS Performance Profi ler must be started as a stand-alone program and attached to the application. I found that when working with complex solutions containing multiple projects, some of which couldn’t be profi led directly, I couldn’t use the Profi le Performance menu choice and had to start the tool in stand-alone mode.

Aft er you start the ANTS Profi ler, the Project Profi ler Settings dialog displays, allowing you to select the executable you want to profi le. You can also attach ANTS to IIS to profi le an ASP.NET application or attach it to a Windows Service. You can then start your profi ling session, which triggers ANTS to launch your executable.

During the profi ling session, ANTS Performance Profi ler displays a graph showing key performance variables such as I/O and CPU usage. But it’s when you stop your profi ling session that the soft ware reveals its full power. In addition

to providing you with an overview of where your application spends its time, the tool also allows you to drill down to individual methods and even lines within methods. You can see how many times any method or line was called and how long, on average, each took to execute (see Figure 1).

CustomizationANTS Performance Profi ler will probably do everything you need out of the box. However, you can pick and choose which performance measures you’re interested 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, XML, database and UI. He’s written several books on application development using Microsoft tech-nologies and presents at conferences worldwide.

ANTS Performance Profi lerDiscover what your application is really doing—method by method, line by line—with Red Gate ANTS Performance Profi ler.

Figure 1. The top part of the Profi ler window lets you select a time range to review; the middle part provides a high-level overview of time spent in the application’s objects; and the lower part lets you look at time spent executing individual lines.

ANTS Performance Profi ler 5.1

Red Gate Software Ltd.

Web: www.red-gate.com

Phone: 866-997 0397

Price: $395; $494 with support and upgrades

Quick Facts: A performance profi ler for analyzing performance bottlenecks

Pros: Easy to use with detailed information organized for ready access

Cons: Integration with Visual Studio not fully realized

Project2 9/8/09 11:39 AM Page 1

14 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

????

????

????

????

? IM

AG

E CR

EDIT

Azure FEATURE

VisualStudioMagazine.com · November 2009 · VISUAL STUDIO MAGAZINE 15

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

Microsoft 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 year 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.

RE-ARCHITECTING

AZURE

16 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

FEATURE Azure

New Business PortalPDC09 marks the unveiling of the gateway to the consumption-based pricing model that’s driving Microsoft’s cloud-computing platform. With the new “business” portal, managers can determine how to purchase the Windows Azure Platform, agree to terms of use, provide payment authorization such as credit-card informa-tion and then assign the platform to a developer or development team by entering their respective Windows Live IDs.

Developers then have access to the entire Windows Azure Platform through a newly unified (common) interface to the Azure Services developer portals. This allows them to use whatever is needed from the Platform as a Service (PaaS), which at launch will consist of the Windows Azure cloud operating system, SQL Azure relational data storage and .NET Services connectivity.

The meter starts running once a developer deploys an applica-tion or storage account to the Azure staging environment, made up of virtual machines (VMs). Usage and billing metrics are pushed to the business portal in near-real time, according to Microsoft, and developers are largely shielded from the financial and legal aspects of Azure.

“The business model drives the technology,” asserts George Moore, a Microsoft software architect, who gave an overview of the new busi-ness portal in a Channel 9 interview in September. “To a large extent, the shape of the final product—like how the fabric actually works, how it’s deployed, how they count things, how the service-level agree-ments [SLAs] work—all that stuff is driven by the business team.”

Maybe that explains some of the head-spinning changes since PDC 2008. Windows Azure and the Azure Services Platform are now referred to as the Windows Azure Platform. The Windows Azure operating system, hosted on Windows Server 2008 in Microsoft’s data centers, brandishes some of the technology improvements floated at PDC 2008. The higher-level developer services—.NET Services, SQL Data Services (now SQL Azure), Live Services, SharePoint Services and Dynamic CRM Services—have been whittled down to two at launch: .NET Services and the revamped SQL Azure.

Unlocking New CapabilitiesBy most accounts, the Windows Azure OS, which consists of VMs (compute), fabric controller (resource management) and unstruc-tured data storage (Blobs, tables and queues), is stable. Developers can expect announcements around the VMs, an Azure version of 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 the community technology previews (CTPs) did not support scaling up “fixed-size” VMs. Automatic provisioning of elasticity, essen-tially the ability to spin up virtual servers as demand increases and decrease their number as it subsides, is expected in the first com-mercial release.

“It’s always been planned to have scaling out, they just haven’t implemented it,” says Roger Jennings, a developer and author of the OakLeaf Systems blog and “Cloud Computing with the Windows Azure Platform” (Wrox, 2009). “That’s supposed to be implemented in the Web release at PDC. It’s a manual process now.”

When the commercial version is launched, Jennings also expects to see final provisioning APIs so that developers can provision their VM instances with code, as well as minimum and maximum instance limits.

As advertised at PDC 2008, Microsoft has expanded Azure beyond managed code to support native code and PHP. Windows Azure Storage has also been improved in the last year with sup-port for limited transactions, among other features. The support for field streams, caches and locks talked about at PDC 2008 have yet to appear.

“When we went out with the CTP last October, it was .NET code only and it was partial trust, and so you couldn’t really run any-thing you wanted to. You had a little bit of a sandbox,” says Steve Marx, a technical strategist for the Windows Azure team. “And we opened that up around our MIX conference and said: ‘You can run native code if you want; you can run PHP and you can run in full trust.’”

The Windows Azure for PHP SDK on CodePlex targets Windows Azure Storage and provides programming interfaces for Windows Azure’s compute and management services. With the Simple Cloud API, a Zend Technologies Ltd.-sponsored open source project launched in September, PHP developers can use three reference interfaces to target multiple cloud vendors’ file storage.

Shaped by Developer FeedbackMicrosoft did listen to developers and changed course dramatically on SQL Data Services (SDS)—formerly SQL Server Data Services (SSDS)—evolving it from a schema-less data source to a fully rela-tional data storage called SQL Azure. “That was a very good move, mostly because SSDS and SDS really duplicated many of the fea-tures of conventional Azure tables,” says Jennings.

Jennings hopes to see support for encryption in SQL Azure, par-ticularly transparent data encryption for commercial and regulatory privacy. SQL Azure is on target for release quality at PDC, he says.

At press time, SQL Azure had a storage limit of 10GB, and Azure Storage Blobs could scale to 50GB. “When you talk about scaling beyond 10GB, where your app owns the logic, I think it would be really nice to be able to get some of that partitioning baked into the platform so that I don’t have to own that as a developer,” says Vishwas Lele, chief technology officer at Applied Information Sciences Inc. (AIS) and a Microsoft regional director.

AIS is working with several customers on Azure prototypes, including a client who has to do a lot of number crunching. “They can spin up the worker role when they have to do all these calcula-tions,” says Lele. Unlike Google App Engine, the worker roles and queues in Azure can run 24x7 for background processing.

Tale of Two PlatformsHow does the Windows Azure Platform integrate with the Windows Live platform? If you’re developing in Azure, do you still have access to Live Services? Microsoft doesn’t have answers to these questions at this juncture.

What’s the future of Live Mesh? According to a Microsoft spokes-woman: “Live Mesh is a sample application that takes advantage of synchronization technology in Live Services. As we announced at PDC last year, the next generation of Live Services will be the first major ship vehicle for Mesh technologies.”

How synchronization will be handled in the Windows Azure Platform remains unclear, despite some presentations that show a “Data Hub,” known as “Project Huron,” which is based on the Microsoft Sync Framework. —K.R.

Project3 3/18/09 9:10 AM Page 1

18 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

FEATURE Azure

.NET Services, which originally consisted of a service bus, access control and workflow, has had a tumultuous year. Workflow was taken offline in the summer because developers indicated that they wanted the workflow engine to be consistent with Windows Workflow Foundation 4, expected in .NET 4.

In the October CTP, access control was re-jiggered, with support for WS-* protocols “temporarily” suspended. The team indicated a decision to focus on secure access to Web REST services as more enterprises move to REST. The idea was floated at MIX and devel-oper feedback indicated that it was the right move, according to the .NET Services Team blog. The October CTP, which closely mirrors what will appear at launch, according to Microsoft, includes support for simple Web trust; two token exchange endpoints, including SAML extensions and Active Directory Federation Services (AD FS) 2.0; claims transformation; and Security Token Service.

According to the Sept. 18 blog posting by the .NET Services Team that detailed planned October CTP changes: “Once this in-frastructure is in place, we will work on future version features of

.NET Services, like Web single sign-on and rich WS-* support. In future releases, we will reinstate full support for the WS-* proto-cols, Web single sign-on, and round out the .NET Access Control Service offering in a way that spans the REST/SOAP spectrum.”

More information on how Windows Identity Foundation and AD FS fit with Azure is likely at PDC09. In August, Microsoft released Project Riviera on CodePlex, the first Azure line-of-business reference application, developed in collaboration with Cumulux. Designed to support a Customer Loyalty Management program, the sample code uses multi-tenant storage via the Windows Azure Table and SQL Azure, Silverlight 3 and several other technologies. Of particular interest is Project Riviera’s use of AD FS, formerly Geneva Framework, and the Security Token Service.

The October CTP also saw drastic changes to the service bus, which is designed to securely connect on-premises and cloud apps through WCF endpoints. Routers have temporarily been dropped. Queues were changed to simpler message buffers. WSHttpRelay

Binding was discontinued, with WS2007Relay Binding suggested as a workaround. External Endpoint Registration is no longer avail-able, but Microsoft expects to reinstate it at some point in the future.

The reshuffling of Live Services—which included the Live Framework and Live Mesh synchronization beta—out of the Azure Platform occurred in late August. David Treadwell, Microsoft corporate vice president of Live Services, announced in the Live Services blog that the Live Framework CTP would end on Sept. 8. The Windows Live Web Role template for Azure won’t be supported in future tooling.

“Largely, what this is, is that Live Framework and the team building it all sort of merged with Windows Live and just became part of that broader team,” says Windows Azure technical strategist Marx.

Developer ExperienceA major selling point of Azure for Microsoft developers is the ability to use their existing skill sets and familiar tooling to program cloud services: Windows Azure Tools for Visual Studio 2008 and Visual Studio 2010 beta 1 CTP, which includes the Windows Azure SDK. Windows Azure currently supports .NET 3.5 even if you’re using VS 2010.

To run code in the cloud, developers use the Azure Services Developer Portal to launch application code and a service model (worker and Web roles). The service model during the CTPs was quite limited, with multiple worker roles as the back-end and Web roles as the front-end just introduced in the July CTP. “The funda-mental communication model and the kinds of things you could run in those [roles] didn’t really expand, and that’s what you can look for coming to this PDC09 and even beyond, is to just open up that box and enable more and more complex services,” says Microsoft’s Marx.

The Azure Tools provide a developer fabric and storage services for creating, debugging and packaging cloud services on your local desktop using C# and VB project templates. “I’ve found that the developer fabric has gotten better,” says Lele, who has been working with the Azure technologies since PDC 2008. Developers can run

Look at your existing applications and identify what makes sense to move to the cloud. “If you have Web apps, ASP.NET or PHP, you can benefit almost instantly with the high availability that Azure provides. You can get two Web roles and you can get 99.5 percent uptime, without having to do much in terms of infrastruc-ture,” says Vishwas Lele, chief technology officer at Applied Information Sciences Inc.

The Microsoft cloud is scale-out: Make the mind shift from working with independent servers to the stateless Web. “All servers have to be identical and they all have to work in exactly the same way. That enables scale, because then I can just add another server and load balance across them and I know it’s going

to work,” says Steve Marx, a technical strategist on the Windows Azure team. “It also gives you reliability and availability: If a server goes down, you can replace it with an identical one.”

Take a look at Windows Azure Tables. “Certainly you have SQL capability now, but it makes sense to take advantage of Azure tables because they’re designed to scale and you’re forced to think about partitioning from the ground up,” says Lele. “The pricing model is really attractive. In SQL Azure, you pay $99 for 10GB, and Azure Tables are only 15 cents a GB.”

Learn how to build a Web front-end. “Anything you develop in Azure is going to have a Web front-end that’s your primary communication,” says Roger Jennings,

developer and Visual Studio Magazine contributor. “You want your front-end to be close to the data for performance.”

Revisit Service-Oriented Architecture (SOA) and Software as a Service (SaaS).

“If you use SOA and SaaS design techniques, you should be able to move your storage to the cloud fairly easily,” says Jennings. “But there’s no real data portability between Azure and any other cloud.”

Learn cloud architecture patterns. “Think about these patterns, and the REST API, so that if a client is ready to deploy to the cloud down the road, you aren’t prevented from doing so because the architecture has something that won’t gel with the cloud,” advises Lele. —K.R.

Patterns and Practices for the Cloud

Project5 10/13/09 1:32 PM Page 1

their code and storage locally using a mixed mode, where they run their code locally and use SQL Azure, Azure Storage or host every-thing in the Azure fabric.

A Service Management API and upgrade option released to the Web in September enables programmatic improvements. “So now people can do things like automate their build process and deploy to the cloud and run some tests, or something like that,” says Marx.

Early on, some developers complained about the need to create a Visual Studio solution for the cloud, particularly if they wanted to use some existing code. “We actually cleaned some of that up in the past year, so now it’s a little easier to share code between some-thing that you’re deploying to Windows Azure with something that you’re not, or make that decision later in the development cycle,” says Marx.

As early adopters like Kevin Marshall, director of product man-agement for Clarity Consulting Inc., have noted, there are also slight differences between what works locally on your desktop in Window Vista or Windows 7 and the cloud because it’s a Windows Server environment.

“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,” says Marx. “In the storage service, in particular, there are some features that we’ve released to the cloud that we haven’t put in the developer version of those services yet.”

Deployment to the staging environment in the previews was “brutally slow,” says Clarity Consulting’s Marshall, who has hosted apps on Azure and Google App Engine. Making changes to even one line of code, once an app or service has been deployed, is tedious. Azure requires that you recompile and deploy the whole app instead of making changes on the fly and patching it.

During the previews, developers had to go through an arduous process of copying their logs locally just to view them. In early October, Microsoft announced on the Windows Azure blog that it was disabling the ability to retrieve logs through the Azure portal because an improved logging system is going to be intro-duced at launch.

Not all that much has changed since the Windows Azure tools were first introduced at PDC 2008. Microsoft is primarily working on performance improvements and “fit and finish” of the tooling, says Marx.

For those concerned about security issues, Microsoft is working on a whitepaper for the PDC09 time frame that explains what is happening “under the hood,” says Marx. The cloud isn’t introducing new security concepts, he asserts, especially if users understand the virtualization model.

Hello Real WorldThe first external Azure app from Microsoft appeared in beta in late June. Called Microsoft Hohm, it’s designed to help consumers mon-itor their home energy consumption and ultimately save money.

Numerous Azure prototypes and enterprise apps are in the works. TriSys Business Software Ltd. is using SQL Azure for its TriSys Recruitment Software as a Service (SaaS). Epicor Software Corp. is migrating the enterprise search component of its ERP to Azure.

“I really want to see what they’re going to do around the small and [midsize] space,” says Bill Wagner, founder of SRT Solutions and a Visual Studio Magazine contributor. “I think the current pricing model works well for a large enterprise, but I really don’t think it’s competitive against PHP and LAMP stack hosting for smaller busi-ness. I think they need an offering to get into that space.”

Marx expects many ISVs to look at Azure for building and hosting SaaS. “I think there’s a lot of benefit to these small development teams that don’t have big data centers—and don’t want to have big data centers—but want to be able to develop and deliver software over the Internet,” he explains.

One of those ISVs, Cumulux, would like to see integrated billing. “I want to give one bill to my customer,” says Ramakrishnan.

Jennings hopes to see pricing that’s competitive with Google App Engine, but he doesn’t think that’s going to happen. “Microsoft thinks [it’s] competing with Amazon,” he says.

However, like many developers, Jennings is impressed with all that has happened during the year since the first Azure previews were released. “It’s very encouraging,” he says. “I think they’ve kept most of their commitments. They’ve listened to their developers and they had the courage to make the changes when they needed to.”

Later this month, if everything goes as planned, the Windows Azure Platform will become real. As one Fortune 100 developer remarked at the Azure introduction a year ago: “We haven’t seen a lot of the application lifecycle, so there’s a promise and it’s very easy to get in—but what happens then?” We’re about to find out. VSM

Kathleen Richards ([email protected]) is executive editor of VSM.

20 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

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

AZURE PRICINGWindows Azure■ Compute: $0.12/hour■ Storage: $0.15/GB stored/month■ Storage Transactions: $0.01/10K■ Bandwidth: $0.10 in/$0.15 out/GB

SQL Azure■ Web Edition, up to 1GB relational database: $9.99/month■ Business Edition, up to 10GB relational database:

$99.99/month■ Bandwidth: $0.10 in/$0.15 out/GB

.NET Services■ Messages: $0.15/100K message operations, including

Service Bus messages and Access Control tokens■ Bandwidth: $0.10 in/$0.15 out/GBSOURCE: MICROSOFT

“Using MapIt helped us reduce our development costs and deliver a new product in record time.”

Mark SewardVice President, Software Development

E SPONDER, LLC

Easy, Fast Mapping of Your Data

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.

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

ESRI® MapIt™ is software plus online services

that enables you to create and share dynamic

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

to high quality online imagery, basemaps,

geocoding and routing services. Visualize

your data in stunning detail through

Silverlight and SharePoint.

Silverlight™ SharePoint® SQL Server® 2008

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

Discover trade area overlap to maximize sales and improve customer service.

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

Project1 10/9/09 9:35 AM Page 1

Coming to a desktop near you – it’s the

SharePoint 2010 Virtual Conference & Expo… and it’s FREE!We’ve heard from you that it’s hard to get out of the office these days and training dollars are limited, so we’re bringing you a FREE virtual event on one of the most anticipated software releases – SharePoint 2010 – live from the convenience of your offi ce.

Keynote Address: Arpan Shah, Director,

SharePoint Product Management team, Microsoft

Enjoy Sessions On:

• The SharePoint 2010 Roadmap

• Your first look at the new SharePoint tools

• Integrating Silverlight with SharePoint 2010

With a revolutionary Virtual Expo Hall you’ll get the full-fidelity experience of a real conference, without all the travel!

Learn more and Register for Free at SharePointVCX.comUse Promo Code NQ9P03

Advisory Council

Ted Pattison

Conference Chair, Co-Founder, Author, Critical Path Training

Andrew Connell

Co-Founder, Author, Critical Path Training

Doug Barney

VP/Editorial Director,1105 Enterprise Computing Group

Paul Stubbs

Technical Evangelist for SharePoint and Office, Microsoft Corporation

r your you – it’s the

o get outdollars are virtual software

m the

irector,

m, Microsoft

t tools

nt 2010

ll get the e, without

ree

Project2 10/7/09 10:39 AM Page 1

YO U R CO D E S O U RC E

{ C # C O R N E R }

</Language Lab>IN THIS SECTION: C# Corner · 23 // Ask Kathleen · 27 ////////////////////////

The Azure FactorHow factoring out common patterns in your Azure worker roles can improve development.BY BILL WAGNER

Every Azure worker role you write will have some common code blocks. The fact is that Azure worker roles will always follow a few well-known patterns. Because of these common well-known patterns, it’s easy to fall into the trap of copying the code from your fi rst application, and modifying it to create your second. 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 parts that aren’t common. Sometimes that’s easy. Sometimes, as with worker roles, you’ll need to reach into your bag of tricks and use Action<>, Func<>, LINQ queries and extension methods to create the library you want. In this article, I’ll take a sample Azure 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 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.

One consistent problem I have is that some old Web links don’t 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 ones that no longer worked. Azure has an architecture that makes it easier to avoid that problem. An Azure worker role can periodi-cally attempt to download all the links. It marks any links that don’t work as possibly bad. The worker role class is shown here:

public class WorkerRole : RoleEntryPoint{ public override void Start() { // This is a sample worker implementation. //Replace with your logic. RoleManager.WriteToLog("Information", "Worker Process entry point called");

while (true) { Thread.Sleep(TimeSpan.FromSeconds(30)); RoleManager.WriteToLog("Information", "Checking Link Database");

// Look at every link.

// build a request and remove those that //don't work StorageAccountInfo accountInfo = StorageAccountInfo. GetAccountInfoFromConfiguration ("TableStorageEndpoint"); LinkDataServiceContext context = new LinkDataServiceContext (accountInfo);

foreach (var weblink in context. WebLinkDataCollection) { if ((!weblink.LinkValid) || (DateTime.Now - weblink. LastVisit > TimeSpan.FromDays(1))) CheckLink(weblink); context.SaveChanges(); } } }

private void CheckLink(WebLinkData weblink) { WebClient client = new WebClient(); try { var answer = client. DownloadData(weblink.Url); RoleManager.WriteToLog("Information", string.Format("link {0} is valid", weblink.Url)); weblink.LastVisit = DateTime.Now; weblink.LinkValid = true; } catch (WebException) { RoleManager.WriteToLog("Information", string.Format("link {0} FAIL", weblink.Url)); weblink.LinkValid = false; public override RoleStatus GetHealthStatus() { // pretty simple, we’re healthy. return RoleStatus.Healthy; }}

VisualStudioMagazine.com · November 2009 · VISUAL STUDIO MAGAZINE 23

Azu

re

</Language Lab>{ C # C O R N E R }

24 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

This is the idiomatic code you’ll see in many Azure applications. The Start() method is an infi nite loop that sleeps for a while, then does some work, then goes back to sleep. The work being done is written in a very imperative style. The end result is that this code has practices that lead to programs that are hard to maintain and enhance. First of all, the actual logic for this appli-cation is mixed in with boilerplate code that would be common on almost every worker role you’ll create. Second, there’s too much emphasis on how a worker role should be coded when you want your code to show what your worker role does. Finally, you know that when you need to create a new worker role, you’ll copy this code. You’ll paste it into your new worker role, and you’ll modify it to suit the needs of the new worker role.

The goal of modifying this class is to separate the parts that are specifi c to this worker role with the code you’ll use in any worker role. To make it easier to integrate into any Azure appli-cation, you can design the API using extension methods on the Microsoft.ServiceHosting.ServiceRuntime.RoleEntryPoint class. The fi rst step is to create a method that can handle the common functionality in your Start() method. The common actions are to sleep for some period, perform some action, and then determine if you continue processing requests. That functionality can be easily represented by this extension method:

public static void RunWorker( this RoleEntryPoint role, TimeSpan sleepTime, Func<bool> method){ do { Thread.Sleep(sleepTime); } while (method());}

Next, you should look at what’s being done at each step. This worker role does its work using items located in Azure Table Storage. That’s going to be a common pattern: run some query against an Azure Table, process some elements, and then save the changes back to that same table. That’s another useful extension method. Azure Table items are accessed from a Service Context as an IQueryable<T>, for some T. An extension method to take some action against items in a table and then save those changes looks like this:

public static void ProcessTableData<T>( this IQueryable<T> sequence, Action<T> action, TableStorageDataServiceContext context){ sequence.ForAll(action); context.SaveChanges();}

public static void ForAll<T>(this IQueryable<T> sequence, Action<T> action){ foreach (T item in sequence)

action(item);}

ForAll is a help method that provides a simple interface to take action against all items in a sequence. ProcessTableData isn’t that complicated of a method, because you can form your query in the calling code. Any LINQ code would work to fi lter the table (where, take, skip, orderby, or any other LINQ method). In fact, that’s what I’m doing in my Start() method. The refactored Start() method looks like this:

public override void Start(){ RoleManager.WriteToLog("Information", "Worker Process entry point called"); StorageAccountInfo accountInfo =

Azu

re

LEARNING REFACTORING TECHNIQUESRefactoring is more than a useful approach to improving the design of existing code. It should be an important part of your regular development process. Adding features and fi xing bugs makes code harder to read, and it’s only natural to try and produce value by changing the smallest amount of code to limit accidental regressions. But over time, these small changes pile up, making code less readable and ultimately incomprehensible. It doesn’t have to be that way.

It’s a good practice to refactor existing code before adding new features or fi xing bugs. Your goal should be to modify the structure of your code, improving it, so that it still clearly communi-cates your design when you’ve fi nished fi xing the bug or added the new feature. It takes practice to develop that skill. You may feel like you’re just moving code when you perform refactorings, and that can certainly be one outcome. The key is to have a goal in mind that ensures you’re actually improving the quality of your code.

If you’re not familiar with refactoring techniques, I strongly recommend reading “Refactoring: Improving the Design of Existing Code” by Martin Fowler (Addison-Wesley Professional, 1999) and “Working Eff ectively with Legacy Code” by Michael Feathers (Prentice Hall PTR, 2004). These two references explain several diff erent techniques and the motivation behind many of the refactorings you may use to improve your code.

One of the best ways to get practice refactoring code is to work with samples and labs. The labs are designed to show a particular technique or library feature. While not intended to be production code, they can be adapted for your own use and can save you time by giving you working code to start from.

While creating the sample app for this month’s column, I started with one of the Azure samples provided by Microsoft. I modifi ed the sample to add the features I needed, then started 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 the code, and each step should make the code more general and easier to reuse in many diff erent applications. When do you stop? When you can’t think of changes that would improve the sample in ways that make it easier to use in your applications. —B.W.

StorageAccountInfo.GetAccountInfoFromConfiguration( "TableStorageEndpoint"); LinkDataServiceContext context = new LinkDataServiceContext(accountInfo);

this.RunWorker(TimeSpan.FromSeconds(30), () => { RoleManager.WriteToLog("Information", "Checking Link Database"); context.WebLinkDataCollection. Where((link) => (!link.LinkValid) || DateTime.Now - link.LastVisit > TimeSpan.FromDays(1)). ProcessTableData((item) => CheckLink(item), context); return true; });}

The other common pattern for a worker role is to pull messages off a queue and process each message. For example, one Azure sample has this code:

// retrieve messages and write them to the //development fabric logwhile (true){ Thread.Sleep(10000);

if (queue.DoesQueueExist()) { Message msg = queue.GetMessage();

if (msg != null) { RoleManager.WriteToLog("Information", string.Format( "Message '{0}' processed.", msg.ContentAsString())); queue.DeleteMessage(msg); } }}

That’s hardly reusable, and you know hundreds of developers have already copied this method many times. Just like with the table storage, you can create an extension method that abstracts away the common portions of the code, and use lambda expres-sions for the specifi c bits of work. Here’s the extension method that contains the processing that’s common to every queue:

public static void ProcessQueue(this MessageQueue queue, TimeSpan timeout, Func<Message, bool> action){ bool more = true; while (more) { Thread.Sleep(timeout); if (queue.DoesQueueExist())

VisualStudioMagazine.com · November 2009 · VISUAL STUDIO MAGAZINE 25

� 25+ full-text and fielded data search options (with Unicode support for hundreds of international languages)

� Built-in file parsers / converters highlight hits in popular file types

� Spider supports static and dynamic web data; highlights hits with links, formatting and images intact

� API supports .NET, C++, Java, SQL, etc. .NET Spider API

Fully-Functional Evaluations

The Smart Choice for Text Retrieval®

since 1991

1-800-IT-FINDS • www.dtsearch.com

Instantly SearchTerabytes of Text

Network with Spider

Web with Spider

Desktop with Spider

Network with Spider

Web with SpiderPublish (portable media)Publish (portable media)

Desktop with Spider

Engine for LinuxEngine for Linux

includes

64-bit Engine for Win & .NETEngine for Win & .NET

“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 … powerful Web-based engines” — eWEEK

“Lightning fast ... performance was unmatched by any other product” — Redmond Magazine

See www.dtsearch.com for hundreds more reviews, and hundreds of developer case studies

{ Message msg = queue.GetMessage();

if (msg != null) { more = action(msg); queue.DeleteMessage(msg); } } }}

And here’s how you’d use it in the sample shown earlier:

queue.ProcessQueue(TimeSpan.FromSeconds(10), (msg) => { RoleManager.WriteToLog("Information", string.Format( "Message '{0}' processed.", msg.ContentAsString())); return true; });

You may be thinking that these changes don’t really add any value. In one sense, that’s true. The sample has the exact same functionality now that it had before I started. But that’s not the same as saying these changes didn't produce value. These methods have factored out common algorithms you’ll use in every worker role you create. That result in itself has value: These extension methods have been fully tested on the fi rst use. Copy/paste/modify reuse often introduces bugs, especially in the modify phase. A common source of those bugs is the Azure Queue processing. Notice how the extension methods get the message, process it and then fi nally delete it. Often, developers make the mistake of deleting the message as they get it, rather than after processing. That can create the kind of bugs that only show up very rarely, when your worker process fails to process the message. That’s the kind of change that causes bugs months later.

Azure is very new, so it’s hard to believe we know the best practices for Azure development. We know many of our ideas on what’s best will change. That’s why I’m very adamant about factoring out common algorithms. When you fi nd a better way to solve a particular problem, you only have one location to fi x. If you’ve duplicated—or worse, duplicated and modifi ed—code, you have to make the same fi xes in many places. That increases your chance for errors and omissions. C# gives you a wealth of tools to factor out these common algorithms, and you end up being able to see your specifi c algorithms more clearly.

Bill Wagner ([email protected]), author of “Eff ective C#: 50 Specifi c Ways to Improve Your C#” (Addison-Wesley Professional, 2004) and “More Eff ective C#: 50 Specifi c Ways to Improve Your C#” (Addison-Wesley Professional, 2008), has been a commercial soft ware developer for the past 20 years. He’s a Microsoft regional director and a Visual C# MVP. His interests include the C# language, .NET Framework and soft ware design.

GO ONLINE

Use this FindIT code at VisualStudioMagazine.com to go directly to these related resources.

READ & DOWNLOAD

Wagner1109 Read and download the sample code for this article.

26 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

{ C # C O R N E R }

Statement of Ownership, Management and Circulation

(Required by 39 U.S.C. 3685, United States Postal Service)

1. Title of Publication: Visual Studio

2. Publication No. 1537-002X

3. Filing Date: 09/30/09

4. Frequency of Issue: Monthly

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:

Henry Allain, President, 16261 Laguna Canyon Rd., Ste. 130, Irvine, CA 92618

Matt N. Morollo, Publisher, 600 Worcester Rd., Ste. 204, Framingham, MA

01702

Doug Barney, VP/Editorial Director, 600 Worcester Rd., Ste. 204, Framingham,

MA 01702

Wendy Gonchar, Managing Editor, 16261 Laguna Canyon Rd., Ste. 130, Irvine,

CA 92618

10. Owner (s): 1105 Media, Inc.: 101 Holdings, 9121 Oakdale Ave., Ste. 101,

Chatsworth,CA 91311. Listing of shareholders in 1105 Media, Inc.

11. Known Bondholders, Mortgagees, and Other Security Holders Owning or

Holding 1 Percent or more of the Total Amount of Bonds, Mortgages or Other

Securities:

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.,

Flr. 51, Boston, MA 02116

12. The tax status has not changed during the preceding 12 months.

13. Publication Title: Visual Studio

14. Issue date for Circulation Data Below: September 2009

15. Extent & Nature of Circulation:

a. Total Number of Copies (Net Press Run) 83,588 80,834

b. Legitimate Paid/and or Requested Distribution

1. Outside County Paid/Requested Mail

Subscriptions Stated on PS Form 3541 68,214 63,479

2. In-County Paid/Requested Mail

Subscriptions Stated on PS Form 3541 573 657

3. Sales Through Dealers and Carriers,

Street Vendors, Counter Sales, and

Other Paid or Requested Distribution

Outside USPS® 2,270 1,203

4. Requested Copies Distributed by

Other Mail Classes Through the USPS 0 0

c. Total Paid and/or Requested Circulation 71,057 65,339

d. Nonrequested Distribution

1. Outside County Nonrequested

Copies Stated on PS Form 3541 11,080 14,757

2. In-County Nonrequested Copies

Distribution Stated on PS Form 3541 0 0

3. Nonrequested Copies Distribution

Through the USPS by Other Classes

of Mail 0 0

4. Nonrequested Copies Distributed

Outside the Mail 1,198 481

e. Total Nonrequested Distribution 12,278 15,238

f. Total Distribution 83,335 80,577

g. Copies not Distributed 253 257

h. Total 83,588 80,834

i. Percent paid and/or Requested

Circulation 85.27% 81.09%

16. Publication of Statement of Ownership for a Requester Publication is required

and will be printed in the November 2009 issue of this publication.

17. I certify that all information furnished on this form is true and complete:

Abraham Langer, Senior Vice President, Audience Development and

Digital Media

Average No. Copies Each Month During Preceding 12 Months

No. Copies of Single Published Nearest toFiling Date

ME

F U

pd

ate

VisualStudioMagazine.com · November 2009 · VISUAL STUDIO MAGAZINE 27

</Language Lab>

{ A S K K A T H L E E N }

Stable Composition in MEFLearn how to work through debugging challenges posed by stable composition in MEF Preview 7, and get insight into using MEF with Silverlight.BY KATHLEEN DOLLARD

Q: I have a Managed Extensibility Framework (MEF) part that I know is there, but it’s not being imported. I can’t fi gure out why. How do you go about debugging missing parts?

A: Stable composition was introduced in MEF Preview 7, and it also appears in beta 2 of .NET 4. For more on MEF and stable compo-sition, see the Ask Kathleen columns “Getting Current on MEF” (September 2009) and “Working with MEF” (April 2009). Stable composition off ers stability that keeps applications that are relying on MEF from failing when bugs or deployment errors make a plug-in unusable. However, it also creates signifi cant debugging problems. In your case, the missing part may be due to a number of issues:

• Th e Import is by name, and the name is incorrect• Th e assembly isn’t deployed into the expected directory• Th e Export attribute is missing, or uses a misspelled name• Th e specifi ed contract is an interface existing in diff erent

namespaces• Th e Export uses a custom metadata attribute and doesn’t

reset the AllowMultiple attribute usage• Any of these problems occur in a nested part• A .NET error occurs when composing a nested part

With stable composition, if a part imports another part that isn’t available, no exception is thrown. MEF only exposes valid parts, resulting in a silent failure. Because stable composition causes parts to be missing from the container if there are problems in the nested parts they contain, the fi rst step is to determine where the failure occurs. During development, unit testing is probably the best approach, and to solve deployment problems you can use mefx or a similar tool. I’ll cover unit testing fi rst.Set up a unit test environment that mimics your normal compo-sition (see “Deploying Unit Tests for MEF,” p. 28). Initialize the container in the ClassInitialize method:

<ClassInitialize()> _ Public Shared Sub MyClassInitialize( ByVal testContext As TestContext) Compose()

End Sub Private Compose() ' Mimic normal composition

Set up non-failing imports for each of the anticipated parts using either ImportMany or Import(AllowDefault:=True):

<ImportMany(Utility.DatabaseNameContract)> _ Private u As IEnumerable(Of String) <ImportMany()> _ Private y As IEnumerable(Of IPersistenceSync( _ Of IUser, Guid)) <ImportMany()> _ Private z As IEnumerable(Of IUserServices)

Finally, provide tests that assert the anticipated number of parts:

<TestMethod()> _ Public Sub Mef_found_database_name() Assert.AreEqual(1, u.Count(), _ "DatabaseName not found") End Sub... <TestMethod()> _ Public Sub Mef_found_user_services() Assert.AreEqual(1, z.Count(), _ "User Services not found") End Sub

Because the persistence service has an import on the database name, it will fail to appear if the database name isn’t exported. Because UserServices has an import of the persistence service, it will fail if the database name isn’t exported, the persistence service isn’t exported, or the persistence service fails composi-tion. Th is series of unit tests allow you to determine the level where the failure occurs, and, more importantly, once they’re in place they give you confi dence that issues are elsewhere in your application, possibly in part deployment.

Th e mefx tool is available as a sample in Preview 7, also marked as pre-beta 2. It runs from the command line and evalu-ates a set of parts. You’ll fi nd it in the bin/Diagnostics directory of the MEF solution. You can use it to check whether a set of direc-tories will compose as intended. You pass one or more directories along with instructions on the information you’d like to receive. If you’re doing custom composition, you may need to pull the

A .NET error generally causes composition to quietly fail when it occurs in a nested part. Th is is to keep applications from failing

because of a badly behaved part.

relevant parts out of mefx and include them in your application or in a custom tool that matches your custom composition.

Th ere are several reasons a part may fail composition. A .NET error generally causes composition to quietly fail when it occurs in a nested part. Th is is to keep applications from failing because of a badly behaved part. However, it can make debugging your application diffi cult. Th e unit test exposes the underlying problem when it explicitly creates the nested part. A particularly obtuse issue can occur when custom metadata attributes derive from ExportAttribute:

[MetadataAttribute()] public class ProcessWrapperAttribute : ExportAttribute, IProcessWrapperComposition { public ProcessWrapperAttribute() : base(typeof(IProcessWrapper)) { } public string Group { get; set; } }

Th is custom attribute allows you to hide MEF from implementing programmers. It also allows you to combine the export attribute and the metadata attribute. Implementing programmers merely need to decorate their class with the single descriptive Process-Wrapper attribute:

[ProcessWrapper(Group = "DatabaseScripts")]

Th is is a very nice enhancement. However, there’s some unfore-seen quicksand here. ExportAttribute is defi ned as:

[AttributeUsage( AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public class ExportAttribute : Attribute

AllowMultiple is set to true so you can export the same class with many contracts—oft en a useful technique. But when MEF encounters metadata attributes that have AllowMultiple set to true, it anticipates that you may need to store more than one value for a single contract. To accommodate this, MEF stores the metadata as an array, not the declared type. When MEF attempts to match metadata, a type mismatch occurs and the part fails to compose. With stable composition, the part—and any containing parts requiring it—fail to appear.

While that’s a rather esoteric reason, the fi x is quite simple. Your custom metadata attributes should almost always be decorated with the AttributeUsage attribute resetting AllowMultiple to False:

[MetadataAttribute()] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class ProcessWrapperAttribute : ExportAttribute, IProcessWrapperComposition

To save space and illustrate additional ways you can fi ne-tune the allowed usage of your custom attribute, I’ve also restricted usage

to classes. You can also create an ExportCustomAttribute, which derives from ExportAttribute and resets AllowMultiple to false. Th e remainder of your custom metadata attribute classes can derive from this ExportCustomAttribute.

Q: I’ve seen blog posts about MEF that mention PartCreator, PartInitializer and SatisfyImports. What do they do, and why can’t I fi nd them in the Visual Studio betas or in MEF Preview 7?

A: You don’t see these features because they’re only available on Silverlight in the current cycle. Th ese features are part of a new abstraction for managing the container. In an ideal, decoupled world, your code wouldn’t only be decoupled from the other parts, it would also be decoupled from the container itself. Using Import and Export attributes, you can remove coupling to the container, except during composition and dynamic part retrieval.

Th e Silverlight version of Preview 7 introduces a new model, which abstracts the container in both of these scenarios. Instead of directly composing with 20 or so lines code, you simply call the shared—static in C#—PartInitializer.SatisfyImports method. Th is method passes the class you wish to compose, oft en the entry class. Imports defi ned in this class, and other imports and exports accessed during composition, are resolved within the current package. It’s really that easy. One line of code instead of 20 is defi nitely a win.

An example of dynamic part retrieval occurs if you’re creating a new invoice page or user control. Th e GetExportedValue method of the CompositionContainer creates a new instance, assuming the underlying part has a non-shared creation policy. But it explicitly uses the underlying container. Th e new model introduces a factory class called PartCreator(Of T).

To use this class, create a fi eld for the factory and decorate it with the Import attribute. When you wish to create a new instance, call the CreatePart method of this fi eld:

{ A S K K AT H L E E N }

ME

F U

pd

ate

28 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

DEPLOYING UNIT TESTS FOR MEF Visual Studio unit testing creates a separate directory where it deploys your application to run tests. Among other things, this allows Visual Studio to morph your application code to include the instrumentation code necessary to determine code coverage. If you’re doing unit testing on the .NET platform with Managed Extensibility Framework (MEF), you’ll need to ensure your part directories are available to the test environment.

You can do this by editing the local test run confi guration and supplying fi les and directories on the deployment tab. List all the directories that contain parts. To allow other developers on your team to use the same test confi guration, you’ll want to use a directory relative to the current solution: <SolutionDirectory>/ServerBin.

If your tests fail, you’ll want to ensure correct deployment to the test environment before exploring other issues. Within the solution directory, you’ll fi nd a directory named TestResults. The most recent directory will have an Out subdirectory that contains your applications deployed for testing. You can ensure the deployment is as expected. Your test composition will often need to refl ect diff erent confi gurations for the test environment.

While it’s a bit troublesome to set up unit testing to resolve stable composition errors, there’s also a real payoff . Throughout the rest of your development, you’ll be confi dent in the basics of composition. And when problems occur, you’ll have a venue to explore them outside the complexities of your application. —K.D.

ME

F U

pd

ate

VisualStudioMagazine.com · November 2009 · VISUAL STUDIO MAGAZINE 29

<Import()> _ Friend userCreator As PartCreator(Of IUser) Private Sub Create_Click( ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim userContext = userCreator.CreatePart() Dim user = userContext.ExportedValue()

Th is abstraction allows you to create new parts without directly accessing the container. (See the next question for a discussion of MEF scoping rules in Silverlight.)

Importing an instance of PartCreator follows the same rules as Lazy, which means issues created by unfulfi lled parts surface when the factory is cre-ated. Creation of the actual part is guaranteed not to fail because of unavailable imports.

Th is is a very nice abstraction. Unfortunately this feature won’t be in .NET 4. Th e release cycles didn’t line up to allow it to be included. Th e MEF team has stated they intend to unify their models, so .NET will eventually support the container abstraction. It just didn’t make it into the .NET 4 time frame.

You might need a unifi ed model if you’re sharing code between Silverlight and .NET. At this point, if you need shared platform code, you’ll have to stick with the direct access to the composi-tion container.

Q: I want to use MEF in Silverlight, but when I do a simple import, I get the following error:

System.FieldAccessException was unhandled by user code

Do you know what’s going on?

A: Th is is almost certainly because you have an import on a private fi eld. MEF can’t import data into a private fi eld because of restrictions Silverlight places on refl ection. You can test this by temporarily making imported fi elds public. If that solves the problem, you’ll want a solution that better respects your desired scope.

Silverlight respects the InternalsVisibleTo attribute. Th us, if you give your fi eld assembly wide scope using the Friend scope in VB or internal scope in C#—and you add the InternalsVisibleTo attribute to your AssemblyInfo fi le—you’ll expose the fi eld to MEF:

<Assembly: InternalsVisibleTo( _ "System.ComponentModel.Composition")>

The assembly-wide scope increases the surface area of your class within the assembly and allows other classes to alter the data you intended as private. You can mitigate this by hiding the field from IntelliSense, which can be done by adding an EditorBrowsable attribute to the field:

<Import()> _ <EditorBrowsable(EditorBrowsableState.Never)> _ Friend user As IUser

If you want to ensure that no code outside the class alters the imported fi eld, you can give it private scope and include an importing constructor, but the importing constructor must then be visible to MEF.

Q: Blend 3 opens my project correctly. Visual Studio 2008 doesn’t. When I’m debugging, Visual Studio just stops while loading the

{ A S K K A T H L E E N }

page. It never displays the Silverlight startup graphic with the circle and the percentage. It’s just blank, dead, frozen. What’s up?

A: Th e most likely cause is that Blend is picking a diff erent startup page. Check that the default page is set to the page that contains your Silverlight application, not a blank default page. Visual Studio will also sometimes display a blank screen when the XAML is invalid, but in this case, Blend wouldn’t display the application. Sometimes one tool or the other gives better mes-sages pointing you to the solution.

Q: I want to fi nd the core type of a Nullable. How do I do that?

A: Th ere are two scenarios, and it’s not clear which situation you’re working with. If you have the type available, you can simply check if the return value of Nullable.GetUnderlyingType is null:

private static bool IsNullable(Type type) { return Nullable.GetUnderlyingType(type) != null; }

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 information on the underlying type of nullables. For example, IsValueType returns True and the GetType() method returns the underlying type. So, GetUnderlyingType will always return null if you retrieve the type using the GetType method. So, if you call this IsNullable method using GetType, it will always return false:

Console.WriteLine(IsNullable(i.GetType()));

Microsoft MVP Deborah Kurata showed me a solution to this problem, adjusted by Microsoft MVP Joacim Anderson. Th is ap-proach uses generics to grab the type, rather than using GetType(), and thus sidesteps the issue of using GetType() with nullables:

private static bool IsNullable<T>(T value) { var type = typeof(T); if (type.IsValueType) { return (Nullable.GetUnderlyingType(type) !=null); } return false; }

While GetType() works well in most situations, generic type inference of method parameters off ers an alternative approach. In addition to solving this issue, you can use this approach when working with anonymous types.

In Visual Basic, the word GetType is used for both the operator that returns the type (typeof in C#) and the GetType method of the .NET type Type. Th is can be confusing. Th e GetType operator is fundamentally diff erent than the method, and it’s only the method that returns the underlying type of nullables. Th e same utility function in VB looks like:

Private Shared Function IsNullable(Of T)( _ ByVal value As T) As Boolean Dim type = GetType(T) If (Type.IsValueType) Then Return (Nullable.GetUnderlyingType(type) _ IsNot Nothing) End If Return False End Function

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?

<AttributeUsage(AttributeTargets.Class, _ AllowMultiple = false)>Error 1 Name 'AllowMultiple' is not declared.

A: Visual Basic uses := to assign named parameters. Th e compiler attempts to fi nd a constant named AllowMultiple to compare with the Boolean value False. It can’t fi nd a fi eld or property by this name so it produces the error.

Q: I’m getting this error:

Error 67 Argument not specified for parameter 'creationPolicy' of 'Public Sub New(creationPolicy As System.ComponentModel.Composition.CreationPolicy)'.

Th e error points to a line of code that obviously has a parameter 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 resetting it to an uppercase C.

<PartCreationPolicy(CreationPolicy:=CreationPolicy.NonShared)> _

A: Th e problem is there are no named parameters, only positional parameters for this attribute. VB provides a confusing error. VSM

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 generation and is the author of “Code Generation in Microsoft .NET” (Apress, 2004). She speaks at dozens of conferences and user groups each year, and is also active in the Northern Colorado .NET SIG, Denver Visual Studio User Group, Northern Colorado Architect’s Group and IASA Denver.

{ A S K K AT H L E E N }

ME

F U

pd

ate

30 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

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

part retrieval.

ID StatementVisual Studio Magazine (ISSN 1537-002X) is published monthly by 1105 Media, Inc., 9121 Oakdale Avenue, Ste. 101, Chatsworth, CA 91311. Periodicals postage paid at Chatsworth, CA 91311-9998, and at additional mailing offi ces. Complimentary subscrip-tions are sent to qualifying subscribers. Annual subscription rates for non-qualifi ed subscribers are: U.S. $34.97, Canada $52.97 (U.S. funds); International $78.97 (U.S. funds). Subscription inquiries, back issue requests, and address changes: Mail to: Visual Studio Magazine, P.O. Box 2166, Skokie, IL 60076-7866, email [email protected] or call toll free (888) 768-8759, fax number 847-763-9564. International calls 847-763-9135. POSTMASTER: Send address changes to Visual Studio Magazine, P.O. Box 2166, Skokie, IL 60076-7866. Canada Publications Mail Agreement No: 40612608. Return Undeliverable Canadian Addresses to Circulation Dept. or Bleuchip International, P.O. Box 25542, London, ON  N6C 6B2.

Copyright Statement© Copyright 2009 by 1105 Media, Inc. All rights reserved. Printed in the U.S.A. Reproductions in whole or part prohibited except by written permission. Mail requests to “Permissions Editor,” c/o Visual Studio Magazine, 230 California St. Suite 302, San Francisco, CA 94111.

Legal DisclaimerThe information in this magazine has not undergone any formal testing by 1105 Media, Inc. and is distrib-uted without any warranty expressed or implied. Implementation or use of any information contained herein is the reader’s sole responsibility. While the information has been reviewed for accuracy, there is no guarantee that the same or similar results may be achieved in all environments. Technical inaccuracies may result from printing errors and/or new develop-ments in the industry.

Corporate AddressCorporate Headquarters: 1105 Media9121 Oakdale Ave. Ste 101, Chatsworth, CA 91311www.1105media.com

Media KitsDirect your Media Kit requests to Matt Morollo, VP Publishing, 508-532-1418 (phone), 508-875-6622 (fax), [email protected]

ReprintsFor single article reprints (in minimum quantities of 250-500), e-prints, plaques and posters contact:PARS InternationalPhone: 212-221-9595E-mail: [email protected]/QuickQuote.asp

List RentalThis publication’s subscriber list, as well as other lists from 1105 Media, Inc., is available for rental. For more information, please contact our list manager, Merit Direct. Phone: 914-368-1000; E-mail: [email protected]; Web: www.meritdirect.com.

Advertiser Page

/n Software Inc. 17www.nsoftware.com

Accusoft Pegasus 29www.accusoft.com

Aspose C3www.aspose.com

ComponentArt, Inc. C2, 1www.componentart.com

dtSearch 25www.dtsearch.com

ESRI 9, 21www.esri.com

FarPoint C4www.fpoint.com

Intel Corporation 2www.intel.com

LEAD Technologies, Inc. 13www.leadtools.com

SAP 5www.sap.com

SharePoint Virtual Conference & Expo 22http://sharepointvcx.com

TechExcel 19www.techexcel.com

Visual WebGui 7www.visualwebgui.com

Wayside Technology Group, Inc 11www.waysidetechnology.com

Editorial IndexCumulux 15 www.cumulux.com

Epicor Software Corp. 20 www.epicor.com

Google Inc. 20 www.google.com

iDesign Inc. 10 www.idesign.net

PreEmptive Solutions 10 www.preemptive.com

Red Gate Software Ltd. 10 www.red-gate.com

TriSys Business Software Ltd. 20 www.trisys.biz

Zend Technologies Ltd. 16 www.zend.com

VisualStudioMagazine.com · November 2009 · VISUAL STUDIO MAGAZINE 31

Advertising Sales Ad Index

EastMatt Morollo VP, Publishing Phone: [email protected]

WestChris KourtoglouRegional Sales ManagerPhone: [email protected]

National Accounts DirectorWilliam SmithPhone: [email protected]

Microsoft Account ManagerDanna VedderPhone: [email protected]

Director, Print ProductionJenny Hernandez-AsandasPhone: 818-734-1520 ext 101Fax: [email protected]

Production CoordinatorSerena BarnesPhone: 818-734-1520 ext [email protected]@1105media.com

GO TO VisualStudioMagazine.comto access the stories in this issue, plus read exclusive online-only content.

Media KitsDirect your Media Kit requests to Matt Morollo, VP Publishing, 508-532-1418 (phone), 508-875-6622 (fax), [email protected]

32 VISUAL STUDIO MAGAZINE · November 2009 · VisualStudioMagazine.com

After the much-delayed release of SQL Server 2005 fi nally came to pass at the end of its namesake year, Microsoft made a promise to release a new version of SQL Server every two to three years, from that point on. The company made good on that promise with SQL Server 2008. And it looks set to make good on it again with SQL Server 2008 R2, expected sometime next summer.

Don’t let the R2 moniker fool you: This release is no mere service pack. It will contain many new features as well as new components that are practically products in their own right. One of those new components is StreamInsight, which until recently was known by its code name, “Orinoco.” StreamInsight is Microsoft’s fi rst entry into Complex Event Processing (CEP), a class of product that handles high-volume, low-latency data streams. In plain English, StreamInsight handles data feeds that are big and fast.

A Good Foundation, A Market NeedAs I understand it, StreamInsight is written in native code, and thus runs “close to the metal,” a quality that’s essential in low-latency processing. As much as I love .NET and Windows Communication Foundation (WCF), you still need unmanaged code if you want to handle mission-critical, high-speed data. It would seem the StreamInsight team knows this and planned their architecture accordingly. So far, so good.

Meanwhile, .NET is supported as a client interface. In other words, .NET code can query the streams and process what’s in them, and there’s actually a LINQ provider for StreamInsight to facilitate this. This gives the best of both worlds: You can use the engine from your favorite programming environment and have that engine be written in fast, native code. So the good news continues.

That’s why, when I learned about StreamInsight, I was pretty excited. I help run a technology consultancy in New York, a city chock-full of fi nancial services clients who have applications that need StreamInsight’s kind of speed. But we’re not a C++ shop, and the middleware technologies we use today—namely WCF and BizTalk—don’t have the ability to handle the kind of 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 intelligence, audit and compliance, sales and marketing and numerous other lines-of-business and IT functions. There are plenty of fi rms that want to play in these spaces, but for many,

the barrier to entry is too high. So StreamInsight could provide a real solution.

Questions RemainWhat about integration between StreamInsight and other Microsoft technologies and products? For example, could BizTalk use StreamInsight, in some fashion, to process and buff er large, high-speed data streams? The BizTalk message bus provides reliability, but not in a low-latency fashion. Could StreamInsight mitigate this shortcoming and take advantage of the strength? StreamInsight, BizTalk and WCF all have adapter models. Are there adapters in the works that could make BizTalk or WCF into StreamInsight clients?

Certainly, BizTalk is a server that needs a low-latency engine. And it appears that StreamInsight will be a low-latency engine that lacks an industrial-strength server/host. These products would seem made for each other, so their integration must be imminent, right? I can’t be sure. Despite earnest inquiry on my part with people on the relevant product teams, it’s not clear that StreamInsight will make its way into, or federate with, BizTalk, Dublin, WCF or anything else. It isn’t even really integrated with SQL Server; that’s just the ship vehicle.

I fi nd this all a tad worrisome. If Microsoft wants to compete against the likes of TIBCO in the fi nancial services world, or any other industry where the data comes fast and furious, it needs something like StreamInsight. But StreamInsight needs a host, manageability and a UI, or it needs to be a value-added embedded component within products that have these features. Without such fl esh and bones, StreamInsight will wither and die. Don’t believe me? I have four words for you: SQL Server Notifi cation Services.

I’m concerned that Microsoft is building something good and backing it up with marketing and planning that’s bad. And I’m further worried that this is emblematic of bigger problems: defi cient communication between product groups, lousy market analysis and a fascination with engineering that trumps commercial viability. I hope my worries are unfounded, and that StreamInsight has real insight behind it. But until I see tangible evidence of this, I’m inclined to expect otherwise. VSM

Andrew J. Brust ([email protected]) is chief of new technology for consultancy twentysix NewYork, as well as a Microsoft regional director and MVP. He’s also the co-author of “Programming Microsoft SQL Server 2008” (Microsoft Press, 2008).

</Redmond Review>

Fast Data at Redmond High

BY ANDREW BRUST

Project1 7/16/09 11:06 AM Page 1

Project1 9/11/09 9:36 AM Page 1