52
IDE IDE EVOLUTION EVOLUTION As Visual Studio 2010 takes new form, will your user experience be enhanced? APRIL 2009 Volume 19, No. 4 VisualStudioMagazine.com PLUS Build Web Parts with SharePoint Extensions Create Templates with XML Literals, WCF and LINQ Work with Managed Extensibility Framework

IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

IDEIDEEVOLUTIONEVOLUTION

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

APR

IL 2

00

9 V

olum

e 1

9, N

o. 4

VisualStudioMagazine.com

PLUS

Build Web Parts with SharePoint Extensions

Create Templates with XML Literals, WCF and LINQ

Work with ManagedExtensibility Framework

Page 2: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

SharePoint is a trademark or a registered trademark of Microsoft Corporation. DataParts is a registered trademark of Software FX, Inc. Other names are trademarks or registered trademarks of their respective owners.

BeTheMasterOnAnyPlatform

VTC–Virtual TrainingCenter for SharePoint

Project8 3/17/09 12:39 PM Page 1

Page 3: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Data visualization for every need, every platform

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

Our most popular product, Chart FX allows you to buildcharts, gauges and maps with additional vertical visualizationfunctionality for business intelligence (OLAP), geographic data,financial technical analysis, and statistical studies and formulas.Recognized for the past15 years as the innovator and industryleader in charting components, Chart FX delivers incomparablegallery options, aesthetics and data analysis features.

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

PowerGadgets puts powerful IT monitoring on your desktopand in your data sidebar. IT professionals can now create gadgetsthat consume data from WMI, Exchange, SQL Server and eventhe Windows Registry. PowerGadgets does not require anydevelopment environments,servers or browsers to run real-timegadget components such as charts, gauges and maps.

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

With the VTC – Virtual Training Center – your IT and helpdesk personnel will no longer be overloaded with SharePointquestions and training tasks. VTC is a complete program ofexpertly produced, self-paced tutorial modules designed toempower every user and maximize the value of every SharePointfeature. VTC installs in minutes on your server, allowing instanton-demand access for everyone in your organization.

Introducing our new products for SharePoint 2007

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

ChooseAHigher PowerForDataVisualization

Project8 3/17/09 12:40 PM Page 2

Page 4: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

programmersparadise.com800-445-7899

Your best source for software development tools!

Prices subject to change. Not responsible for typographical errors.

programmers.com/theimagingsource

Download a demo today.

BestSeller!

Professional EditionParadise #

T79 02101A01$919.99

®

programmers.com/sap

Crystal Reports 2008by SAP BusinessObjectsCrystal Reports 2008 is a powerful,dynamic, actionable reporting solution thathelps you design, explore, visualize, anddeliver reports via the web or embedded inenterprise applications. It enables endusers to consume reports with stunningvisualizations, conduct on report businessmodeling, and execute decisions instantlyfrom the report itself-reducing dependencyon IT and developers.

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.

programmers.com/virtualiron

Virtual Iron ExtendedEnterprise Editionby Virtual IronVirtual Iron Extended Enterprise Editionprovides the most advanced server virtualization and virtual infrastructuremanagement capabilities available at a fraction of the cost.

• Unlimited virtual servers• Virtual SMP• Local, iSCSI, FC storage• VLAN• LiveMigration• LiveMaintenance• LiveRecovery

• .NET WinForms control for VB.NET and C#• ActiveX for VB6, Delphi, VBScript/HTML, ASP• File formats DOCX, DOC, RTF, HTML, XML, TXT• PDF export without additional 3rd party

tools or printer drivers• Nested tables, headers & footers, text

frames, bullets, numbered lists, multipleundo/redo, sections, merge fields

• Ready-to-use toolbars and dialog boxes

TX Text Control 14Word 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

programmers.com/datacore

SANmelody Kit v2.0by DatacoreDataCore SANmelody overcomes the high cost barrier and complexity of traditional SAN storage. SANmelody converts standardIntel/AMD servers, blades or virtual machines(VMs) into fully capable storage servers thatvirtualize disks and serve them over existingnetworks to application servers. They are simpleto operate, take only minutes to install, and let you cost-effectively optimize, manage andprotect data storage and disk space.

Paradise # DCA 01101A06

CALL

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

Single ServerParadise #

D29 02101A07 $949.99

New64-bit

Version!

programmers.com/sparxsystems

Enterprise Architect 7.1Visualize, 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.1 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 0001

$182.99

programmers.com/lead

LEADTOOLS DocumentImaging v 16:by LEAD TechnologiesLEADTOOLS Document Imaging has every component you need to develop powerfulimage-enabled business applications includingspecialized bi-tonal image display and processing, document clean up, high-speedscanning, advanced compression (CCITTG3/G4, JBIG2, MRC, ABC) and more.• Multi-threaded OCR/ICR/OMR/

MICR/Barcodes (1D/2D)• Forms recognition/processing• PDF and PDF/A• Annotation (Image Mark-up)• C/C++, .NET, WPF - Win32/64

Paradise # L05 03201A01 $2,007.99

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 043X $91.99

programmers.com/faircom

c-treeACE™ Professional by FairComThe c-treeACE database engine is a high performancedatabase alternative proven by developers in missioncritical enterprise systems, desktop deployments, andembedded devices for over 25 years. • Complete set of APIs including ADO.NET, LINQ,

C#, C/C++, ODBC, JDBC, VCL, and dbExpress • Graphical productivity tools • Simple deployment • No DBA or ongoing administration • Low deployment licensing costs • Cross-platform support for all major platforms

including Windows, UNIX, Linux, and Mac OS X

Make your applications faster, easier to deploy,and more affordable with c-treeACE.

Paradise # F01 0131

$711.99

Paradise # C0N 11101A03

$462.99

Paradise # S4A 08201E02

$4,606.99

Paradise # V87L01101A01

$799.99

programmers.com/vmware

Paradise # V55 72101A01

CALL I

VMware Lab Automation BundleThe VMware Lab Automation bundlehelps IT administrators consolidate labinfrastructure, reduce storage costs andeliminate time-consuming provisioningtasks. Lab users benefit from on-demandaccess to system configurations while ITremains in administrative control.Includes VMware vCenter Lab Managerand VMware Infrastructure 3 for 8 CPUs,and vCenter Server.

Special promotional pricing expires April 30, 2009.

SAVE 15%off combined

MSRPs

Project1 2/24/09 11:24 AM Page 1

Page 5: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Going LargeWhen Microsoft launched .NET Framework3.0 back in November 2006, it heralded arush of frameworks, foundations, pro-gramming models and languages thatcontinues—unabated—to this day.

.NET development has, in short, gonelarge. As VSM Executive Editor KathleenRichards reports in our cover story on theevolution of Visual Studio 2010 (see “IDEEvolution,” p. 16), developers find them-selves confronted with a lot of hard deci-sions. Decisions that have lasting implica-tions both for your applications and foryour career.

Today, Visual Studio supports develop-ment for Windows PresentationFoundation, Silverlight, ASP.NET, AJAX andWinForms. And the next version extendsits reach in so many directions, it’s almostsilly. There’s ASP.NET-friendly clouddevelopment for Windows Azure, freshlyintegrated SharePoint tooling, and sup-port for parallel programming and func-tional languages like F#. And I didn’t evenmention the Dynamic Language Runtime.

Consequently, developers need tograsp the big picture even as they masterthe minutiae, which explains the changesin this issue of Visual Studio Magazine.We’ve adopted a new design, a freshapproach and a broader mission. We’ll con-tinue to provide detailed tutorials.Familiar columns including Ask Kathleen,C# Corner and On VB will appear in everyissue of VSM in our new Language Labsection (see p. 32). But you’ll also see abroader exploration of emerging tech-nologies and challenges facing develop-ers—like the changes posed by VisualStudio 2010.

So take your time. Check out the newDevDisasters department from the folksat The Daily WTF (p.8). Read AndrewBrust’s Redmond Review column (p. 48).And get back to me with your thoughtson what we can do better—I’m [email protected].

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 3

COV

ER

ILL

US

TR

AT

ION

BY

RYA

N E

TT

ER

FEATURES16 IDE Evolution

Microsoft Visual Studio 2010 promises significant changes, from advanced WPF customization to support for a number of new and updated technologies. What does the update mean for developers, and how might Visual Studio 2010 set the stage for Microsoft’s flagship IDE down the road? BY KATHLEEN RICHARDS

26 Build and Debug Web Parts with SharePoint ExtensionsThe SharePoint Extension CTP makes developing and testing Web Parts almost easy, provided you install it correctly. BY PETER VOGEL

DEPARTMENTS6 Letters to the Editor

8 DevDisasters When Aptitude Leads to Futility BY ALEX PAPADIMOULIS

10 DevInsight DEVELOPER NEWS, REVIEWS, PRODUCT BRIEFS

Microsoft Revamps SQL Data Services Cloud Database PAGE 10

Product Review: Automation Design Canvas Boasts Advanced Web Testing PAGE 12

Product Briefs: ERWin Data Modeler and ComponentOne LiveLinq PAGE 13

32 LANGUAGE LAB ON VB, C# CORNER, ASK KATHLEEN

On VB PAGE 32 Use XML Literals, WCF and LINQ to create powerful templates that can be called fromboth client- and server-side code. BY STEELE PRICE

C# Corner PAGE 40There are multiple ways to solve every problem. Strive for code that communicates your intent and makes your meaning clear for every developer using your code.BY BILL WAGNER

Ask Kathleen PAGE 42Learn how to free your application from dependencies and interchange implementations using Managed Extensibility Framework. BY KATHLEEN DOLLARD

COLUMNS3 Frameworks BY MICHAEL DESMOND

48 Redmond Review BY ANDREW BRUST

47 Index of Advertisers

{ F R A M E W O R K S }ContentsApril 2009// Volume//19 No. 4

16Michael Desmond, Editor in Chief, Visual Studio Magazine

0409vsm_TOC_003.v3 3/19/09 2:21 PM Page 3

Page 6: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com4

ILLU

ST

RA

TIO

N F

RO

M I

ST

OC

KP

HO

TO

VISUALSTUDIOMAGAZINE.COM

Practical ASP.NETCreate a Reporting Dashboard withWebPartZones (but Without WebParts): All you need to let your users customizetheir Web pages is the ability to createUserControls. BY PETER VOGEL

LOCATOR+ CODE: VS0904PV1

Classic VB CornerWorking with Multiple Monitors: Most of the time it doesn’t matter where theuser puts your application’s windows, butevery now and then you really need toknow—or even decide this for yourself.BY KARL E. PETERSON

LOCATOR+ CODE: VS0904KP1

Inside VSTSInside the TFS Databases: Get to know the ins and outs of TfsWorkItemTracking in the first part of this series covering themost useful aspects of the TFS database.BY JEFF LEVINSON

LOCATOR+ CODE: VS0904JL1

REDDEVNEWS.COM

RDN Express: The UnbearableSilverlightness of BeingWith version 3 revealed at Mix09, therewas no shortage of opinions from readers,who took some time to share theirthoughts about Silverlight’s evolution. BY KATHLEEN RICHARDS

LOCATOR+ CODE: VS0904RD1

Windows WorkFlow 4.0 Promises VastImprovementDeveloper speaking at VSLive! says forthcoming WF will be the first trulyusable version since it was released more than two years ago.BY JOHN K. WATERS.

LOCATOR+ CODE VS0904ED2

Version 1.0 ASP.NET MVC ReleasedMicrosoft released ASP.NET Model-View-Controller (MVC) version 1.0 at the MIX09conference in March. Will the ASP.NET MVC succeed in advancing a design pattern for test-driven development of enterprise-scale Web applications?BY MICHAEL DESMOND

LOCATOR+ CODE: VS0904RD3

ADTMAG.COM

Is SOA Dead?In an interview following her controversialblog post, Burton Group analyst AnnThomas Manes explains her point was toget the word out to enterprise architectsthat they need to temper expectationswhen pitching enterprise application inte-gration projects to corporate sponsors orelse they will be nixed.BY JOHN K. WATERS

LOCATOR+ CODE: VS0904AD1

Eclipse Launches Effort to DefineStandard Mobile Dev Tools Pulsar is aimed at standardizing the waysoftware is developed for different vendors’ mobile handsets using toolsbased on the open source framework.BY JOHN K. WATERS

LOCATOR+ CODE: VS0904AD2

Open Source Project Gives Java Devs a ‘Lift’The open source Lift Framework projectaims to develop a Web application frame-work that solves issues present in existingapproaches. BY JOHN K. WATERS

LOCATOR+ CODE: VS0904AD3

Online Contents

Get the complete picture—the latest dev news, analysis and how-to content—atVisualStudioMagazine.comand our partner sites in the Redmond DeveloperNetwork.

VisualStudioMagazine.com RedDevNews.com ADTmag.com

0409vsm_WTOC_004.v3 3/19/09 3:13 PM Page 4

Page 7: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Integrate Mapping and GIS into Your Applications

Give your users an effective way to visualize and analyze their data so they can make more informed

decisions and solve business problems.

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

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

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

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

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.

Subscribe to EDN and leverage the power of GIS to get

more from your data. Visit www.esri.com/edn.

Project17 1/19/09 5:24 PM Page 1

Page 8: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com6

VSM readers respond to the March 2009 cover story on the changing face ofSharePoint development.

The tools are abysmal. The best examples I’ve seen come out of Ted Pattison. Hiscommentary in the SDK videos pretty much sums it up. He says that somedayMicrosoft will produce some great and wonderful tools, but until then you needto learn the hard way.

Mike, California, posted online

The tools, quite frankly, stink. The documentation for those tools is also very,very poor. The SharePoint developer SDK is full of examples that don’t work.Many examples are trivial, too. The fact that you have to use the tools on theSharePoint server is just icing on the cake. Virtual PC is a real dog with a fullMOSS installation. On the other hand, so many of our clients are turned off by the high cost of licensing SharePoint that they decide to go in another direction instead.

JP, Kansas, posted online

Good-bye Redmond Developer NewsVSM sister publication RDN published its last print issue in February 2009. Areader shares her thoughts.

I’m disappointed that RDN is going away. When it was created I thought it wasdifferent and better than anything else for what it covered. The columns abouttechnology, the interviews and DevDisasters, too, were all good to have. I work ina data warehouse development group so we are especially interested in SQLServer and data access and data presentation. Often I would tear a page out andput it on my manager’s desk so he could read it and be aware, too.

Visual Studio Magazine is OK, but it’s different. RDN will be missed.Laura Granstedt, Bridgeport, Conn.

Letters VisualStudioMagazine.comApril 2009 • Volume 19 • No. 4

Editorial StaffVice President, Doug Barney

Editorial DirectorEditor in Chief Michael Desmond

Executive Editor Kathleen Richards

News Editor Jeffrey Schwartz

Managing Editor Wendy Gonchar

Associate Managing Editor Katrina Carrasco

Contributing Editors

Andrew J. Brust, Ken Cox, John Cronan, Dan Fergus, John Gavilan, Roger Jennings, Don Kiely,

Martin Kulov, Jeff Levinson, Bill McCarthy, John Charles Olamendy Turruellas,

Keith Pleas, Bill Wagner

Art Staff

Creative Director Scott Shultz

Graphic Designer Erin Horlacher

Online/Digital MediaEditor, VisualStudio Becky Nagel

Magazine.comExecutive Editor, New Media Michael Domingo

Online News Editor Kurt Mackie

Associate Editor, Web Gladys Rama

Web Producer Shane Lee

Director, Web Development Rita Zurcher

President Henry Allain

Vice President, Publishing Matt N. Morollo

Director of Marketing Michele Imgrund

Online Marketing Director Tracy S. Cook

President & Neal VitaleChief Executive Officer

Senior Vice President Richard Vitale& Chief Financial Officer

Executive Vice President Michael J. Valenti

President, 1105 Events Dick Blouin

Vice President, Finance Christopher M. Coates& Administration

Vice President, Digital Media, Abraham M. LangerAudience Development

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

AdvertisingVice President, Carmel McDonagh

Attendee Marketing

Chairman of the Board Jeffrey 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 thefollowing form: [email protected]. Do not include a middle name or middle initials.

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

San Francisco Office 415-814-0950; Fax 415-814-0961

Irvine Office 949-265-1520; Fax 949-265-1528

Corporate Office 818-734-1520; Fax 818-734-1528

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

SharePointReflections

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

0409vsm_Letters_6.v4 3/19/09 7:32 AM Page 6

Page 9: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

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

Page 10: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com8

Experience may be the best teacher, butfailure too often is its bitter reward. Afterall, what software developer worth his salthasn’t committed some code-bound atroci-ty or embarrassed himself with an ill-advised kludge? The thing is, good devel-opers learn from these failures to becomebetter developers.

I should know. As the author ofDevDisasters and founder of The DailyWTF Web site (www.thedailywtf.com), I’vemade it my personal mission to stand wit-ness to the painful shortcomings of soft-ware developers. The whole thing startedback in 2004, when I noticed how fre-quently programmers tend to discuss andshare anecdotes about the poorly writtencode they encounter every day. It was clearto me that developers could learn an awfullot by reading about some other guy’s uglyflameout, rather than experiencing it

themselves. And who knows, we allmight even enjoy a laugh or two

while we’re at it.So, welcome to the first

installment of DevDisastersin Visual Studio Magazine.This regular department,which has appeared inVSM’s sibling publicationRedmond DeveloperNews since 2007, willoffer readers a chance

to learn the hard lessonswithout taking the

hard hits.

A Painful LegacyThe fourth time will be the charm.

That’s what Martin F. told himself onthe first day of a new assignment. He

was the fourth consultant sent from his IT firm to work with the HR department at Pan Euro Investments (PEI), a majorEuropean banking and insurance conglomerate. Apparently, the first con-sultant walked off the job. The secondran. And the third sprinted like a bat outof hell.

“Just to warn you,” Martin’s new bossstarted, “I’ve been told that our database isa bit of a mess. Ever since Rob—the guywho built the system—left, it’s changedquite a few hands and has experienced afew ‘growing pains’ over the year.”

Growing pains was a gross under-statement. Back in the early ’90s, PEI purchased an incredibly inefficient andunreliable enterprise resource planning(ERP) system to help HR manage employ-ees. Because the system lacked so manyfeatures, the HR department had nochoice but to supplement it with applica-tions of its own. That’s where Rob camein. He was an HR specialist who “dabbled

a bit” in programming and took it uponhimself to build the HR department’s sup-plemental systems.

A decade or so later, Rob’s supple-mental applications were central to thebusiness and the ERP system had fadedout. By the time Rob left, the HR depart-ment worked with an amalgamation ofMicrosoft Access databases, VB5 applica-tions and macro-powered Excel spread-sheets, strewn across different worksta-tions and servers.

At the heart of this “system” lay thecentral database. It held monthly snap-shots of all 50,000-plus employees’ datagoing back about four years. Over thatperiod of time, the database had grown toan impressive 2 million records. And for anAccess database on a file share, thatmeant a typical “Select and Group By”query took a good eight minutes.

Diving into the HR-Access PoolRobert’s first task was to correct a fewbugs in the “provider importer.” It was anExcel-based “application” that PEI’s 100-plusdaughter companies would use each month.After the appropriate data was filled in, thespreadsheet would generate a few .CSV filesand e-mail them to a manager in PEI’s HRdepartment.

In turn, that HR manager would for-ward the e-mail to the appropriate subordi-nates, who would then do the following:

1. Process every .CSV through anAccess-based data-verification programthat output “Verified .CSVs”

2. Consolidate all the verified filesinto another Access database

3. Find and remove any duplicateemployee records

4. Export the data into “DuplicateVerified .CSVs” and import it into temporarytables of the central database

{ 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 }

SERVED UP BY ALEX PAPADIMOULIS

</DevDisasters>Coding Catastrophes

0409vsm_DevDisasters_8-9.v6 3/19/09 8:01 AM Page 8

Page 11: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 9

5. Perform the final checks and cor-rections against temporary tables and thenconsolidate to master tables

6. Run the appropriate reports andsend PDF-formatted documents to appro-priate managers at daughter companies

This song and dance tooktwo people a full week toaccomplish. After send-ing the reports to the100-plus managers,they set asidethree days forfeedback and cor-rections from thedaughter compa-nies, and thenwent back to stepone to repeat theprocess for the “final”version.

Ol’ TellerMartin had little faith that the code power-ing this ridiculous process would make anymore sense than the process itself. Peeringunder the veneer of the ordinary-lookingspreadsheet, Martin uncovered a writhingheap of undocumented VBA code thatmade him shudder.

When Martin completed the requestedbug fixes, his boss thanked him for theprompt turnaround. Then he quietly added:“Now, ahem, you just need to fix all of thedaughter companies’ importers.”

As Martin begrudgingly edited eachand every one of the 100 or so different“provider importer” spreadsheets, he plotted the ways that he could tastefullyflee like there was no tomorrow. And who knew, maybe the fifth time would bethe charm.

Death by AptitudeNothing screams sexy like an ad for a C#developer job at a well-funded start-up. Infact, when Frank’s recruiter presented theopportunity to him, Frank knew it would bea long shot. After all, he had no commercialsoftware experience and had only limitedWeb development experience. But he didknow .NET pretty well, so he figured it’d beworth a try. Maybe his skills could translateto a Web-based software company.

His first interview went surprisinglywell. They asked a lot of “aptitude” ques-tions, as they were firm believers that“experience can be gained and skills can belearned, but attitude never changes.”

Apparently, Frank showed good aptitudeand was asked back for a second interview.

When Frank came back for roundtwo, he was given the grand tour. It waseverything start-up dreams were made of:posh decor, shiny new Macbooks every-

where, an air-hockey table, freecatered meals and Aeron

chairs as far as the eyecould see. After the

interview, his future bossDerrick made Frank anoffer he couldn’trefuse.

Frank’s firstday consisted mostly

of introductions.When he finally made it

back to his desk, he could-n’t help but wonder about

some things. Things like, why would aWeb-based software company with 20 employees have only three developers on staff? And why would two of those developers bepart-time interns?

The more he thought about it, the more he worried. Frank counted four dif-ferent program managers. What tasks at thesmall company could possibly keep the NewProduct Introduction Manager or GeospatialSystems Program Manager busy all day?

“Did the company really need 10‘manager’ level positions?” Frank askedhimself. “Shouldn’t some of these peoplehave software backgrounds?”

But Frank shrugged his concerns off,reasoning that this was the type of teamneeded to build a successful start-up.

Wait … What?Once Frank finally settled into his comfyAeron chair and fired up his dual-monitorworkstation, he was ready to learn the code.This, he figured, is where it would all cometogether and make sense. He heeded his fel-low developers’ warning that things “were alittle beta-ish” and dove right in. After all oftwo minutes, he wanted to jump back out.

The pages were riddled with race con-ditions and generally only supported onerequest at a time. The developers didn’tseem to know the difference betweenCache, ViewState and Session objects, sothey just used all three simultaneously to “make things work.” As for the “helperfunctions”—they were perhaps the most unique take on .NET coding Frank had ever seen. In one baffling case, the developers created their ownareValuesDifferent method to act as awrapper for object.Equals():

public bool areValuesDifferent(object x, object y) {

... snip ...

if (0 == x.GetType().FullName.CompareTo("System.String"))if (0 != ((string)x)

.CompareTo((string)y))diff = true;

if (0 == x.GetType().FullName.CompareTo("System.Int64"))if (0 != ((long)x)

.CompareTo((long)y))diff = true;

... snip ...}

As the lead developer later told Frank,“Well, this way, it only checks the value.”

Frank took a few minutes to explainthe whole concept of “virtual” methods, andhow Equals() does exactly the same thing.His colleague shrugged his shoulders andreplied, “Hmm, I guess that would work, too.”

The really good news came later thatday, when Frank learned that the companywould be hiring some new intern developers.Well, not just any interns, only the “mostaptitudinal” that money could buy. VSM

Alex Papadimoulis is a managing partner at

Inedo LLC and publisher of the Web site The

Daily WTF (www.thedailywtf.com). He writes

DevDisasters in every issue of VSM.

The developers

didn’t seem to knowthe difference betweenCache, ViewState and

Session objects, so theyjust used all three simultaneously to

“make thingswork.”

Tell Us Your Tale

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

0409vsm_DevDisasters_8-9.v6 3/19/09 8:01 AM Page 9

Page 12: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com10

Dat

a S

erv

ices

After months of criticism that the test build of its cloud-basedSQL Data Services (SDS) lacked the horsepower for enterprise-grade applications, Microsoft is scrapping the effort and movingto a pure relational model instead.

Microsoft made the surprise move just one week before itsannual MIX09 conference in Las Vegas last month. Ironically, Thecompany announced its cloud-based database offering at MIX08,one year before. The test version of SDS that critics panned wasbased on REST and SOAP Web services interfaces.

Eliminating Web ServicesUnder the new plan, Microsoft will offer a pure relational data-base in the cloud by exposing its Tabular Data Stream (TDS)over-the-wire protocol for accessing SQL Server via its forthcom-ing Azure Services Platform.

Microsoft will support traditional relational database capa-bilities, including SQL queries and support for relational schemaand stored procedures. While the company maintains that was

always the plan, it said it will no longerexpose those capabilities by requiringthe REST Web services interface.

The move eliminates the Webservices layer and exposes TDS to SQLServer over the cloud. As a result, saysMicrosoft, developers will be able tomove data-driven code developed inMicrosoft’s T-SQL language for SQLServer over to SDS.

“We were calling it SQL Serverbut it really was not similar to a SQLServer-type experience,” explains NirajMatrani, senior product manager forSDS. “Customers preferred more withthe traditional T-SQL-based support,so we decided to go in this direction.”

Microsoft is suggesting thatthose who want to use REST-based pro-

gramming for applications that do not require arelational database management system can use

the Azure table storage. “You can still access your rela-tional data (located on premises or in the cloud) via

HTTP/REST using the ADO.NET Data Services framework,”Microsoft Senior Program Manager David Robinson wrote in ablog posting.

SDS DOAIndeed it was the similarity between Azure Tables for storageand SQL Server tables using the Entity Attribute Value (EAV)model that may have helped render Microsoft’s first test build ofSDS dead on arrival. “The two were virtually identical,” says con-sultant and Microsoft MVP Benjamin Day of Brookline, Mass.-based Benjamin Day Consulting.

The four-month test of SDS failed to meet the performanceexpectations of enterprise developers such as OakLeaf SystemsPrincipal and VSM contributor Roger Jennings, who found it wasunable to offer the scalability of the existing SQL Server. “Theyoffered some pseudo-relational features but they didn’t offer theones that people really wanted,” Jennings explains.

It also became clear that developers weren’t going to rede-velop their T-SQL application for SDS. “It highlights that chal-lenge [that], as people transition to the cloud, they’re absolutelynot going to accept two different programming models—one forinside the firewall and one for outside the firewall,” saysForrester Research Inc. analyst Jeffrey Hammond.

Microsoft Revamps SDSCloud DatabaseBY JEFFREY SCHWARTZ

D E V E L O P E R N E W S / / / R E V I E W S / / / P R O D U C T S

D E V E L O P E R N E W S

</DevInsight>

0409vsm_DevInsight_10-13.v7 3/19/09 8:06 AM Page 10

Page 13: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Develop your application with the same robust imaging technologies used by Microsoft, HP, Sony, Canon, Kodak, GE, Siemens, the US Air Force and Veterans Affairs Hospitals.

LEADTOOLS provides developers easy access to decades of expertise in color, grayscale, document, medical, vector and multimedia imaging development. Install LEADTOOLS to eliminate months of research and programming time while maintaining high levels of quality, performance and functionality.

• Image Formats: All industry standards including TIFF, EXIF, PDF, JPEG/JPEG2000, DICOM, PCL, DWG and hundreds more.•Image Compression: From standard JBIG, JBIG2, ABIC, JPEG and CCITT G3/G4 to LEAD’s specialized ABC, CMP and CMW compression.•Display Controls: Scroll, zoom, pan, magnify glass, brightness/contrast/gamma, window level.•Image Processing: 200+ filters, transforms and color conversion functions with extended grayscale (10 to 16-bit) support.•OCR/ICR/OMR: Full page or zonal multi-threadedrecognition with formatted output including PDF, DOC and TXT for Win32 and x64.•Barcode: Read/write all industry standard 1D and 2D bar-codes (DataMatrix, PDF417, MicroPDF417, QR Code and more).•Forms Recognition and Processing: Automatically identify forms and extract user filled data.•Document Cleanup/Preprocessing: Deskew, despeckle, line and border removal, registration marks and more.•PDF and PDF/A: Read/write raster and text searchable PDF files.•Annotations: Interactive UI for document mark-up, redaction and image measurement (including support for DICOM annotations).•Grayscale Imaging: Display and process signed/unsigned 10-16 bit, 32 bit data.

•Medical Web Viewer Framework: Plug-in enabled framework to quickly build high-quality, full-featured, web-based medical image delivery and viewer applications.•Medical Image Viewer: High level display control with built-in tools for image mark-up, window level, measurement, zoom/pan, cine, and LUT manipulation.•DICOM: Full support for all IOD classes and modalities defined in the 2008 DICOM standard (including Encapsulated PDF/CDA and Raw Data).•DICOM Communications: Full support for DICOMmessaging and secure communication enabling quickimplementation of any DICOM SCU and SCP services.•WPF (XAML): Viewer, Image List, Annotations, Transitions and WIC Codecs.•AJAX Web Form Image controls for developing rich web applications.•JPIP Client and Server components for interactive streaming of large images and associated image data using the minimum possible bandwidth.•Scanning: TWAIN 2.0 and WIA (32 and 64-bit), auto-detect optimum driver settings for high speed scanning.•DVD: Play, create, convert and burn DVD images.•Multimedia: Capture, play, stream and convert MPEG, AVI, WMV, MP4, MP3, OGG, ISO, DVD and more.

Free 60 Day Evaluation! www.leadtools.com/vsm 866-530-3399LEADTOOLS SDKs feature LEAD’s iCompress™ Technologies.

Mark-up DICOM Medical

Form Recognition & Processing

Multimedia

Document Barcode

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

Project1 2/24/09 11:22 AM Page 1

Page 14: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com12

</DevInsight>A

uto

mat

ed T

esti

ng

Developer ExpectationsThe new offering should be welcomed bydevelopers, says Day: “It looks like it’sgoing to make it extremely easy for you todeploy existing code in the cloud.”

But he cautions that until the testrelease is available, it’s too early to sayhow well it will perform compared to on-premises versions of SQL Server. “We’llhave no idea what it will be until we runit,” he notes.

Jennings is skeptical. He pointed outthat TDS was designed to run over high-speed LANs and that it’s not an Internet-friendly protocol. But Matrani insistsMicrosoft has already conducted exten-sive benchmarking and testing and per-formance shouldn’t be a problem. “Wethink it’s appropriate for what we aredoing and the direction we are talking it,”he says. “As we get more early-adoptercustomers and we look at the type ofworkloads they’re building, they’ll keepmodifying and tweaking our protocols soit’s more workload-friendly.”

Matrani adds that SDS will lend itselfwell to CRM applications, content manage-ment, product lifecycle management, sup-ply chain and collaboration. But heacknowledges that it won’t initially besuited to data warehousing and OLTP.

Day and Jennings also warn that rela-tional data has its performance limita-tions. “There are theoretical limits on howscalable you can make a relational data-base,” Day explains.

One of the unanswered questions isthat of cost. While Microsoft still hasn’tdisclosed how it is pricing SDS, rivalAmazon Web Services has already low-ered the bar. The company slashed theprice of its EC2 service by offering thosewho sign one- or three-year commitmentsto usage-based pricing that ranges from 3 cents to 24 cents per hour, dependingon configuration. That represents a 30 percent to 50 percent reduction, thecompany says.

Microsoft says SDS with TDS supportwill be available for testing by mid-yearand commercially available by the end ofthe year. DI

Jeffrey Schwartz ([email protected]) is

Visual Studio Magazine’s news editor and the

editor of ADTmag.com.

BY KEN COX

Automation Design Canvas (ADC)1.1 from ArtOfTest Inc. is a high-endtest tool for developing repeatable,automated tests of Web applications.The generated tests execute onArtOfTest’s included WebAii—pro-nounced “Web-eye”—framework.The designer portion integratesseamlessly with Visual Studio 2008(though not the Express versions) torecord, execute and analyze tests ofbrowser-based content.

Getting StartedADC installed flawlessly on a 64-bitbeta of Windows 7 running in aHyper-V virtual machine. The setupadds a template called WebAii to theVS 2008 Test collection.

The proper configuration ofyour test machine is essential. Forthe tooling to work properly, youmust disable Internet Explorer’sProtection Mode, ease Firefoxbrowser security settings and shutoff User Access Control in Windows.

The online video and the FAQ docu-ment cover these issues adequately.

The Quick Start guide offers afine overview of the tool’s basic fea-tures and environment, but it coulduse some polishing and expertreview of what looked like syntaxerrors in the code examples.

Recording navigation, textinput and mouse clicks are standard fare for any test tool, butADC’s strength becomes apparentboth during and after recordingoperations.

Using Test Explorer you canreorder, edit and disable any step tofine-tune the test sequence. I lovedthe Quick Test button for checkingan individual step without sloggingthrough the whole test sequence.The powerful Convert to Code func-tion turns a step into a highly read-able C# or VB function. This is not ascripting language. You’re codingagainst strongly typed objects withfull IntelliSense and tooltip support.WebAii’s property and method

Automation Design Canvas integrates with Visual Studio 2008 to design andrun flexible tests of Web applications. Each test step remains a separate itemthat you can tweak, re-order or turn into a .NET function. You might need toadd a slight pause for AJAX-enabled controls.

Automation Design Canvas Boasts Advanced Web Testing

R E V I E W

0409vsm_DevInsight_10-13.v7 3/19/09 8:06 AM Page 12

Page 15: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 13

Dat

a M

odel

ing

names are intuitive, resulting in recog-nizable statements such as:

input_Text_Q.Wait.ForExists(1000);

Rather than cluttering Web forms withjunky “asdfdadfdf”-type input, testerscan store realistic values once in the soft-ware’s convenient data table option.When you point an HTML control’s Textproperty to the built-in Data[] object,WebAii loops through its data rows andinserts whatever is in the table. You canalso use external sources, such as a SQLServer database, to feed data-driven tests.

Smooth DesignThe purpose of most tests is to check forappropriate responses. To configurescreen reading in ADC, you use an over-lay function that suspends record modewhile you highlight a screen object suchas a label or image. The overlay’s context

menu lets you set the expected result; forexample, a string of text or a visibleimage. This point, click and configurefeature is very valuable and well-designed.

Recording and playback is usuallysmooth and automatic, but theCascadingDropDown sample on the AJAXControl Toolkit site was an exception. Itrequired adding delays by hand. I suspectedWebAii was trying to select an optionbefore its XMLHttpRequest-fed value wasavailable inside the browser DOM.

ADC logs extensive results and asummary report for each test run. Thetool can even log a screenshot at anypoint in the process to help developersassess the results at the post-mortemreview stage.

ADC 1.1 and WebAii are chock-fullof impressive and useful features for testdevelopers. However, prepare for anenterprise-level price: $2,499 for a

designer workstation license and $199 foran execute-only machine license. DI

Ken Cox is a Canadian .NET programming

writer and the author of “ASP.NET 3.5 for

Dummies” (For Dummies, 2008).

ERWin Data Modeler 7.3 and LiveLinqErwin Data Modeler 7.3With more complex data sources throughout the enterprise anddemands to move beyond structured information, modeling toolsare moving beyond their roots. For one thing, database developerscan now find them in application lifecycle management suites.

Case in point is Erwin from CA Inc., one of the most widely usedof the data-modeling tools. The new CA ERwin Data Modeler 7.3 cannow be integrated with Visual Studio Team System 2008 and SQLServer 2008, among a number of other key data repositories includ-ing Teradata and IBM Corp.’s DB2 for its mainframe-based z/OS v9.

The tight integration between ERwin and SQL Server allowsfor all SQL Server database objects to be captured in ERwin datamodels for analysis, says CA partner Antonio Amorin, president ofNorthbrook, Ill.-based Data Innovations.

The new release of ERwin also boasts new reporting capabili-ties via a bundled copy of BusinessObjects Crystal Reports, whichprovides graphical rendering in spreadsheets, PDFs and HTML.

“Our techie geeks love that because they can completely cus-tomize any report they want, when a model is published,” saysDonna Burbank, a senior principal product marketing manager at CA.

The new release also has a new option for data profiling,thanks to a recent partnership with Exeros Inc., whose data profileris now integrated into ERwin. The data profiling lets developerscompare data distributed throughout disparate legacy systems,which CA says will ease the process of identifying informationsuch as customer data, and making sure it’s consistent with struc-tural designs. This allows architects and those on implementationteams to ensure data is modeled so it can be used in data marts,warehouses and master-data management hubs.

ERwin, which recently celebrated its 20th anniversary, isamong the leading suppliers of data modeling tools, says

Forrester Research Inc. analyst Jeffrey Hammond. “ERwin is probably the most traditional of the data modeling tools,” henotes. Other key providers include Embarcadero Technologies Inc. and Sybase Inc., according to Forrester. IBM, Microsoft and Quest Software Inc. also are emerging providers of data management tools.

ERWIN DATA MODELER 7.3

CA Inc.Price: $8,000www.ca.com800-225-5224

LiveLinq Boosts QueriesOne of the key benefits of Microsoft LINQ is that it can cut downdevelopment time for data-driven applications. But for those looking to optimize the speed of applications developed in LINQ andfor dynamic views of data rendered in LINQ-based queries,ComponentOne LLC is readying a new tool called LiveLinq. Availableas a community technology preview in February and slated forrelease next month, LiveLinq is a new class library that the companysays speeds up LINQ queries by indexing in memory. ComponentOneclaims “typical” performance boosts of 10 to 50 times.

The live views will render data dynamically to users of appsusing LiveLinq libraries. Any developer familiar with LINQ shouldbe able to use LiveLinq without training, says ComponentOneProduct Manager Chris Meredith. DI

LIVELINQ

ComponentOne LLCPrice: Not disclosed yetwww.componentone.com800-858-2739 412-681-4343

AUTOMATION DESIGN CANVAS 1.1

ArtOfTest Inc.www.artoftest.com512-535-2428

Price: $2,499 per developer machine;$199 per execute-only machine license

Quick Facts: A sophisticated VisualStudio 2008 plug-in for recording, coding and executing tests of a Webapplication using Internet Explorer orFirefox.

Pros: Easy to learn and use; powerful recording and playback features; flexible editing of test steps;exposes rich, strongly typed C# or VBobjects

Cons: Pricey; AJAX controls may requirespecial attention

P R O D U C T S

0409vsm_DevInsight_10-13.v7 3/19/09 8:06 AM Page 13

Page 16: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Project3 3/19/09 9:08 AM Page 1

Page 17: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Project3 3/19/09 9:09 AM Page 2

Page 18: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com16

VISUAL STUDIO 2010 FEATURE

The team in Building 41 on the Redmond campus isworking on ways to modernize the developer experi-ence for Microsoft’s third-largest application and flag-ship toolset. The Visual Studio platform architects facethe same challenges as their developer customers: Howto revitalize a pivotal legacy codebase as hardware sys-tems, Software plus Services (S+S) and new ways ofbuilding applications demand advancement.

Visual Studio (VS) 2010—expected in betaaround the Microsoft Tech·Ed timeframe (May 11-15,2009)—will mark the start of a major remodeling ofthe IDE, according to Microsoft, a process that willcontinue over several product cycles.

In the upcoming release, the Developer Divisionis taking a major leap of faith by “dogfooding” itsunproven graphics technology. The VS 2010 betadebuts a new code editor, user interface and shell builton Windows Presentation Foundation (WPF), the.NET 3.x graphics subsystem that surfaced to mixedreviews in Vista.

“We’ve told developers how to make applicationsthat are intuitive and exciting and modern looking fortheir customers,” says Matt Carter, Microsoft’s VisualStudio group product manager.“What we’re trying todo is say, ‘You deserve an environment that’s also veryeasy to use and intuitive and visually appealing, butalso uses that visual appeal to really provide greaterinsight into what you’re working on, how the differentparts of your code and your applications are related.’”

A programming model to take advantage ofVista’s new graphics subsystem, WPF was designed tomodernize the user experience by enabling developersto code against a powerful framework that housed asubset of DirectX 3D, animation, vector graphics,ClearType, declarative programming, data binding,multimedia, styling and controls. The initial releases of

WPF, according to many developers, provided limitedguidance and a lack of sufficient tooling.

“It’s good to see Microsoft using WPF in one oftheir core products, as it will surely drive the maturity ofWPF and related tools,” says Rockford Lhotka, principaltechnology evangelist at Minneapolis-based consultancyMagenic Technologies Inc.“Every time Microsoft buysinto its own technologies like this, we all benefit.”

Dated and ConfusedThese bold moves come as VS’s architects attempt toroadmap a remodel of the IDE with investments in fiveareas: extensibility beyond the core throughout theproduct, frugality with better dependency manage-ment and resource allocations, connectivity with S+S,scalability to the tune of 10,000 projects in a solution;50,000 files in a system and overall modernization.

“The 2008 product looks a lot like the 1998product and I don’t think that’s a good thing,” saidVisual Studio architect Rico Mariani in a Channel 9interview at the Visual Studio Extensibility (VSX)conference in September.

“We’re doing a lot of work around scalability andfrugality in the IDE, so that you can afford to be mod-ern,” he said.“We can pay for our WPF costs with sav-ings elsewhere. We don’t expect WPF to be free.”

Moving beyond “single-threaded app” perform-ance in Visual Studio and a Model-View-Controller-type

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ILLU

ST

RA

TIO

N B

Y R

YAN

ET

TE

R

EVOLUTIDE

0409vsm_F1VS_16-23.v7 3/19/09 12:55 PM Page 16

Page 19: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 17

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.

ION

0409vsm_F1VS_16-23.v7 3/19/09 12:55 PM Page 17

Page 20: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Project1 1/21/09 11:14 AM Page 1

Page 21: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Project1 1/21/09 11:15 AM Page 2

Page 22: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com20

VISUAL STUDIO 2010FEATURE

architecture are among the roadmap’s talking points.“We haveplenty of threads but we don’t have a whole lot of concurrency,”said Mariani.“And there’s a lot we could do if we separate whatneeds to be synchronous, what needs to interface with the user,which is where the SDK models begin. Get the state off of thoseobjects and separated and get separation between the con-trollers, which can initiate asynchronously and have high-qualitymodels in the background.”

In VS 2010, developers can experience firsthand the begin-ning of the IDE’s evolution: improved code navigation, annota-tion and extensibility with the WPF-based shell; better perform-ance and scalability for native code; and fundamental improve-ments in debugging and test-driven development.

Snazzy New UI BlingLike many teams tasked with modernizing their apps, Microsoftis revitalizing its legacy code base with a .NET presentation layer.The UI changes appeared modest to several developers who wit-nessed the first pubic unveiling at VSLive! in February. The UIRibbon found in Vista and Office 2007 is not part of the redesign.

In the new VS 2010 interface, the menus and commands areconnected together in a shelf, so it’s easy to coordinate and findthings or get the clutter out of the way, explains Carter. Microsofthas done design work around how color and negative space is used,and removed some of the necessary gradients and line work thereso that the app is “cleaner and crisper than it has been in the past,”he explains. “It lets you focus on the work that you’re doing andminimize the distractions from other parts of the environment.”

Lhotka, who attended the VSLive! keynote delivered byMicrosoft’s Visual Studio GM Jason Zander where the UI wasfirst shown, questions the “less clutter” argument.“While it’s nicethat Visual Studio is now WPF, it didn’t seem to me that the lay-out and dialogs were all that different from today,” Lhotka says.

In addition to a new look and feel, WPF allows you to extendthe application experience beyond what Microsoft delivers in theIDE through third-party or self-written add-ins.

WPF allows new extensibility to the source code editor thatin the past has been difficult to achieve, says Rob Sanfilippo,research vice president of developer platforms at Directions on

Microsoft, a Kirkland, Wash.-based research firm.You can look at methods in your code and get apop-up with history of the modifications as it’sgone through development. You can also lever-age debugging information in Team FoundationServer, create specialized IntelliSense or adornXML Documentation Comments.

“Microsoft will offer a lot of these exten-sions,” Sanfilippo explains.“But it also opens up amarket for that ecosystem. It’s an interestingcompetitive move: If there are features in com-peting dev environments, to put [Visual Studio]on par with what’s found on other toolsets.”

At Tech·Ed in Barcelona, Zander showed aDevExpress add-on that lets you create thumb-nail code views, so it’s easy using WPF layers topick a word and drill down in the DocumentMap Margin.

The new WPF-based Home Screen is alsoextensible through configuration and XAMLfiles. “I could see extensions to this screen that

can display things like quick-facts,” says Sondre Bjellås, Microsofttechnology leader for Capgemini in Oslo, Norway. “How muchcode you’ve checked in lately, how much time you spend testing,how much time you spend documenting your methods and soforth. It could aggregate data from the Team System warehouseand display it personalized for the individual developer.”

The WPF redesign of the IDE is the part of VS 2010 thatimpresses Andrew Brust, chief of new technology at twentysixNew York, the least.“What I saw looks more like a WPF port of the2008 IDE than a true redesign. I hope that Microsoft will considermaking more fundamental UI design changes to VS 2010 beforerelease,” Brust says.

“We’re not embracing WPF because we want graphical‘wow’—that wouldn’t be enough of a reason,”blogged VS architectMariani in late November.“What we want is flexibility and exten-sibility. For instance, it’s because the new editor is WPF-based thatwe can, for reasonable engineering cost, offer the ability to addinline adornments, margins, even ‘heads up display’ style exten-sions. ... The best part is you won’t have to wait for us to do thesethings—you want profiler information overlaid on your text? Noproblem. Go do it. Test coverage? Hot links to documentation?Online presence indicators based on e-mail names in comments?You could do all these things.”

The WPF-based editor is built on Microsoft’s newManaged Extensibility Framework, a .NET 4.0 library forbuilding extensible applications or discovering extensions.MEF is available as a preview on CodePlex (see more aboutMEF in this month’s Ask Kathleen, p. 42).

“This whole modernizing thing, I think it’s a little tongue-in-cheek,” although it’s a good direction for Microsoft, says JeffLevinson, ALM practice lead at Kirkland, Wash.-basedNorthwest Cadence Corp. “Companies have been writing add-ins in Visual Studio for 16 years now. They can’t just go anddump what’s there. I think what they’re going to do is skin it forWPF, but I don’t know how full-featured WPF is going to be interms of interoperability,” he says.

The current VSX architecture remains intact, according toVS architect Mariani, but extensibility needs to be more uni-form. Other questions remain: How can developers find and

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

The WPF shell lets developers undock window palettes and view code on multiple monitors.

0409vsm_F1VS_16-23.v7 3/19/09 12:55 PM Page 20

Page 23: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 21

plug into the appropriate subsystem? How do you de-bug andupdate these components? How many extensions are feasible?

A new Extension Manager in VS 2010 lets developers access,search and download extensions from the VSX gallery, for exam-ple, from within Visual Studio without a required VSIP packageon their machines.

Perhaps the biggest question around WPF is how it will affectthe IDE’s performance. Mariani, known as a “performance guy,”hasacknowledged that there will be a penalty.“I’m expecting to take astartup hit,” he said during a Channel9interview, noting that around 300-msecwould be acceptable.

The new IDE will be targeted at devel-oper machines.“We’re going to down-levelto XP in this version,” he explained, but toget the best experience, developers need tohave a graphics accelerator (DirectX 9.0).

From a practical standpoint, WPFalso lets developers zoom in and out ofcode, undock palettes and view codeand designer windows on multiplemonitors. “It’s easier to work in differ-ent [but integrated] projects on differ-ent screens independently from yourscreen resolution,” says Daron Yöndem,a Microsoft regional director andINETA Turkey lead, who described theWPF support as “crazy good” in an e-mail. “I’m looking forward to thegreat days where we will be able todesign our own Visual Studio interfacewith full templating.”

Crowded with GoodnessDesigning custom toolsets appeals tomany developers, especially those whoare accustomed to downloading only themodules they need, which is the Eclipsemodel. The promise of .NET, accordingto Microsoft, is that you can target somany applications—Windows, Office,Web, smartphone, cloud—with a singleframework. And there’s the rub: How cana single IDE keep up?

“It has been bloated for a numberof years,” says Northwest Cadence’sLevinson. “For example, if you look atTeam Explorer, which is just a VisualStudio Shell, that’s 387MB to downloadand install … and if you look at some-thing like Eclipse, that thing is around180MB. Then when you add everythingelse on, [Visual Studio] is almost 1GB.”

Microsoft has heard the refrain foryears—Visual Studio needs to be a small-er footprint and take up less resources.“Ittakes a long time for certain operations tooccur, where it shouldn’t take that long,”says Levinson. “I would like to see themshrink it so that you only install the pack-

ages that you need and the shell is much smaller.” He acknowl-edged that the ecosystem makes it hard to address a lot of theseissues in a single product cycle.

The platform wave continues in the new IDE, which willsupport .NET 4.0, Windows 7, SharePoint 2007 and MicrosoftOffice SharePoint Server, the Azure Services Platform andSilverlight 2.

“If you’re a Visual Studio developer, you already have the coreknowledge to take advantage of all these great new innovations,”

Powerful Imaging for .NET

www.atalasoft.com

DotImage 7 – Affordable imaging toolkits for .NET.

Runtime royalty-free deployment to the desktop, scalable

licensing for servers, and 3 months of free gold support.

Visit Atalasoft.com for web demos, video tutorials, and a free trial.

Call us toll free at 866-568-0129

VISUAL STUDIO 2010 FEATURE. . . . . . . . . . . . . . . . . . . . . . . . . . .

0409vsm_F1VS_16-23.v7 3/19/09 12:55 PM Page 21

Page 24: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com22

VISUAL STUDIO 2010FEATURE

says Microsoft’s Carter, pointing to recent developer feedback onthe new SharePoint tooling.

Indeed, the new Server Explorer,VS 2010 Web Parts,ApplicationPage Designers and user controls for SharePoint are highly anticipat-ed by many developers who have bemoaned the lack of tooling.

This release is primarily focused on Windows 7. (VS 2008did not fully support Vista/.NET 3.x until Service Pack 1 wasreleased last summer.) VS 2010 and Visual C++ will offer newclass libraries for building Windows 7 apps (including UI ele-ments like the Ribbon), bring back the MFC Class Wizard andsupport multitouch interfaces.

For Web developers, VS 2010 adds much-needed designersand ASP.NET integration for Silverlight 2, tooling for ASP.NETMVC, advanced JavaScript IntelliSense, snippets in HTML andOne-Click Deployment.

In addition to support for its bread-and-butter platforms,Microsoft is baking in tooling to support emerging applicationtrends, namely cloud computing and parallel programming forbuilding applications that can take advantage of the performance ofmulti-core systems.Visual Studio offers additional support for par-allel programming with debugging windows and profiling for coding against the Parallel Extensions to .NET Framework, PLINQ,the native Parallel Pattern Library and Concurrency Runtime.

The Windows Azure Tools for Visual Studio, released out ofband at the Professional Developers Conference (PDC) 2008 inOctober for building, debugging and deploying cloud apps andservices, is also integrated into the new IDE.

Third-party products and frameworks are also finding theirway into the IDE. Two notable inclusions in the VS 2010 toolingare Oracle database support with an optional database schemaprovider developed by Quest Software Inc., and native JQuery.“We had two paths we could follow there,” explains Carter. “Wecould create a JQuery functional equivalent or we could just useJQuery ourselves … and have it supported by Microsoft. It willhave all the IntelliSense that you’d expect from Visual Studio. Ifyou have a problem and call Microsoft, we’re here to support it.”

Team CollaborationWhile developers and analysts describe VS 2010 outside of thecore platform support as somewhere between a point release andfull-fledged upgrade, Team System 2010 is a milestone releasethat ratchets up the testing capabilities on par with third-partytesting products, and reinvents the architecture role to ensurebest practices in the build process.

“The 2010 release is kind of like an über release,” saysLevinson.“The functionality is much better. The introduction ofhierarchical work items will make your life a lot easier. Plus, nowMicrosoft is putting out a fully compatible, competitive profession-al testing tool, which they haven’t really had before. If I had to cate-gorize VSTS 2010 in a single word, I would say,‘Awesome!’”

The new Architecture Edition is more of an app tool than asystems tool, according to Levinson. It makes elements composableand discoverable so that you can now reverse engineer withsequence diagrams or use the Architecture Explorer to drill down tosee relationships. IDE support for UML is also added in 2010. VSProfessional has traditionally shipped with Visio, which offers UMLstencils, but this is the first time Microsoft is supporting it in its ownproducts. How “Oslo,” the model-driven development tooling

announced at PDC, fits into this strategy is unclear. The latest Oslocommunity technology preview was released in January.

Improvements like the “no repro” debugging and the newTest Lab Manager, a virtual machine environment that develop-ers and testers can spin up and tear down, goes beyond quality,asserts Carter, to a team dynamic that can be fostered with thenew software.

“My read is it will enable teams on tight deadlines and budgetsto put out much higher quality code, because the effort required tofind and fix the bugs will now be greatly reduced,” says Brust.“Automation and all the recording features will really help here.”

VSTS 2010, which includes role-based client tools that incor-porate VS Professional and a license to TFS, is the first majorupgrade to the collaboration environment since its debut in VS 2005. TFS will drop support for SQL Server 2005 as the back-end source control system and thus require an upgrade to SQL Server 2008. Team System also rolls up the former Developeredition into the Database edition, resulting in Architect, Tester andDatabase roles in addition to Team Suite, which includes all of theaforementioned functionality in a single SKU.

“We’re looking at quality across the board,” says Carter.“When customers are ready to move up from doing unit testingin Visual Studio 2010 Professional, to advanced stuff in VisualStudio Team System, that’s an easy transition. That’s really excitingstuff … things like historical debugging, not only drive quality, theyhelp save time and resources for your team.”

Call to ActionWith installable beta 1 bits expected next month, developers cantest drive the new editor and try out the code navigation. A new Call Hierarchy feature provides inline information on code

New in .NETFramework 4.0Visual Studio 2010 will ship with a .NET Frameworkthat has undergone major changes, most notably a complete overhaul of Windows Workflow. Other note-worthy additions include:

■ Managed Extensibility Framework (MEF): A new .NET 4.0 library for building extensible applications ordiscovering extensions. MEF is available as a previewon CodePlex.

■ Integration of .NET Parallel Extensions: A new libraryfor data and task parallelism that includes the TaskParallelism Library and declarative programming support via Parallel LINQ (PLINQ).

■ Support for the functional programming languagedeveloped by Microsoft Research, F# and Microsoft’sdynamic languages IronRuby and IronPython via thenew dynamic language runtime built on top of the common language runtime. —K.R.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

0409vsm_F1VS_16-23.v7 3/19/09 1:06 PM Page 22

Page 25: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 23

VISUAL STUDIO 2010 FEATURE

interaction. Highlight References bypasses the Find in Files featureto highlight reference information in context of selected code andQuick Search provides insight into other code locations.

Like VS 2008, the new IDE will support multitargeting of.NET Framework, and new with VS 2010, developers will also beable to “multitarget” both versions of the Common LanguageRuntime (CLR2 and CLR4). Developers can also build clientapps for multiple versions of Office, anddeploy as a single package.

Those with existing solutions basedon C++ project systems will need to con-vert to MSBuild in VS 2010 to receive fullIDE support. Although Microsoft hassaid it will provide migration tools, moreinformation is needed.

VS 2010/.NET 4.0 beta 2 is expectedbefore the end of the year with a Go Livelicense, according to sources familiarwith Microsoft’s plans. The tiered VSpricing structure, which debuted with VS2005, isn’t changing, but professionaldevelopers may be better able to discernwhat functionality is available in whatSKU/MSDN subscription based on theirexperience with this pricing model.

Microsoft started a step-upgradediscount program last July that offers 30percent off to developers who upgrade ormove from competing products to VSProfessional/MSDN Premium subscrip-tions or VSTS, both of which include theVS 2010 upgrade. Microsoft has declinedto quantify how many step-upgradeshave been sold.

VS 2010 is the first release in what theVisual Studio platform architects describeas a multicycle evolution. The team islooking at a 64-bit version of the IDE for VS 11, but hasn’t committed to a tech-nology roadmap.

“The reason that you do this is tomake sure that the developer experience isas efficient as possible,” says Microsoft’sCarter. “So that’s really what we pivotaround—to make sure that with VisualStudio 2008 and 2010 and beyond wedeliver a great productive experience thatis at once familiar to developers, but alsolets them tap into these new capabilities.”

The ultimate goal, according toMariani, is: “How do you make it so thatwhen a developer sits down, they feel likethere’s nothing in his or her way betweentheir idea and the execution?” VSM

Kathleen Richards ([email protected])

is executive editor of Visual Studio Magazine,

and editor of RedDevNews.com.

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to godirectly to these related resources.

READ MORE

VS0904KR Read this article online.

. . . . . . . . . . . . . . . . . . . . . . . . . . .

0409vsm_F1VS_16-23.v7 3/19/09 1:06 PM Page 23

Page 26: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Las Vegas • June 8-11The Venetian Resort Hotel Casino

Post event workshop on June 11

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

**

VSLive! Returns to Las VegasAttend the educational conference created by developers with deep coverage of existing and new technologies that you can use on the job today. Join your fellow developers for:

Over 45 sessions on WFP, WCF, LINQ, ASP.NET, Oslo, Azure, Team Foundation Server and more

Cutting edge techniques needed to solve today’s development challenges

Independent, real world information provided by industry experts

Face to face time with speakers to ask your toughest questions

Visit www.vslive.com/09lv to view the complete agenda and register.

Save up to $300 with early bird registration AND get a $50 Venetian gaming credit*. Register by April 29th. Use priority code NQ9V02

Take advantage of our $99 hotel room

rate

09VSL_LV_VSM_adFinal.indd Sec1:209VSL_LV_VSM_adFinal.indd Sec1:2 3/13/09 7:17:38 PM3/13/09 7:17:38 PM

Page 27: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Conference Day 1 • Monday, June 8KEYNOTE: Team Foundation Server 2010

ASP.NET WPF WCF

VM1 • Build Blazingly Fast ASP.NET Apps with 100% Clientside UI ExtJS - Peter Kellner

VM2 • Build a WPF Application in an Hour - Kenneth Getz

VM3 • Understanding Transactions in WCF - Michiel van Otegem

VM4 • Introduction to the ASP.Net MVC Framework - Gus Emery

VM5 • Silverlight Design for Developers - Bill Wolff VM6 • WCF Extensibility In-Depth - Jesus Rodriguez

Lunch

VM7 • ‘Real World’ ASP.Net MVC in 75 Minutes! - Gus Emery

VM8 • XAML Crash Course - Billy Hollis VM9 • Advanced Access Control with WCF - Michiel van Otegem

VM10 • Building High performance ASP.NET web applications - Peter Kellner

VM11 • Silverlight Data Access Methods - Bill Wolff VM12 • WCF-WF Integration In-Depth with an Eye Towards Dublin - Jesus Rodriguez

VM13 • Implementing Caching Technology as One Rung of the Scalability Ladder - Josef Finsel

VM14 • Deep Dive on the WPF/Silverlight Control Set - Billy Hollis

VM15 • Windows Workfl ow and WCF Help Make “Software + Services” a Reality - Michael Stiefel

Welcome Reception

Conference Day 2 • Tuesday, June 9KEYNOTE: Silverlight 3

.NET LINQ Agile/Design

VT1 • Essential C# 4.0 - Mark Michaelis VT2 • Moving from LINQ to SQL to the Entity Framework - Jim Wooley

VT3 • How to Partition and Layer a Software Application - Michael Stiefel

VT4 • Writing Better Code: Using Visual Studio to Improve Your Code Base - Jason Bock

VT5 • Investigating LINQ to XML - Kenneth Getz VT6 • Design Patterns for Mere Mortals - Philip Japikse

Birds-of-a-Feather Lunch

VT7 • Practical Parallelism - Rockford Lhotka VT8 • Leveling the LINQ to XML Playing Field with LINQ to XSD - Leonard Lobel

VT9 • Beyond Basic Unit Testing: Mocks, Stubs, User Interfaces, and Refactoring for Testability - Benjamin Day

VT10 • Exceptional Development: Dealing with Exceptions in .NET - Jason Bock

VT11 • Super-Optimized Microsoft LINQ: Indexed Objects - Aaron Erickson

VT12 • Achieving Balance - Rockford Lhotka

VT13 • Self-Writing Programs - Using the Expressions namespace in C# to “Write Code that Writes Code” - Aaron Erickson

VT14 • LINQ Kinq for the DBA Guy - Jim Wooley VT15 • Advanced Test Driven Development - Philip Japikse

Conference Day 3 • Wednesday, June 10VW1 • Introduction to OSLO - Jon Flanders VW2 • Windows Azure: A New Era of Cloud

Computing - Aaron SkonnardVW3 • Get More Out of Team Build 2008 - Brian Randell

VW4 • Codename “Dublin”: Windows Application Server - Aaron Skonnard

VW5 • Windows Azure: Is the Relational Database Dead? - Benjamin Day

VW6 • Dispelling the Myths: Visual Studio Professional vs. Visual Studio Team System

VSLive! Panel Discussion

Lunch

VW7 • Building Textual DSLs with Oslo - Mark Michaelis

VW8 • How to Work with Data in the Cloud: SQL Data Services Introduction - Josef Finsel

VW9 • Customizing Team System Projects - Brian Randell

VW10 • M in Depth: The Underpinnings of Oslo - Jon Flanders

VW11 • Windows Azure, an Enterprise Solution? - Jerry Sevier

VW12 • Better Together: Getting the Most Out of Visual Studio Team System 2008 Development and Database Editions

Post-Conference Workshops • Thursday, June 11VPC1 • A Day of Windows Azure - Aaron Skonnard VPC2 • SQL Server 2008 for Developers

- Leonard LobelVPC3 • Build Distributed Apps in .NET 3.5 SP1 - Rockford Lhotka

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

09VSL_LV_VSM_adFinal.indd Sec1:3 3/13/09 7:17:47 PM

Project3 3/20/09 12:07 PM Page 1

Page 28: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com26

SHAREPOINT EXTENSIONS HOW-TO

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

0409vsm_How-To_26-32.v5 3/19/09 10:14 AM Page 26

Page 29: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 27

PH

OT

O F

RO

M IS

TO

CK

.CO

M

Microsoft released the Visual Studio 2008 Extensions forWindows SharePoint Services 1.3 (VSeWSS) as a communitytechnology preview (CTP) in January 2009. The extensions sim-plify creating and debugging many kinds of SharePoint compo-nents. The CTP version is feature-complete, though presumablythere are still some bugs left to remove (the final version is sched-uled for release in the spring). On the Visual Studio side, the CTPsupports VS 2008 but not VS 2005. On the SharePoint side, theCTP supports both Windows SharePoint Services and OfficeSharePoint Server. The Extensions package supports installingyour Web Part, debugging it on the same computer as VS—remote debugging is not supported.

We’ll walk you through the process of installing theExtensions and using them to create and debug a Web PartProject. Along the way, you’ll see how to create a configurablesearch tool for a SharePoint site.

Installing the ExtensionsThe Extensions download package can be retrieved fromhttp://tinyurl.com/bjqwmk by following the link in the body ofthe page (don’t click on the Downloads link—it takes you to apatch you probably won’t need). You can download up to threecomponents: two .MSI files (one each for 32-bit and 64-bitWindows) and the release document. You must have IIS,SharePoint and VS 2008 installed on your computer to run theinstallation package.

The installation package installs a Web service (calledVSeWSS) on your computer that VS will use to communicatewith SharePoint. One of the first challenges that you’ll face afterstarting the installation wizard is to configure the Web service(Figure 1, p. 28). Your first step is to pick an application pool touse for the Web service. If you don’t want to use an existing pool,you’ll need to create the new pool in IIS Manager before startingthe installation. There are two conditions that the identityassigned to the pool must meet:

■ It must have the same permissions as those granted to theidentity used by the SharePoint Central Administration site

■ The identity must be part of the Administrators group I picked the simplest solution to meet the first condition: I

used the SharePoint Central Administration site’s pool as thepool for the Web service. This also saved me from having to setup a new pool.

To meet the second condition, you must determine theIdentity used by the pool you’ve picked. You do this in IISManager, under Application Pools, by finding the pool you picked

in the dialog. Once you’ve found the pool, right-click on it andselect Properties. You’ll find the identity name on the Identity tab(on my machine, the identity was Network Service). The next stepis to add the Identity to the Administrators group: From yourcomputer’s Start menu, select Administrative Tools | ComputerManagement and drill down through Local Users and Groups |Group to select Administrators. Right-click on the group, selectAdd to Group and enter the name from the Identity tab.

After you make these changes, you can leave the Wizard torun unattended. After the installation is complete, you can useVS to determine if your installation was correct.

Creating Your Web Part ProjectWith the Extensions installed, you’re ready to start using their firstfeature: A set of SharePoint templates that support creating mostSharePoint components. To create a Web Part, for instance, youselect Web Part project template in the SharePoint category of theNew Project dialog (see Figure 2, p. 28). The resulting project has afolder called Web Part1—delete it (renaming Web Parts is not100% reliable, at least in the CTP) and use the standard Add NewItem dialog to add your Web Part with the correct name. For thisarticle, I added a Web Part called VideoSearchPart.

The result is a new folder with the three files required for aSharePoint Web Part: The code file for the Web Part, an XML filecontaining the information needed to install the Web Part and a.WEBPART file with the XML used to configure the Web Part.While it doesn’t appear in Solution Explorer, the Web Part tem-plate also includes a feature.xml and a setup.bat file, which you’lluse when installing your Web Part on your productionSharePoint site.

Because you can only debug your WebPart on your devel-opment computer, you’ll need to either copy your target site toyour local computer or create a test site on your computer. Inthis particular case, I created a test SharePoint site by startingSharePoint Central Administration from my Start menu and,from the Application Management tab, picking Create orExtend Web Site to bring up the dialog that lets me add a newsite. After clicking the OK button to create my site, I used thenext page in the process to add a Site Collection usingSharePoint’s Wiki template.

If your development SharePoint site isn’t installed on port80 at http://Localhost then you’ll have one more configurationstep to make: You must set the start URL for debugging to pointto the URL for your site. To do this, open your project properties,navigate to the Debug tab and set the “Start browser with URL”

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

SHAREPOINT EXTENSIONS HOW-TO

0409vsm_How-To_26-32.v5 3/19/09 10:14 AM Page 27

Page 30: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com28

SHAREPOINT EXTENSIONS HOW-TO

text box to the URL for the local SharePoint sitewhere you want to test your Web Part .

With your project created and configured,you can now check to see if your installation wentcorrectly: Right-click on the project and selectQuick Deploy | Recycle Application Pool. If therewere any errors in your installation, you will get amessage in your Error List. If you changed the“Start browser with URL” option and you get amessage that refers to the original LocalHost URL,select Recycle the Application Pool option again(the Extensions seem to use the original settingonce, before using your updated setting).

Configuring the Project and the SiteYou’re not quite ready to start creating your WebPart. While the Extensions make debugging easy,they don’t configure your SharePoint site to supportdebugging or report error information. To makethese changes, return to IIS Manager, drill downthrough Web sites to your SharePoint site, right-click and select Properties. On the Home Directorytab, you’ll find the path to the folder holding yoursite’s files in the “Local path” text box. In WindowsExplorer, navigate to that folder and open theweb.config file in the folder. In this file, change thedebug attribute on the compilation element to“true” in order to turn on debugging:

<compilation batch="false" debug="true">

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

<customErrors mode="Off" />

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

<SafeMode CallStack="true" />

Before adding code to the .VB or .CS file that repre-sents your Web Part, you should update the .XMLand .WEBPART files in the project (it doesn’t appearto be possible to change these values after debuggingyour Web Part for the first time, at least in the CTP). Inside theproperties element in the .WEBPART file, rewrite the default prop-erty elements in the file with the title and description you want tohave displayed in SharePoint’s Add a Web Part dialog. This exampleshows the settings for my sample search part:

<properties><property name="Title” type="string">Video Title

Search</property><property name="Description" type="string">Fuzzy

search on video titles</property></properties>

By default, your Web Part will appear in the Add Web Parts dialogin the Miscellaneous section. To have your Web Part appear in adifferent category, open your Web Part’s XML file and add twoProperty tags inside the File element: One with its Name attrib-ute set to Group and the other with its Name attribute set toQuickAddGroups. With the two properties defined, set the Valueattribute on both tags to whatever value you want for your groupname. This example will cause the part to appear in a sectioncalled “PHV Tools”:

<File Path="VideoSearchPart.webpart"Url="VideoSearchPart.webpart"

FIGURE 1. Configuring the Web service: You can’t move off of this page inthe Extensions setup wizard until you’ve successfully configured the applica-tion pool used by the Extensions’ Web service.

FIGURE 2. SharePoint Project Template: The SharePoint Extensions add aSharePoint category to the Add New Item dialog containing a set of tem-plates for SharePoint components.

0409vsm_How-To_26-32.v5 3/19/09 10:15 AM Page 28

Page 31: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Project7 3/5/09 12:14 PM Page 1

Page 32: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com30

SHAREPOINT EXTENSIONS HOW-TO

Type="GhostableInLibrary" ><Property Name="Group” Value="PHV Tools"/><Property Name=vvQuickAddGroups” Value=”PHV Tools"

/></File>

Programming the Web PartYou’re finally ready to start creating your Web Part. Within theWeb Part’s code file you must—in the CreateChildControlsmethod—create the controls that will appear on your Web Part.The simplest approach is to create a table, add it to the Web Partobject’s Controls collection, add rows and cells to the table, thenadd your controls to the Controls collection of the cells in thetable. This code adds a Label control to the first cell in the firstrow of the table:

Dim tbl As New TableMe.Controls.Add(tbl)

Dim trTitle As New TableRowtbl.Rows.Add(trTitle)

Dim tcTitle As New TableCelltrTitle.Cells.Add(tcTitle)

Dim TitleLabel As New Label()TitleLabel.Text = "Look for movies with title:"tcText.Controls.Add(SearchTitle)

For my example, I created a table with four rows: the first rowcontains a Label and TextBox for the user to enter the title of amovie to search for, the second row contains a Label and aTextBox for the user to enter a category (such as Action orDrama), the third row contains the button to trigger the search,and the final row holds a GridView to display the result. In theCreateControls method, you should also wire up any events

that your Part needs. This code adds a button to the table andwires an event routine to it:

Dim trButton As New TableRowtbl.Rows.Add(trButton)

Dim tcButton As New TableCelltrButton.Cells.Add(tcButton)

Dim SearchButton As New Button()SearchButton.Text = "Search"AddHandler SearchButton.Click, AddressOf Me.StartSearchtcButton.Controls.Add(SearchButton)

The event routine pulls data from the two TextBoxes in the table(in the first and second rows) and fills a DataSet that is bound toa GridView (in the fourth row):

Private Sub StartSearch(ByVal sender As Object, _ByVal e As System.EventArgs)

Dim conn As New SqlConnection("…")Dim cm As SqlCommand = conn.CreateCommandDim da As New SqlDataAdapter(cm)Dim ds As New System.Data.DataSetDim searchString As String

Dim tbl As Tabletbl = CType(Me.Controls(0), Table)

searchString = CType( _tbl.Rows(0).Cells(0).Controls(1), TextBox).Text

cm.CommandText = "Select * From …"da.Fill(ds, "Results")

Dim gv As GridViewgv = CType(tbl.Rows(2).Cells(0).Controls(1), GridView)

SharePoint vs. SQLIs MOSS putting the squeeze ondatabase development?BY JEFFREY SCHWARTZ

It has been well-chronicled how pervasiveMicrosoft Office SharePoint Server(MOSS) is becoming in the enterprise.

But for some database developersand administrators—and in certain caseseven higher-ups in the IT food chain—SharePoint’s rampant growth is a concern,particularly in organizations where datathat belongs in SQL Server is finding itsway into MOSS. “You don’t have to be adeveloper to go in there,” says Ed Smith, a systems analyst at Tetra PakInternational, a global supplier of

packaging machines. “You can get twosecretaries together, they can figure outwhat they want to do and they can startputting stuff in there.”

This is a common occurrence thatcan quickly become problematic, particu-larly in cases where data that requiresreferential integrity is put into aSharePoint list, says independent con-sultant and Microsoft MVP Don Demsak,who’s observed this trend and a growingdemand for SharePoint developers.“SharePoint is very successful becauseyou’re removing levels of impedance, anda lot of DBAs hate SharePoint for thosesame reasons,” explains Demsak.“Basically you’re storing everything in aBLOB, and you can’t relate to object-rela-tional mapping, and you can’t do goodentity relationships. You can’t do relation-al models because there’s all sorts of

problems when people try to extend thatSharePoint model past where it’s sup-posed to go.”

Strengths and WeaknessesSharePoint is popular for storing andsharing documents and other unstruc-tured content, but when an individual hasdata based on rows and columns and istrying to join one list to another, “that’snot what those tools were made for,”Demsak says. “When you need a relation-al database, you use a relational data-base—the way it was supposed to be.”

Paul Andrew, Microsoft technicalproduct manager for the SharePointdeveloper platform says many are alreadybuilding custom applications onSharePoint that use a mix of SQL Serverschema and tables within MOSS. “Ofcourse, each has its own strengths, and

0409vsm_How-To_26-32.v5 3/19/09 10:15 AM Page 30

Page 33: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 31

gv.DataSource = dsgv.DataMember = "Results"gv.DataBind()

End Sub

It wouldn’t be a real SharePoint application if it didn’t supportsome level of customization. For my example, the categoryTextBox is supported by a customizable category property thatmanages an internal field called _category:

Private _category As String

<Personalizable(PersonalizationScope.User)> _<WebBrowsable(True)> _<WebDisplayName("Movie category")> _<System.ComponentModel.Category( _"Movie Search Settings")> _ <WebDescription( _"A valid movie category to search within")>

Public Property Category() As StringGet

Return _categoryEnd GetSet(ByVal value As String)

_category = valueEnd Set

End Property

When the SeachCategory TextBox is added to the Table thatmakes up the control, I initialize the TextBox with the _categoryfield that is set through the personalizable property:

Dim SearchCategory As New TextBox()SearchCategory.Text = _categorytcCategory.Controls.Add(SearchCategory)

SharePoint will now allow the user to set a value for the Categoryproperty by selecting the “Personalize this Page” choice on the“Welcome User”menu at the top of the page to put the page in “per-sonalization mode.” Once the user enters a value, SharePoint willensure that the property is automatically set to that value wheneverthe user returns to the page.

Simple DebuggingAt this point, you get the real payoff for the work you’ve done in set-ting up SharePoint Extensions and configuring your project: to testand debug your project you just set breakpoints in your code andpress F5. When your site displays, you’ll need to add your Web Partto a page by selecting, from the Site Actions menu, the Edit Pagechoice. When the page redisplays in Edit Mode, click on any of theAdd Web Parts bars to display the Add a Web Part dialog with yourWeb Part. After adding the Web Part to your page you’ll find thatyou can debug it as you would any other .NET project type.

The SharePoint Extensions are a real boon for developerscreating SharePoint apps. In addition to simplifying the processfor creating new Web Part projects, the debugging process ismuch simpler. Not only does this make life easier forSharePoint developers, it lowers the barrier to entry forASP.NET developers interested in migrating their skills to theSharePoint arena. 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 design. He’s written several books on app development using

Microsoft technologies and presents at conferences around the world.

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to godirectly to these related resources.

READ & DOWNLOAD

VS0904PV Read this article and download the associated code.

SHAREPOINT EXTENSIONS HOW-TO

each is better suited in different parts ofan application,” Andrew says.

“Complex data with a deep relationalstructure doesn’t fit well in SharePointlists,” according to John Beasley, a direc-tor with U.K.-based Microsoft GoldCertified Partner InfoStrata Solutions Ltd.To get around this, he uses Quest WebParts for SharePoint, which allows simplerelational structures to be simulated inSharePoint lists, as well as allowingdevelopers to keep data in SQL Serverwhile accessing it via SharePoint.InfoStrata is a Quest partner, but thereare other third-party tools developers—such as Bamboo Solutions andCorasWorks Corp.—that make use ofASP.NET Web Parts Controls to enable thebuilding of customizable pages.

SharePoint, Beasley notes, removesthe tedium of re-developing routine facili-

ties, such as security, document manage-ment and workspaces. “This massivelyreduces our time to market,” he says in ane-mail. Using these tools “means you getto do all the correct data analysis you’reused to, but can still use SharePoint toprovide all the front-end facilities it’s sogood at providing.”

Adding ControlsStill, others argue that companies need tounderstand when to build applications forSQL Server versus SharePoint. “Lookingat SharePoint Lists and relational data-bases, there isn’t a comparison,” saysGraham Sutcliffe, director of technologyat RD2 Inc., a Dallas-based design firm.

“They both have their uses. Youcan’t stifle an organizations progression,but you have to put people in charge ofits data. Not trusting the data is the same

as not trusting the CEO’s decisions,because essentially that’s what decisionsare made upon,’ he says, before adding acaution: “One thing you don’t want to dois swing the pendulum too far and turnthe people responsible for data into a reli-gious organization.”

Others are avoiding the problemaltogether by putting controls over who’spermitted to commit data to MOSSservers. That’s the case for the city ofPrince George, British Columbia, Canada.“We’ve locked it down pretty much, sothat all they can do is put in contentdirectly,” says programmer and analystRob Woods. “Nobody else really has theoption of doing any of this kind of stuffexcept for the IT staff.”

Jeffrey Schwartz ([email protected]) is

the news editor for Visual Studio Magazine.

0409vsm_How-To_26-32.v5 3/19/09 10:15 AM Page 31

Page 34: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

XM

L L

iter

als

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com32

{ O N V B }

IN THIS SECTION: On VB · 32 // C# Corner · 40 //Ask Kathleen · 42 ///////////

Y O U R C O D E S O U R C E</Language Lab>X

ML

Lit

eral

s

XML Literals, WCF and LINQ Learn how to create powerful templates that can becalled from both client- and server-side code. BY STEELE PRICE

One of the great things about .NET Framework is that there isso much included to make your life as a developer easier. Overthe past few years we’ve been flooded with new capabilities.Staying current with all of these tools is nearly a full-time job.So what’s a developer to do? I choose to pick the tools that applydirectly to a problem I need to solve and use those new capabili-ties to enhance my productivity. Even more power and flexibili-ty comes when we can take several of these capabilities andcombine them for a unique solution to a problem.

We’re going to look specifically at three pieces of theframework that can be combined to provide a new technique.This technique helps in writing more responsive ASP.NET pages,while at the same time making the code more readable. Thethree technologies are: XML literals, Windows CommunicationFoundation (WCF) Factory Services and LINQ. XML literalsand LINQ are new in Visual Basic 9 (VB9). LINQ gives us acommon syntax for querying just about any data, be it SQL,XML or objects. Even though WCF has been here for a while,the out-of-the-box readiness for building factory services is lit-tle-known. Here we’ll show you how to create WCF services with-out changes to config files for endpoints, behaviors and bindings.

XML LiteralsVB9 includes XML literals, an incredibly useful new tool. WithXML literals, what used to be an archaic, difficult process ofreading and writing raw XML or XHTML has become straight-forward and simple. Type raw XML into the Visual StudioEditor and it understands that you want an XElement. An XMLliteral on its own is a remarkable piece of technology that canhelp VB developers in many, many ways.

What used to make code difficult to read becomes trans-parent when using XML literals. For example, using aStringBuilder to write long strings makes writing joined stringseasier and more performant:

Dim MyText = String.EmptyDim sb As New StringBuilderWith sb.Append("This is a String.").Append(vbCrLf).Append(vbTab).Append("You will notice that the whitespace ").Append("is retained when we use the string.").Append(vbCrLf).Append(vbTab).Append(vbCrLf).Append(vbTab).Append("This is just the beginning and is a bit ").Append("easier to read than StringBuilder, right?")MyText = .ToString

End With

Reading and writing these in the editor is less productive than ifyou could just write the whole string and retain the whitespaceas follows:

<MyString>This is a String.You will notice that the whitespace is retained when

we use the string.

This is just the beginning and is a bit easier to readthan StringBuilder, right?</MyString>

Compared to StringBuilder, XML literals are far easier to readand much less to type. Use MyString.Value to get the text insidewithout the <MyString> tags. The goal here is not to maximizeperformance in the runtime, but to be more productive. Youcan actually read the string and don’t worry; performance willstill be very good.

String handling with XML literals is just a side note. Forstructured elements that really are XML, such as XHTML, thereis no comparison. The XML literals approach gives us a highlyreadable, productivity enhanced solution to writing structuredXML in code behind. Consider the following:

XML literals give you the power to create data presentation dynamically, in ways that are more productive

than many other alternatives.

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 32

Page 35: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Language Lab

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 33

XM

L L

iter

als

Dim MyTable = _<table><tr><td>First Cell Contents

</td><td>Second Cell Contents

</td></tr>

</table>

Reading XHTML in code behind isnow remarkably easier. You also gettrue IntelliSense for the elements thatare in a known namespace, which ofcourse means even less typing. XMLnamespaces are recognized by usingImports statements such as the follow-ing for XAML:

Imports <xmlns= "http://schemas.microsoft.com/ winfx/2006/xaml/presentation">

Imports <xmlns:x= "http://schemas.microsoft.com/ winfx/2006/xaml">

Imports System.Windows.Markup

The result of all this is that you can do things the same way forcode behind as you are used to doing in ASPX source view.Productivity increases by continuing to write markup this way.You do not have to learn another language or syntax to achievethe same in code behind.

Embedded expressions also look very similar to what youare used to seeing in markup:

<td><%= item.@id %></td>

An embedded expression lets you access something outside theXML literal and embed it into the result. In this case; item.@idis an attribute from an item element in another XElement.Additionally, variables aren’t limited here; you can use lambdas,functions or anything else available to VB.

I know what you’re thinking, so I’ll go ahead and say it. “Ifyou’re loading from XML and returning XML, can’t you justuse XSLT?” Of course we could, but what fun is that? In fact, Icame up with this technique in a project overhaul that wasusing XSLT in its previous version. During development, itbecame quite clear that working in XSLT was not the way to gofor us. XSLT is a completely different mindset for most of usand has a fairly steep learning curve. In addition, the old sys-tem was forcing SQL to return data as XML, which is notexactly optimal. This approach eliminated that issue whiledramatically improving performance. Ultimately, using XMLliterals means you can be productive faster and have more

tools at your disposal for debugging, without learning a newlanguage.

WCF Factory ServicesI have a Web site that is currently in production. I need to addsome performance features to it and I don’t want to retool toaccomplish what I need. I could use AJAX and update panels,but then I would need to account for the entire page lifecycle,which in some cases may be quite large.

For example, I have a page that contains aggregate infor-mation and I wish to display that in a table format. I could putall my aggregates into GridView objects and then place thoseinside update panels, then … no, no, no. I’m sure you see thetrouble here already. If I have more than one update panel onthe page, I’m really loading the entire page multiple times, justto get my aggregated information to run asynchronously.

How can you achieve this without creating a new project,using PageMethods or something else with a large lifecycle?Enter Windows Communication Foundation (WCF). WCF hasalways had a lesser-known feature called a factory service. Withfactory services, you don’t have to worry about things like secu-rity, as it inherits the same security as the site. As for config set-tings, there are none. This is a perfect solution when you need toaccess some information in an AJAX way from client-side code.

The factory services are quite similar to WebMethod(), butthey’re completely WCF compliant. To create a factory service,you simply create a new WCF service. But wait, you said factoryservice; I don’t see any factory service in my Add Items templates.

That is correct, to create a configuration-less factory serv-ice you need to do it by hand; editing the .SVC file of an AJAX-enabled WCF service. To do this, open the .SVC file with theXML editor and add the following:

Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"

FIGURE 1. When you add a new template to your Web application, it appears in the MyTemplates area at the bottom of the Add New Item dialog box.

On VB

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 33

Page 36: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com34

Then you have to go and delete the config information.Because this isn’t an intuitive way to proceed, I created a tem-plate that you can install to do the same thing. Install the template by copying WCF_FactoryService.zip toC:\Users\<yourusername>\Documents\Visual Studio 2008\Templates\ ItemTemplates\Visual Basic

With this template, you can create services that your Webapplication can use in a very easy way with no bother to the cur-rent configuration. If you need to move to a full service with dif-ferent bindings, it’s very easy to change this from a factory serv-ice. Simply delete the factory attribute from the .SVC file andadd your binding, behavior, service and endpoint configurationsto web.config.

Something you might be thinking: Why use WCF servicesand not a regular page that just returns the small amount of datawe need?

While this approach makes sense in some instances, youstill have a full-page lifecycle to deal with. Furthermore, theresults aren’t as easy to work with when you want to insert theminto a portion of an already rendered page with JavaScript. Ifyou used a page you would have to do quite a bit of parsing. Inaddition to the speed of execution for WCF, there are support-ing features that will make life easier. Throwing FaultExceptionsis one thing you cannot do with page results. You can throwHttpExceptions, but they aren’t handled the same way on the client.

Using LINQLINQ provides the magic you need to glue all this together.Writing markup in code behind is easier to read, while accessingthe same code from both the client side and the server side givesyou a lot of power. Combining LINQ and embedded expres-sions in XML literals gives you a better way to handle loopingthrough data.

Instead of a table, let’s shift to something more demonstra-tive, the <ul> element. Say you just need to iterate through agroup of items and return an unordered list. Unordered lists aregreat for things like menus and navigation. How is this accom-plished with our new toolset? Let’s look into that now. In the pastyou had to do something like the following:

Dim ul as New HtmlGenericControl("ul")Dim li As HtmlGenericControlFor Each i In itemsli = New HtmlGenericControl("li")li.InnerHtml = i.Valueul.Controls.Add(li)

Next

Now you can do this:

Dim MyMenu = <ul><%= From i In items Select <li><%= i.Value %></li>%></ul>

The embedded expressions let you insert external data intoyour elements with much less code. Given the same data, theoutput is identical.

Let’s dissect what’s happening here. MyMenu is anXElement cast by Option Infer, which is a new feature in VB9that lets you declare variables without explicitly stating a datatype. The compiler infers the data type of a variable from the type of its initialization expression. The <ul> element isoutside the LINQ query so it’s not repeated. The LINQ queryiterates through the items and returns a group of <li> ele-ments inside the <ul> element, with the item’s value insertedinto the list item.

All of this can now be done in one line of easy to read andsimple to type code. Anything used for lists of data can be donethis way: tables, unordered lists, ordered lists, select inputs(dropdowns), and the like. Have you ever done a view source ona page only to see a dropdown with all the states listed as optionsin the HTML? Using WCF services with AJAX will keep peoplefrom being able to see this with view source. You’ll probably getyour page to load faster if that was an AJAX call.

XML literals give you the power to create data presenta-tion dynamically, in ways that are more productive than manyother alternatives. Any LINQ-enabled data, SQL, entities,objects, files, WMI, XML, RSS feeds and the like can beaccessed this way.

Now that you have all three pieces in place, your Web appli-cation is wired up to both client and server sides. Accessing theservice from the server is as simple as calling a method. The serv-ice is already there and calling it is as simple as Services.GetPresidentsList().

On the client you can use ASP.NET AJAX or jQuery to call the service. Referencing services in ASP.NET AJAX isincredibly easy—just add a ScriptManager that points to theservice as follows:

<asp:ScriptManager ID="ScriptManager1" runat="server"><Services><asp:ServiceReference Path=

"~/Services/MyFactoryService.svc" /></Services></asp:ScriptManager>

Calling the service in JavaScript is now very easy and completelywired up for us:

function getPresidents(){var ws = new Services.MyService();ws.GetPresidentsList(getPresidentsComplete);

}

function getPresidentsComplete(result, eventArgs){if (result.d !== null){$find("<%= PresidentsArea.ClientID %>").InnerHtml =

result.d;}}

</Language Lab>X

ML

Lit

eral

s

On VB

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 34

Page 37: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

PUREVISUAL STUDIO AND .NET

PUREVISUAL STUDIO AND .NET

OPTIMIZED FOR

PRINT ✱ ONLINE ✱ EVENTS

For more information visit:www.VisualStudioMagazine.comwww.RedDevNews.comwww.VSLive.com

M A G A Z I N E . C O M

POWERING THE WINDOWS SOFTWARE REVOLUTION

E N T E R P R I S E S O L U T I O N S F O R . N E T D E V E L O P M E N T

0208vsm_VSMPureAd.final 1/18/08 11:46 AM Page 32

Page 38: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com36

This makes an asynchronous call to the service and the result isre t u r ne d w h e n t h e s e r v i ce p e r f o r m s a c a l l b a c k togetPresidentsComplete (). You have the ability to call the serviceboth synchronously and asynchronously, depending on whatyou need to accomplish. Here’s the same idea using jQuery:

$.ajax({type: 'POST',url: '/Services/MyFactoryService.svc/'

+ 'GetPresidentsList',data: '{}',contentType: 'application/json; charset=utf-8',dataType: 'json',success: function(result, eventArgs) {if (result.d !== null){$("#<%= PresidentsArea.ClientID %>")

[0].innerHTML = result.d;}},error: onServiceError

});

The json notation is assigned for the dataType because WCF isreturning JSON for the result object. The syntax is a little differ-ent, but is still pretty easy to use. jQuery’s nice ajax() methoddoes all the work for you, and what you get returned from theservice ends up in result.d. I used an anonymous function hereto retrieve the result, which we expect to be XHTML into theInnerHtml of our div element target.

We can inspect for errors, but you can see that if we threwany FaultExceptions in the WCF service, then another functioncalled onServiceError runs. The Error Handling function ispassed to the result object for us to inspect for errors and reactaccordingly.

My normal process for using this in a production applica-tion is to define a single function in my master page for callingthe service. If you provide accessibility through several short-cuts, getting results from the services and assigning those resultsbecome even easier.

Here’s a sample that I’ve used:

function execMyFactoryService(method, target) {var rval = '';$.ajax({type: 'POST',url: '/Services/MyFactoryService.svc/' + method,data: '{}',async: true,contentType: 'application/json; charset=utf-8',dataType: 'json',success: function(result, eventArgs) {

if (result.d !== null){target.innerHTML = result.d;

} },

error: function(result) {var msg = '';if (result.get_message) {msg = 'Error: ' + result.get_message();

} else {msg = result.responseText;if (msg == '') { msg = 'Error: Unknown... missing Service?'; }

}alert(msg);target.innerHTML = '';

}});

}

Assigning our result to a position on our page is simple. Placea <div> element anywhere on your page and set theinnerHTML to the result. Anywhere I’m using that masterpage; I will have a function that I can use to directly assign the results:

execMyFactoryService('GetPresidentsList',$("#<%= PresidentsArea.ClientID %>")[0]);

All the error handling and result inspection is handled centrallyand when we’re assigning results as the response to some actionon the Page, this makes understanding what’s happening mucheasier. If we were to use the full $.ajax syntax everywhere weneeded to use it, it might make the scripting too verbose to bereadable at first glance.

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

The Whole PictureNow that I’ve explained the parts and pieces, how does it allwork together? Let’s explore this a little further. A completetemplate looks like this inside the service:

<OperationContract()> _Public Function GetPresidentsTable() As XElementDim items = XElement.Load(ApplicationPhysicalPath & _

"App_Data/SampleData.xml")TryDim result = _<table><thead><th>Position</th><th>Name</th><th>Began Term</th><th>Finished Term</th>

</thead><%= From i In items.Elements Select _

</Language Lab>X

ML

Lit

eral

s

On VB

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 36

Page 39: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

<tr><td><%= i.@id %></td><td><%= i.@Name %></td><td><%= i.@Start %></td><td><%= i.@End %></td>

</tr> _%>

</table>Return result

Catch ex As Exception' This is not returning a StackTrace, ' it’s a shortcut to get the current Method NameThrow New FaultException(New StackTrace() _

.GetFrame(0).GetMethod() _

.Name & ": " & ex.Message)Return Nothing

End TryEnd Function

The service is a WCF factory service. These are very simple tocreate, with the Visual Studio Template included here.

I use a Services Folder in my Application for organizationand security. Add the Services Folder, and then add a web.con-fig for the folder. This lets us assign different security rights tothe services in the folder if we need to limit them by Roles.Adding a New Item to your Web Application looks like Figure1, p. 33.

The new Template is in the My Templates area at the bottomof the dialog. If you’re like me, you probably have many installedTemplates you need to scroll through to get to My Templates.

When the template creates the service, we can inspect theconfiguration data using Open With.

Choose XML Editor from the list. This will open the .SVCfile for us, rather than the code behind that gets opened whenyou double-click on the file itself. You may see someIntelliSense confusion from the editor, but you can safelyignore it.

The generated service is:

<%@ ServiceHost Language="VB" Debug="true" Service="Services.MyFactoryService" Factory="System.ServiceModel.Activation.

WebScriptServiceHostFactory" CodeBehind="MyService.svc.vb" %>

The code behind is:

Imports System.ServiceModelImports System.ServiceModel.Activation

Imports System.Web.Script.SerializationImports System.Runtime.Serialization

Namespace Services

''' <summary>''' This Service provides access to various ''' MyFactoryService procedures through WCF''' </summary>''' <remarks></remarks><ServiceBehavior( _

IncludeExceptionDetailInFaults:=True)> _<ServiceContract(Namespace:="Services", Name:= _

"MyFactoryService")> _<AspNetCompatibilityRequirements( _

RequirementsMode:= _AspNetCompatibilityRequirementsMode.Allowed)> _

Public Class MyService

<OperationContract()> _Public Sub DoWork()

End Sub

End Class

End Namespace

All that’s left for us to do is enter the code into DoWork().Usually you’ll want to rename this, which is fine, because what’spresented here is just a stub to get us started.

For debugging we simply add a Try/Catch block to handleanything bad that may cause the template to break. For thisexample we are just returning Nothing, but we could add veryrich error handling here by throwing FaultExceptions.FaultExceptions are handled quite nicely by ASP.NET AJAX andjQuery on the client. You can decide how to handle problems inthe service and the client can respond using a combination ofresults and error handling.

Let’s talk briefly about what you can do with this in yourtoolbox. I want to display a bunch of images dynamically.Maybe I want to get the results from a search out on the Web. Icould configure something in the client, or I could stay consis-tent and use our own services. This lets us control everythingand not expose possibly sensitive information in the client-side code, such as a password. We won’t build that one rightnow, but think about how useful it could be to control goingout to your external service accounts to grab dynamic statusor images from social networking services.

In our Presidents sample we could go look on an externalservice for the images of the Presidents. Configuring this isreally quite easy now that we have a set of tools to work withthat makes this simple. I could use a WebClient to call the

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 37

XM

L L

iter

als

Lambdas are a new feature in VB9 and can save you a lot ofhassle when you need a quick function. LINQ itself is actually a framework

built on lambda expressions and are an integral part of how it works.

On VB

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 37

Page 40: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com38

external API and work with the results in the service prior toreturning them.

What if I already have the images? How do I get themfrom the file system easily? I would create a service methodsimilar to this:

<OperationContract()> _Public Function GetPortrait( _

ByVal value As String) As XElementDim image = (From FileName In _

My.Computer.FileSystem.GetFiles( _HttpContext.Current.Server.MapPath( _"~/Images"))

Where FileName.StartsWith(value) Let File = _My.Computer.FileSystem.GetFileInfo(FileName) Select <img src=<%=

HttpContext.Current.Server.MapPath( _File.FullName) %>title=<%= File.Name %>></img>).First()

Return imageEnd Function

I have provided a dynamic function to return an image fromour file system—certainly not a daunting task for us now. Wecan expand this to handle getting the image path any way thatsuits our needs and we can surround all the proper error han-dling in the function. I can return either an appropriate faultexception or an empty element to just ignore missing images, sothe client doesn’t see errors.

When designing a template consider what’s static andwhat requires looping. Looping should be done with eitherLINQ or lambdas in this case. A Do Loop or For Each worksjust as well, but I find myself replacing them with LINQ since Ihad no other alternative before. It also makes the code mucheasier to work with in templates if you use LINQ.

Something to consider here is the use of lambda expres-sions. Lambdas are a new feature in VB9 and can save you a lot of hassle when you need a quick function. LINQ itself isactually a framework built on lambda expressions and are anintegral part of how it works. Lambdas in Visual Basic looklike this:

Function(u) If(u.Age < 18, _u.ParentPermissionGranted, u.PermissionGranted)

This function will evaluate the condition, and then return adifferent field from the user object based on the condition.The interesting thing here is that we didn’t have to tell thelambda what u is, inference will do that for us most of thetime. Occasionally inference gets confused and you may needto qualify what u is which you can do with:

Function(u As User)

I don’t want to go on too much about lambdas, you will usethem all the time with LINQ. Just about any time you need aWhere clause you’ll be using lambdas. LINQ hides some of theverbosity for you when you’re using the full query syntax, butit’s still a lambda. When you use the extension syntax youalmost always use lambdas:

items.Elements.Where(Function(i) i.@id = 1)

Another reason I bring this up now is to answer the question:What if we need to return complex conditioning to our datawhen we build the return? This is much easier with lambdasthan creating a bunch of functions that may only be used forthis specific template. When building our template, maybe wewant to change the elements returned based on some criteria inthe data. Extended syntax like lambdas make very powerfultools for building templates.

Easy Formatting Based on ConditionsBecause we have a true ternary If() command available to us wecan make templates that do this:

<%= If(items.Count = 0, _<tr id="norecords" class="GridRow"><td style="text-align: left" colSpan="4"><div>No records to display.</div>

</td></tr>, _CType(Nothing, XElement)) _

%><%= —- continue normal processing —- %>

This template lets us return Nothing when we have real data towork with, or an element describing the lack of data to theuser. I can go on and on about the wealth of possibilities youhave at your disposal when using all these techniques together.

</Language Lab>X

ML

Lit

eral

s

jQuery provides a great productivity boost through a superbset of tools for navigating and manipulating DOM objects in JavaScript.

Some of the same features are in ASP.NET AJAX, but the two models can beused together to provide even more power for your client-side activities.

On VB

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 38

Page 41: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 39

� dozens of indexed, unindexed, fielded data and full-text search options (including Unicode support for hundreds of international languages)

� file parsers / converters for hit-highlighted display of all popular file types

� Spider supports static and dynamic web data; highlights hits while displaying links, formatting andimages intact

� API supports .NET, C++, Java, databases, etc. New .NET Spider API

Contact dtSearch for fully-functional evaluations

The Smart Choice for Text Retrieval®

since 1991

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

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

� “For combing through large amounts of data,” dtSearch “leads the market” – Network Computing

� dtSearch “covers all data sources ... powerful Web-based engines” – eWEEK

� dtSearch “searches at blazing speeds” – Computer Reseller News Test Center

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

Instantly SearchTerabytes of Text

Network with Spider Network with Spider

Web with SpiderWeb with Spider

Desktop with SpiderDesktop with Spider

Network with Spider

Web with SpiderPublish for CD/DVDsPublish for CD/DVDsPublish for CD/DVDs

Desktop with Spider

Engine for LinuxEngine for LinuxEngine for LinuxEngine for Win & .NETEngine for Win & .NETEngine for Win & .NET

New64-bitNew64-bit

The Bottom LineCurrently, nothing else is this flexible and this easy with the out-of-the-box tools we get with Visual Studio 2008. You have com-plete access to all the features of .NET Framework for buildingyour templates. Calling them from both the client and server isextremely easy, and because you’re using WCF, ther’s no addedpage lifecycle overhead. A similar service can be created to returnXAML instead of XHTML. This makes migrating or extendingyour templates extremely easy if you need access from Silverlightor WPF in the future.

T4 templates and other code generator-based utilities aregreat when you can generate everything in advance. This tech-nique goes beyond that to generate during runtime, and we cangenerate runtime-ready code in any XML derivative such asXAML and XHTML.

ASP.NET 4.0 is expected to provide a new template system,but that doesn’t change the usefulness of this technique. ASP.NET4.0 will be using a completely different system, which may or maynot be as easy to use and as flexible in what it returns. From whatI’ve seen so far, it looks good, but it still doesn’t solve the immediateissues that are addressed by using this technique.

XML literals, WCF factory services and LINQ, taken bythemselves, are very useful. When these are combined, you get acompletely different picture for solving real-world problems. Allwhile maintaining a productive, easy-to-implement style.

XML literals provide high productivity and readabilitywhen writing structured XML in code behind. It can also helpformat long or complex strings to make them more readable.Embedded expressions give you the power to insert externaldata into the XML in a very easy-to-read and -maintain way.

WCF factory services allow you to extend the power of theframework to your client-side code without the hassle of all theconfiguration knobs and buttons that are available to WCF services. Starting with a factory service does not limit you in anyway from upgrading to the full configuration format later. Asimple change enables a progressive upgrade path when youneed this ability.

Finally, using LINQ in embedded expressions enables youto insert external data into XML in a way that is easy to read,with much less code to accomplish the task. LINQ allows you tostart thinking differently about how you process loops throughany data utilizing the same syntax. Now go see what you can dowith all this new power and productivity. VSM

Steele Price ([email protected]) has been professionally designing and

developing data-driven applications for more than 25 years. He has been a

Microsoft MVP for Visual Basic since 2005 and frequently works with the

Microsoft VB team to help improve the language. Price is currently chief

technology officer at Digital Dreamshop, a micro ISV developing enterprise

applications with VB.NET, Silverlight, Windows Presentation Foundation

and LINQ.

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to godirectly to these related resources.

READ MORE

VS0904OV Read this article online.

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 39

Page 42: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com40

</Language Lab>

Make Your Code ClearThere are multiple ways to solve every problem. Strivefor code that communicates your intent and makes yourmeaning clear for every developer who uses it.BY BILL WAGNER

It’s often not that hard to create code that works. What oftenseparates average code from high-quality code is how well thatcode—especially its public interface—describes its own capa-bilities. A small time investment in your code will save timeexplaining how it works and avoid enhancing it unnecessarily,creating more work for yourself and your users.

In this article, I’ll walk you through a review of a smalllibrary, discussing a series of changes and the motivationbehind those changes. You’ll see how to improve the resiliencyand quality of a codebase.

A Working Numeric LibraryListing 1 (opposite page) shows a small numeric class that per-forms a few simple calculations on a sequence of numbers. Thislibrary has some simple mathematical functions: mean, medi-an, variance, minimum and maximum. It’s not a major library,but there are enough methods here to demonstrate the con-cepts involved in shaping the impression your code can give tocustomer developers.

This library works, but there are many areas where the codecan be improved.When developers look at your API, they’ll createan impression of the library based on your stated API. If they’reyour team members and they examine your source, they’ll contin-ue to build on those assumptions. Your code gives those clientdevelopers an impression of your code. You’re going to spendyour time making its intent clearer, not fixing behavior.

The first problem is that all of the methods on this class areinstance methods. There’s no reason for instance methods onthis class. The first change is to make all the methods staticinstead of instance methods:

public static double Mean(List<double> sequence)

After this change, your customers no longer need to create aNumericAlgorithm object in order to use these methods.Instead of writing this:

NumericAlgorithm target = new NumericAlgorithm();List<double> sequence = new

List<double>(Enumerable.Range(1, 50).Select(n =>(double)n));

double actual = target.Mean(sequence);

After this change, they can write this simpler version:

List<double> sequence = newList<double>(Enumerable.Range(1, 50).Select(n =>(double)n));

double actual = NumericAlgorithm.Mean(sequence);

One less line of code, and that means one less bit of work forevery use of your library. Of course, this first change leads to theobvious change of making the NumericAlgorithms class a staticclass:

public static class NumericAlgorithm

Doing so prevents any customer from accidentally creating aNumericAlgorithm class. It also prevents library maintainersfrom creating instance data or instance methods in the class.

These are small changes, to be sure, but they do preventusers from accidentally doing the wrong thing.

Next, you should look at the current API and consider itslimitations. All the APIs use List<double> as the inputsequence. That’s unnecessarily limiting. The internals of themethods don’t rely on any capabilities beyond IEnumerable<double>. You can see the costs of this restriction on the samplecode. Instead of writing this:

List<double> sequence = new List<double>(Enumerable.Range(1, 50).Select(n =>(double)n));

Users should be able to write the simpler version:

IEnumerable<double> sequence = Enumerable.Range(1, 50).Select(n =>(double)n);

This version allows users to call your library using any type ofcollection: a list, an array or even a dynamically read sequenceas I’m using above.

This changes the signatures of all the methods in the class:

public static double Mean(IEnumerable<double> sequence)

In addition, you’ll need to change the internal implementationof some of the methods. In particular, the Mean, Median andVariance methods now must generate both the sum and thecount of elements. That’s because IEnumerable<T> doesn’tcontain a Count property where List<T> does.

At this point, you’ll notice that some of the methods mightneed additional work. The Mean() and Variance() methodsmust iterate the collection more than once: calculating the sum,the count of items and even the squares of the collection. Youmay be tempted to create more complicated methods to per-form all those calculations in one pass. If you look at the fin-

Cle

ar C

ode

{ C # C O R N E R }

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 40

Page 43: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 41

Cle

ar C

ode

ished version of the numeric library, you’ll notice that I didn’t dothat extra work. I ran some performance tests and found thatmaking those changes just didn’t change the performance metrics by any appreciable amount. Therefore, I went with thesimpler implementation. Your mileage may vary, but test performance before making changes with the intent ofimproving performance.

Also, your algorithms should make the smallest set ofassumptions about the parameters you need. By making fewerassumptions, you automatically get more reach from possibleusers. Look at your methods and determine if you need all thecapabilities of a parameter type. Whenever you can, provide aless-constraining interface.

Avoiding ProblemsI wrote this sample to be representative of common productioncode I see in libraries. Too often, many of the developers I workwith create libraries from the inside out. They have strongknowledge about how they’ll implement a particular set of fea-tures, and that knowledge deeply colors how they create thefunctionality. Those assumptions show up quickly in the testcode. It’s especially evident in the test code that demonstratesthe successful scenarios for your library. For example, let’s lookagain at one of the first test samples for the original library:

[TestMethod()]public void MedianSimpleTest(){

NumericAlgorithm target = new NumericAlgorithm();List<double> sequence = new

List<double>(Enumerable.Range(0, 50).Select(n => (double)n));

double expected = 25;double actual = target.Median(sequence);Assert.AreEqual(expected, actual);

}

Contrast that with the final version:

[TestMethod()]public void MedianSimpleTest(){

IEnumerable<double> sequence = Enumerable.Range(0, 50).Select(n => (double)n);

double expected = 25;double actual = NumericAlgorithm.Median(sequence);Assert.AreEqual(expected, actual);

}

There’s not a huge difference in size. You may not easily see ben-efits when you examine a single test method. Instead, seriouslyexamine the clarity of the test code. Is it clear what the test codeis trying to do? Is it clear how to use the API?

The second test, which executes the exact same actions, hasless code that’s unrelated to the problem at hand. It’s easier tounderstand exactly what test is executing. (I realize that theEnumerable.Range() method may be unfamiliar if you don’tuse LINQ much, but that’s not related to the API.) In fact, usingthe new version, you could replace the range call with an array,or any other storage.

I look at test code as a way to evaluate the code that client

developers will need to write. When possible, I’ll write the suc-cess scenario tests before I create any of the library code. Thatforces me to think about the problem and the solution througha client developer’s eyes: What code would I want to call inorder to solve a given problem? If I start by writing the librarycode, I’ll create a library that looks like how I solved the prob-lem, not a library that looks like how I want to use a solution.

Of course, not every project can be written that way. Toooften, we’re extending existing systems that don’t have a testframework already in use. In that case, you’ll end up workingthrough the tasks I outlined earlier in this article: create the

public class NumericAlgorithm{

public double Mean(List<double> sequence){

double total = Sum(sequence);return (sequence.Count == 0)

? total : total / sequence.Count;}

public double Median(List<double> sequence){

if (sequence == null)throw new ArgumentNullException("sequence",

"Sequence must not be null");if (sequence.Count == 0)

return 0;

List<double> local = new List<double>(sequence);local.Sort();

return local[local.Count / 2];}

public double Variance(List<double> sequence){

double sum = Sum(sequence);if (sequence.Count == 0)

return 0;List<double> squares =

sequence.Select(n => n * n).ToList();double sumSquares = Sum(squares);double variance = (sumSquares + sum * sum /

sequence.Count) / (sequence.Count - 1);return variance;

}

public double Sum(List<double> sequence){

if (sequence == null)throw new ArgumentNullException("sequence", "Sequence must not be null");

double total = 0;sequence.ForEach(num => total += num);

return total;}

}

NUMERIC LIBRARY VERSION 1

LISTING 1 This version of the numeric library works correctly.However, there are many poor practices in this library that make itharder to use. In addition, those practices will confuse users of thecode. They’ll make assumptions about what the code does becauseof how it’s structured. In its current form, those assumptions will be wrong.

C#

C# Corner

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 41

Page 44: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com42

tests; look at the code in the tests; and modify the library until you have the API you’d like. At each step, look at your tests—especially the success tests—and decide if the APIis as convenient as it could be. If not, you should continue tomake modifications until you have an API that matches yourexpectations.

Structuring Your CodeCompare the initial version of the library with the final version(see Go Online for how to access a sample of the final version).Even with only a few methods, you can see more clarity in howthe library will use its parameters and how it can be used. TheAPI more clearly describes how it will be used.

Think about your own classes and examine if they com-municate their intent and their use for other developers. Doestheir structure communicate your design intent? If not, modifythe public API until it matches your assumptions about theusage of your classes.

Your code communicates your design intent to its users.It’s important that you take advantage of this opportunity tocommunicate to the users of your code. Do it well. VSM

Bill Wagner ([email protected]), author of “Effective C#: 50

Specific Ways to Improve Your C#” (Addison-Wesley Professional, 2004)

and “More Effective C#: 50 Specific Ways to Improve Your C#” (Addison-

Wesley Professional, 2008), has been a commercial software developer for

the past 20 years. He’s a Microsoft regional director and a Visual C#

MVP. Wagner’s interests include the C# language, .NET Framework and

software design.

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to godirectly to these related resources.

READ & DOWNLOAD

VS0904CC Read this article and download the associated code.

</Language Lab>C

lear

Cod

e

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

Working with MEFLearn how to free your application from dependenciesand interchange implementations using ManagedExtensibility Framework. BY KATHLEEN DOLLARD

Q: I’ve been hearing the term MEF lately and I know it meansManaged Extensibility Framework, but I don’t understand what itdoes. Would it be a good fit for allowing customers to add their ownforms to our Windows Presentation Foundation (WPF) app? Weneed those new forms to appear in our menus and we don’t want togive customers our Visual Basic source code to recompile.

A:This sounds like a good application for MEF. You could usethe same approach for WinForms or ASP.NET and the C# codewould be similar to what I’ll show here.

MEF is an extensibility model that allows components tointeract using a simple model. Components are called parts inMEF. MEF is designed to be extensible to different types of mod-els, but ships with an attributed model. This lets you define theinteraction between your parts via normal .NET attributes. If apart needs something, it uses an Import attribute and if a partsupplies something it uses an Export attribute. Any part can be ahost or client, provider or consumer. MEF bases these interac-tions on contracts and offers a flexible discovery model. Yourapplication makes a request and leaves it to MEF to provide theimplementation. This frees your application from dependenciesand lets you interchange implementations.

MEF is currently available as a preview on CodePlex. It’s inthe System.ComponentModel namespace, indicating that itwill appear as a full member of .NET Framework 4.0. Several

projects within Microsoft are committed to it, including theVisual Studio (VS) 2010 code editor. Until it appears in .NETFramework, you’ll need to download MEF and placeSystem.ComponentModel.Composition.dll in an accessible location.You should also realize that changes to the API may occur.

Your application will be the MEF host while your cus-tomers will write MEF clients or extensions. Extensions aresimpler to write because the host must also manage theCompositionContainer. I’ll step through the process of creatingan interface, building extensions and building a WPF host. TheWPF host will pass a catalog to a CompositionContainer thatwill specify a directory to search for menu extensions.

Extensions support contracts. The most common con-tracts are interfaces, and these interfaces might be quite simple:

Public Interface IExtensionSub ShowWindow()

End Interface

Your customers can add extensions by implementing this interface and specifying the Export attribute from theSystem.ComponentModel.Composition namespace:

<Export(GetType(IExtension))> _<ExportMetadata("MenuCaption", "First")> _Partial Public Class First

Implements IExtension

Public Sub ShowWindow() _Implements Common.IExtension.ShowWindow

End Sub

C# Corner

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 42

Page 45: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 43

ME

F

End Class

You can also use an arbitrary string to identify the export, butthe common case for extensions is to retrieve via an interfacecontract. The ExportMetadata attribute lets you include extrainformation about the extension that the host can retrieve with-out actually instantiating the underlying object, which lets youcontrol instantiation and protects performance.

When you design your solution, put interfaces in a sepa-rate assembly referenced by both the host and all extensionassemblies. Do not establish any direct references between yourhost and extensions. All of your assemblies will need a referenceto System.ComponentModel.Composition.dll. Your compiledextensions will need to be placed in a convenient location. Youcan specify the build location in the Project Properties dialog.

The host is responsible for managing the Compo-sitionContainer. The CompositionContainer hooks up importsand exports behind the scenes and must know what exports areavailable. Creating the container as a project level variable lets youclean it up in OnExit. The call to the container’s Dispose methoddisposes of any parts that implement IDisposable:

Protected Overrides Sub OnExit( _ByVal e As System.Windows.ExitEventArgs)MyBase.OnExit(e)If mContainer IsNot Nothing Then

mContainer.Dispose()End If

End Sub

Overriding the OnStartup method let’s you prepare the con-tainer when your application starts:

Protected Overrides Sub OnStartup( _ByVal e As StartupEventArgs)MyBase.OnStartup(e)If Compose() Then

MainWindow.Show()Else

Shutdown()End If

End Sub

The compose method does the actual preparation:

Private Function Compose() As BooleanDim cat As New AggregateCatalog

The aggregate catalog allows you to manage several catalogstogether. If a set of catalogs appear together in an aggregate cat-alog, all matching items within this set of catalogs are discov-ered. Several different types of catalogs are available, includingDirectoryCatalog, which loads all assemblies in a specifieddirectory. In your case, I’d suggest including the location ofextensions as part of the application settings to allow later con-figuration. You’ll also add the current assembly:

Dim extLocation = My.Settings.ExtensionLocationcat.Catalogs.Add(New DirectoryCatalog(extLocation))

Ask Kathleen

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 43

Page 46: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com44

cat.Catalogs.Add(New AssemblyCatalog( _Me.GetType.Assembly))

mContainer = New CompositionContainer(cat)

At this point the container is ready to work, but no work hasbeen requested. A composition batch allows you to specify theitems to evaluate for Import requests when you call theCompose method. Any object later instantiated via an Importrequest will also be evaluated for additional Import requests. Inmany cases the first call to Compose will be the only one youneed to perform. Because Compose performs the composition,it will fail if composition rules are not followed, so theTry/Catch block provides reporting:

Dim batch = New Hosting.CompositionBatch()batch.AddPart(Me)TrymContainer.Compose(batch)

Catch ex As CompositionExceptionMessageBox.Show(ex.ToString())Return False

End TryReturn True

End Function

The Main window of the application uses anImport attribute on a field. For MEF to satisfy thisrequest and create the field value, the Main windowitself must be provided via MEF—MEF evaluatesImport attributes on anything explicitly added to abatch and anything that is instantiated via anotherImport. You can do this by replacing theMainWindow method in the base class viaOverloads (new in C#):

<Import(GetType(Main))> _Public Overloads Property MainWindow() AsWindowGetReturn MyBase.MainWindowEnd GetSet(ByVal value As Window)MyBase.MainWindow = valueEnd Set

End Property

There’s one more detail specific to VB. The ApplicationFramework automatically instantiates the specified window andbypasses your MainWindow property. Disable the ApplicationFramework and add a Sub Main to the Application.xaml.vb file:

'''<summary>'''Application Entry Point.'''</summary><System.STAThreadAttribute()> _Public Shared Sub Main()Dim app As Application = New Applicationapp.Run()

End Sub

</Language Lab>M

EF

The menu caption is retrieved from the MEF metadata.While this works, your goal is to make life as easy as possible for

programmers writing extensions. This metadata approach requires they know to use the exact string "MenuCaption". It’s easy to fix this using

strongly typed MEF metadata.

Managed Extensibility Framework offers several catalog types. The directory catalog searches a file system directory for parts that match yourimport requests. This lets your users add extensions just by dropping assemblies into a specified directory.

Ask Kathleen

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 44

Page 47: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 45

ME

F

This causes the application to retrieve the MainWindow via theproperty and thus evaluates MEF requests in the Main window.The Main window exports itself to MEF to match theMainWindow property import:

<Export(GetType(Main))> _Partial Public Class Main

The Main window uses MEF to discover available extensionsthat implement the IExtension interface:

<Import(GetType(IExtension))> _Private exportExtensions As ExportCollection( _

Of IExtension)

Anything that appears in the catalog or is manually added to thecontainer through batches and implements the IExtension inter-face will appear in this collection. Note that this creates a collec-tion of Export objects that contain sufficient information toinstantiate the actual extensions, but they do not yet instantiatethem. This is important to maintain adequate performance.

The Main window fills the menu using standard WPF code:

Private Sub Main_Loaded() Handles Me.LoadedFor Each export In exportExtensions

Dim newItem = New MenuItem()newItem.Header = export.Metadata("MenuCaption")Me.ExtensionMenu.Items.Add(newItem)

Next

End Sub

Note that the menu caption is retrieved from the MEF metadata.While this works, your goal is to make life as easy as possible forprogrammers writing extensions. This metadata approachrequires they know to use the exact string "MenuCaption". It’seasy to fix this using strongly typed MEF metadata. To begin,create an interface:

Public Interface IExtensionMetadataReadOnly Property MenuCaption() As StringEnd Interface

Now create an attribute that parallels this interface. This attrib-ute needs to match the metadata interface. It does not need toimplement the interface, but this is the easiest way to keep themin sync:

<MetadataAttribute(), AttributeUsage( _AttributeTargets.Class)> _

Public Class ExtensionMetadataAttributeInherits AttributeImplements IExtensionMetadataPrivate mMenuCaption As StringPublic Sub New(ByVal menuCaption As String)

mMenuCaption = menuCaptionEnd SubPublic ReadOnly Property MenuCaption() _

As String Implements IExtensionMetadata.MenuCaption

Ask Kathleen

PERFECTION IN SOFTWARE PROTECTION

Exceptional Software Protection

CodeMeter for .NET

Order your Free Software Development Kit now!Phone 1-800-6-GO-WIBU | [email protected]

Access Protection

Document Protection

Software Protection

Media Protection

More than 1000 Key-Storage License Entries�

- Different ISV´s can share one dongleSecure Expiration Date with a Real-Time-Clock�

- Unique Time Certifi cation Feature- Control Relative and/or Absolute timeMore ways to sell = More sales�

Create Student and Version Licenses�

Control Network Licensing�

- Control concurrent users- Control “roaming“ usersCreate “Standby“ Licenses�

- Hot Standby and Cold Standby- Provide Overfl ow Licenses

Pay-Per-Use Counter�

etwork Licensing

WIBU-SYSTEMS USA Inc.110 W Dayton Street,Edmonds, WA 98020United [email protected]

PERFECTION IN SOFTWARE PROTECTION

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 45

Page 48: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com46

</Language Lab>M

EF

GetReturn mMenuCaption

End GetEnd Property

End Class

Your customers can decorate their extensions with this attribute:

<Export(GetType(IExtension))> _<ExtensionMetadata("First")> _Partial Public Class First

You can leverage this metadata by altering the Import request inthe Main window to include a second type parameter:

<Import(GetType(IExtension))> _Private exportExtensions As ExportCollection( _

Of IExtension, IExtensionMetadata)

This provides a strongly typed MetadataView to simplify accessto export metadata:

newItem.Header = export.MetadataView.MenuCaption

While I’ve answered your question, I don’t think I’ve solved yourproblem yet.At this point, the windows display but do not interactwith each other or the rest of your application. That next step iseasy because MEF makes no distinction between extensions andhost while resolving Import and Export attributes. The sample inthe download uses additional interfaces to provide a string toextensions from the host as a simple demonstration.Your app willprobably provide more sophisticated functionality such as theparent window, where extension user controls or specific busi-ness objects or application data should be sited.

It’s valuable to export classes, not primitive values or struc-tures. The values of reference types will reflect changes as yourapplication proceeds rather than reflecting only the value MEFsupplied at composition. This also means two-way communica-tions can be provided either through mutable objects that allowchanges, or through immutable objects that expose specific data.In addition to host/extension interactions, multiple extensionscan communicate with each other using interfaces that areentirely unknown to the host or initial programmers.

The compiler shortcuts recompiling non-referencedassemblies and a composable application doesn’t maintain ref-erences. Avoid problems with out-of-date assemblies by usingRebuild Solution before testing your application.

MEF is similar to System.AddIn (also called MAF), which Idiscussed in April 2008 (see “Extend Your Apps with ExternalAdd-Ins”). MAF is significantly more complex to use, but solvesadditional problems of isolation and versioning. MEF extensionsrun in the AppDomain of the host, with the rights of yourAppDomain. This means when using MEF you must trust exten-sions not to run malicious code, or offer protection via CodeAccess Security. MAF solves this problem by creating extensionsin a separate AppDomain, which you can lock down or sandbox.

You are committing to maintaining the interfaces yourelease to your customers. If you alter the interface, you willbreak their code. Instead you can create a new interface, leavingthe previous interface intact. MEF itself is extensible. If youencounter versioning or AppDomain isolation problems, youcould create an additional programming model that wouldcombine the MEF and MAF, however you would reintroducesome of the complexities of MAF.

MEF also has a direct access API, which you might require,but the Import/Export attribute model is desirable for mostscenarios in VB or C#. The full extensibility of MEF allows itsuse in other scenarios, including dynamic languages, externaldefinitions and alternate discovery mechanisms.

So far, I’ve skipped over the important issues of cardinalityand lifetime. When you place the Import attribute on a singleitem, you state that you expect a single item. The standard MEFcontainer configuration throws an exception if no matches ormultiple matches are found:

<Import(GetType(ITextToDisplay))> _Private textToDisplay As ITextToDisplay

If you know there may be multiple matches, you can importinto an IEnumerable or an ExportCollection. If you don’t wantan exception thrown if no match is found, you can set theAllowDefault parameter on the Import attribute to True. If youdon’t know how many matches will be discovered, place theimport on a collection and manage getting the correct instancein your code.

Lifetime refers to whether a single instance of the export isused for all requests (CreationPolicy.Shared), or a new instancecreated for each request (CreationPolicy.NonShared). Youdeclare the lifetime using a CreationPolicy parameter on theExport attribute or the RequiredCreationPolicy on the Importattribute. The default creation policy is Any and if both Exportand Import attributes have a CreationPolicy of Any, the result isa shared instance. If the CreationPolicies conflict, MEF throwsan exception. This allows you fine grain and flexible controlover instance creation from either the export or import side.

MEF has the capacity to let you build highly decoupledapplications that support customer extensions, granular devel-opment, test mocking and good programming design. It’s agood technique to add to your arsenal. VSM

Kathleen Dollard ([email protected]) is chief technologist for AppVenture

(www.appventure.com), as well as a consultant, author, trainer and speaker.

She’s been a Microsoft MVP for 11 years and an active member of the INETA

Speakers Bureau. She wrote “Code Generation in Microsoft .NET” (Apress,

2004) and blogs at http://msmvps.com/blogs/kathleen.

GO ONLINE

Use this Locator+ code at VisualStudioMagazine.com to godirectly to these related resources.

READ MORE

VS0904AK Read this article online.

Ask Kathleen

0409vsm_Langlab_32-46.v11 3/19/09 10:57 AM Page 46

Page 49: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

VisualStudioMagazine.com · April 2009 · VISUAL STUDIO MAGAZINE 47

Andrew MintzNational Sales ManagerPhone: [email protected]

Chris KourtoglouRegional Sales ManagerPhone: [email protected]

National Accounts DirectorWilliam SmithPhone: [email protected]

Microsoft Account ManagerDanna VedderPhone: [email protected]

West

East

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

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

Ad IndexAdvertiser Page

/n Software Inc. 7www.nsoftware.com

Accusoft Pegasus 23www.accusoft.com

AppDev Training 29www.appdev.com

Aspose C3www.aspose.com

Atalasoft Inc. 21www.atalasoft.com

ComponentArt Inc. 14, 15www.componentart.com

dtSearch Corp. 39www.dtsearch.com

ESRI 5www.esri.com

Intel Corp. C4www.intel.com

LEAD Technologies Inc. 11www.leadtools.com

Microsoft Corp. 18, 19www.microsoft.com

Rally Software 43www.rallydev.com

Software FX C2,1www.software FX.com

Visual Studio Magazine 35http://visualstudiomagazine.com

VSLive! Las Vegas 24, 25http://vslive.com/

Wayside Technology Group Inc. 2www.waysidetechnology.com

WIBU-SYSTEMS USA Inc. 45www.wibu.com

Editorial IndexAAmazon.com Inc. 12, 48www.amazon.com

ArtOfTest Inc. 12, 13www.artoftest.com

CA Inc. 13www.ca.com

Capgemini 20www.us.capgemini.com

ComponentOne LLC 13www.componentone.com

Embarcadero Technologies Inc. 13www.embarcadero.com

Exeros Inc. 13www.exeros.com

IBM Corp. 13www.ibm.com

InfoStrata Solutions Ltd. 31www.infostratasolutions.com

Magenic Technologies Inc. 16www.magenic.com

Northwest Cadence Corp. 20, 21www.nwcadence.com

Quest Software Inc. 13www.quest.com

SAP AG 13www.sap.com

Sybase Inc. 13www.sybase.com

ID StatementVisual Studio Magazine (ISSN 1537-002X) is publishedmonthly by 1105 Media Inc., 9121 Oakdale Avenue,Ste. 101, Chatsworth, CA 91311. Periodicals postagepaid at Chatsworth, CA 91311-9998, and at additionalmailing offices. Complimentary subscriptions are sentto qualifying subscribers. Annual subscription rates fornon-qualified subscribers are: U.S. $34.97, Canada$52.97 (U.S. funds); International $78.97 (U.S. funds).Subscription inquiries, back issue requests, andaddress changes: Mail to: Visual Studio Magazine,P.O. Box 1164, Skokie, IL 60076-8164, [email protected] or call toll free 888-768-8759, fax number 847-763-9564. International calls847-763-9135. POSTMASTER: Send address changesto Visual Studio Magazine, P.O. Box 1164, Skokie, IL60076-8164. Canada Publications Mail Agreement No:40612608. Return Undeliverable Canadian Addressesto Circulation Dept. or Bleuchip International, P.O. Box25542, London, ON N6C 6B2.

Copyright Statement© Copyright 2009 by 1105 Media, Inc. All rightsreserved. Printed in the U.S.A. Reproductions inwhole or part prohibited except by written permis-sion. Mail requests to "Permissions Editor," c/o VisualStudio Magazine, 2600 El Camino Real, Ste 300, SanMateo, CA 94403.

Legal DisclaimerThe information in this magazine has not undergoneany formal testing by 1105 Media, Inc. and is distrib-uted without any warranty expressed or implied.Implementation or use of any information containedherein is the reader's sole responsibility. While the

information has been reviewed for accuracy, there isno guarantee that the same or similar results may beachieved in all environments. Technical inaccuraciesmay result from printing errors and/or new develop-ments in the industry.

Corporate Address1105 Media Inc.9121 Oakdale Ave. Ste 101Chatsworth, CA 91311www.1105media.com

Media KitsDirect your Media Kit requests to Matt Morollo, VPPublishing. Phone: 508-532-1418 Fax: 508-875-6622 E-mail: [email protected]

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

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

Advertising Sales

0409vsm_AdIndex_47.v2 3/19/09 4:35 PM Page 47

Page 50: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

</RedmondReview>

VISUAL STUDIO MAGAZINE · April 2009 · VisualStudioMagazine.com48

Dev

elop

er N

ews

When I wrote my first column for this magazine 15 years ago, I covered a new advance in database programmability for VisualBasic programmers. I’ve been gone from these pages for a while,but I’m back. And, as an appropriate topic for a return engagement,I focus on another database programming advance, this time for.NET developers.

Back then, I explored something called the VB CompatibilityLayer (VBCL), which let VB 3 programmers use version 1.1 of theAccess/Jet Database Engine. VB 3 was the first version of the productto include its own database engine, and the VBCL ensured thenewest version of that engine would be available to its programmers.Compatibility was key then, and it remains so today—as Microsoftseems to have belatedly realized with its cloud computing strategy.

Last month Microsoft announced a major change of coursefor SQL Data Services (SDS), its cloud database offering. AlthoughSDS is not yet released, Microsoft is nonetheless giving the tech-nology a completely different programming interface than the oneit announced more than a year ago. Back then, Microsoft broughtus a product that, while based on a modified version of the SQLServer we all know, had to be programmed through an interfaceand conceptual paradigm that bore very little resemblance to it.

Rather than giving us a database with tables, columns and T-SQL, Microsoft instead provided us with the “ACE” model:Authorities (which were akin to servers), Containers (akin to databases) and Entities (a cross between data records and dictionary objects). The ACE model didn’t have tables, didn’t requireany consistent schema from Entity to Entity and could be accessedonly through SOAP and REST Web service interfaces. Microsoftpromised us relational capabilities for SDS, but appeared set on providing them by enhancing the ACE model, rather than just givingus direct access to the SQL Server behind the curtain.

The ACE model is good for basic storage and retrieval of data.Support for BLOBs means ACE works well for content managementtoo. But for .NET application developers needing to do mainstream

database work (in other words, almost all .NET developers), this firstcut at SDS didn’t make much sense. Microsoft had turned SQL Serverinto a structured storage repository instead of a relational database,and had implicitly told developers that if they wanted to move tothe cloud, they’d need to re-design their databases and re-writetheir code. Ouch.

To call Microsoft tone deaf on this issue would be an under-statement. But eventually the SDS team heard the music, and gotthe rhythm. On Feb. 23, at the co-located VSLive!/MicrosoftDeveloper Conference in San Francisco, Microsoft hinted that theywould re-jigger the SDS model to be relational, and on March 10 itannounced through the SDS team blog that SDS would, in fact, be acloud-based SQL Server, accessible via T-SQL over Tabular DataStream (TDS), SQL Server’s native protocol. Apparently, existing on-premises .NET/SQL Server code will work fine with the new SDS;only a change in connection string will be necessary to turn SQLServer code into SDS code.

So Redmond listened to its customers, and the bizarre obses-sion with copying Amazon’s SimpleDB Web service is over. Microsofthas given us a truly simple offering: the SQL Server technology thatmost Microsoft developers have been using for a decade and some

have been using since even before myfirst column was published.

What’s old is new, I suppose. Fordatabase technologies as well as colum-nists. Aligning SQL in the cloud to SQLon the ground is about more than justcommon sense. It’s about getting thingsdone. Yes, the cloud, done right, will dif-fer from on-premises technology. It willoffer dynamic scaling and utility-based

pricing. In short, it will lower the barrier to entry for getting applica-tions up and running, and keeping them running smoothly.

But the cloud, done right, will reflect and preserve familiaron-premises technology, too. Because the cloud isn’t just abouthow cool it is to run your application “up there.” It’s about easilyprovisioning the servers and services you need to run your busi-ness down here. SDS 1.0 had its head in the clouds; SDS 1.1 isappropriately down to earth. A compatibility layer indeed. VSM

Andrew Brust ([email protected]) is chief, 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).

What’s Old Is New Again

BY ANDREW BRUST

Aligning SQL in the cloud to SQL on the ground is about more than just common sense.It’s about getting things done.

0409vsm_RedReview_48.v4 3/19/09 2:36 PM Page 48

Page 51: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

Project1 2/24/09 10:18 AM Page 1

Page 52: IIDEDE - 1105 Mediapdf.1105media.com/VSMMag/2009/VSM_904DG.pdfevolution of Visual Studio 2010 (see “IDE Evolution,” p. 16), developers find them-selves confronted with a lot of

EVOLVE YOUR CODE.Parallelism breakthrough.

Find out what your Windows* apps can really do with Intel® Parallel Studio. ������������ ����� ������������������������������ �������������������� �������� ������ �������� �� ���� ������� ��� ������ ��������������� ����������������������� ����

������������������������ � �!�www.intel.com/software/parallelstudio

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

Project1 2/25/09 8:40 AM Page 1