Headwinds - 1105 Mediapdf.1105media.com/VSMMag/2009/70023025/VSM_905DG.pdfMicrosoft Tech·Ed North...

52
Headwinds MAY 2009 Volume 19, No. 5 VisualStudioMagazine.com PLUS Create Data-Driven Apps with Silverlight 3 Generate Code Using T4 Templates Why Redmond Needs to Return to Its Roots How are Microsoft, tool vendors and development shops dealing with the downturn? Our Tech·Ed preview offers a .NET forecast.

Transcript of Headwinds - 1105 Mediapdf.1105media.com/VSMMag/2009/70023025/VSM_905DG.pdfMicrosoft Tech·Ed North...

Headwinds

MAY

20

09

Vol

ume

19

, No.

5VisualStudioMagazine.com

PLUS

Create Data-Driven Apps with Silverlight 3

Generate Code Using T4 Templates

Why Redmond Needs to Return to Its Roots

How are Microsoft, tool vendors and development shops dealing with the downturn? Our Tech·Ed preview offers a .NET forecast.

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

Project4 4/17/09 1:23 PM Page 1

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 build

charts, gauges and maps with additional vertical visualization

functionality for business intelligence (OLAP), geographic data,

financial technical analysis, and statistical studies and formulas.

Recognized for the past15 years as the innovator and industry

leader in charting components, Chart FX delivers incomparable

gallery options, aesthetics and data analysis features.

Grid FX was built specifically for Visual Studio developers to

provide a powerful design-time experience right out of the box.

Grid FX includes all Chart FX features, and uses AJAX to

provide robust, run-time functionality in ASP.net applications.

Dynamic controls for presentation aesthetics and analysis allow

easy adaptation to existing applications, and specific tailoring

to corporate brand guidelines.

PowerGadgets puts powerful IT monitoring on your desktop

and in your data sidebar. IT professionals can now create gadgets

that consume data from WMI, Exchange, SQL Server and even

the Windows Registry. PowerGadgets does not require any

development environments,servers or browsers to run real-time

gadget components such as charts, gauges and maps.

DataParts is a powerful new way to add interactive business

intelligence to SharePoint portals. With DataParts, visualizing

and analyzing data becomes remarkably easy – and code-free.

DataParts includes our complete suite of advanced lists, card

views, charts, digital panels and gauges as web parts that are

easily configured for the type of data desired in just minutes.

With the VTC – Virtual Training Center – your IT and help

desk personnel will no longer be overloaded with SharePoint

questions and training tasks. VTC is a complete program of

expertly produced, self-paced tutorial modules designed to

empower every user and maximize the value of every SharePoint

feature. VTC installs in minutes on your server, allowing instant

on-demand access for everyone in your organization.

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 FX

has risen above all others by supplying top-of-the-line data visualization tools to enterprise developers

working with diverse markets, platforms and environments. This wisdom has evolved into a vast body

of products including best-of-breed data presentation solutions, virtual training for SharePoint, and the

most powerful selection of data monitoring and analysis components. For a world of software that can

raise your work to a higher level, depend on the source that’s clearly on top.

ChooseAHigher PowerForDataVisualization

Project4 4/17/09 1:24 PM Page 2

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.

NEWRELEASE!

Professional EditionParadise #

T79 02101A02$848.99

®

programmers.com/sap

Crystal Reports 2008by SAP BusinessObjectsCrystal Reports 2008 is a powerful,dynamic, actionable reporting solution that helps you design, explore, visualize,and deliver reports via the web or embedded in enterprise applications. It enables end users to consume reportswith stunning visualizations, conduct on report business modeling, and execute decisions instantly from the report itself—reducing dependency on 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 and PDF/A export, PDF text import• Tables, headers & footers, text frames, bullets,

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

• Ready-to-use toolbars and dialog boxes

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

programmers.com/farpoint

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

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

Paradise # F02 01101A01 $936.99

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 17201A01

$455.99

Paradise # S4A 08201E02

$4,606.99

Paradise # V87L01101A01

$799.99

programmers.com/vmware

View PremierParadise #

V55 66101A01

CALLI

VMware View Premier Starter KitView Premier is an Enterprise-classDesktop and Application virtualizationsuite that enables you to take control of your desktops and applications whileproviding storage optimization. TheStarter Kit is the entry level solution that includes 10 concurrent user licensesof VMware Infrastructure Enterprise,vCenter Foundation, ThinApp, ViewComposer and View Manager. SnS is required and sold separately.

VDI Included

New Release!

Project3 3/30/09 12:50 PM Page 1

DepressingDevelopmentsThe economic downturn doesn’t offermany places to hide. Gartner predicts thatglobal IT spending this year will decline 3.8percent from 2008. How is this slowdownaffecting the .NET developer community?We checked in with developers and ISVs toget a sense of how they’re adapting asTech·Ed North America 2009 approaches.The results, which are the basis of thismonth’s cover story, were enlightening. It turns out that different sectors areexperiencing different levels of dislocation.One survey respondent in the buildingindustry says “all new development is onhold, we are working on maintenenanceonly.” But few are taking it harder thanthe auto industry.

A developer at a supplier of steeringcolumns and shifters for auto and trucking manufacturers from Michigansays, “Our departmental budgets are virtually non-existent.”

Similar tales of layoffs, cutbacks andbare maintenance-only budgets abound inthe travel, finance, energy utility and othersectors. Heck, even collection agencies arehurting. “Yes, we have a lot of incomingbusiness. But while placements are up, collections numbers are down, and wecan’t spend money for new projects,” saysthe information services director of aHouston-based collection agency.

Not everyone is cutting back.Government, military, security and areas ofhealth care remain active. Respondentsworking in the U.S. Army and Air Force saydev activity is strong, and one governmentdeveloper writes, “We’re moving forwardwith all current initiatives as planned.Funding, while potentially reduced, will justextend the time toward project completion.”

How is your dev organization weather-ing the downturn? And how is the slow-down impacting your ability to adopt majornew Microsoft technologies? E-mail me [email protected].

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 3

COV

ER

ILL

US

TR

AT

ION

BY

R

YAN

ET

TE

R

FEATURES14 Headwinds

Despite a troubled economy and falling IT budgets, Microsoft and its partners arebusy rolling out new tools and platforms. We preview some of the goings on atMicrosoft Tech·Ed North America 2009, and talk to developers and ISVs about howthey’re managing in a sluggish software market. BY MICHAEL DESMOND

26 Silverlight 3 Enables Data-Driven App DevThe latest version of Silverlight boasts a new DataForm control and enhanced support for data-driven applications, enabling developers to deliver line-of-businessapplications to any user with a Silverlight-enabled Web browser. We walk through the new capabilities in the latest beta of Silverlight 3. BY PETER VOGEL

DEPARTMENTS6 Letters to the Editor

8 DevDisastersGatekeepers of Bad Software BY ALEX PAPADIMOULIS (TheDailyWTF.com)

10 DevInsights DEVELOPER NEWS, REVIEWS, PRODUCT BRIEFSNews: Tech·Ed Preview PAGE 10Product Review: Sybase PowerDesigner Data Modeling PAGE 11Product Briefs: Test Center Standard Edition and Connect ODBC 6.0 PAGE 12

36 LANGUAGE LABC# Corner PAGE 36Covariance and contravariance are precise terms that describe which conversions aresafe on parameters and return types. Learn about new constructs to be supported in C# 4.0, and how to live with the current limitations until Visual Studio 2010 isadopted by your organization. BY BILL WAGNER

Ask Kathleen PAGE 42Learn how to create and debug templates using Microsoft’s Text TransformationTemplating Toolkit (T4) language, which is included with Visual Studio 2008. 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 }ContentsMay 2009 // Volume19 // No. 5

14Michael Desmond, Editor in Chief, Visual Studio Magazine

0509vsm_TOC_3-4.v5 4/17/09 11:16 AM Page 3

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com4

IST

OC

KP

HO

TO

.CO

M

VISUALSTUDIOMAGAZINE.COM

Online TutorialsWahlin on .NETUsing Silverlight’s WebClient Class: TheWebClient class gives you a straightfor-ward way to access distributed servicedata without having to worry about a lotof asynchronous complexities.BY DAN WAHLIN

LOCATOR+ CODE: VS0905DW1

Classic VB CornerPrisoner of Geography: When it comes toour understanding of Unicode issues, the“Born in the USA!” chant (no matter howyou feel about The Boss) can almostamount to a proclamation of cultural ignorance.BY KARL E. PETERSON

LOCATOR+ CODE: VS0905KP1

Inside VSTSAdding Events to User Controls: To fullyexploit User Controls, you need to treatthem as objects, which includes havingthem fire events. This is a step-by-stepguide.BY PETER VOGEL

LOCATOR+ CODE: VS0905PV1

REDDEVNEWS.COM

RDN Express: Avalon Take 2Developers can expect a lot of progress inWindows Presentation Foundation 4.0,which is part of the upcoming .NETFramework 4.0 beta expected this month.BY KATHLEEN RICHARDS

LOCATOR+ CODE: VS0905RD1

First Service Pack Released for SQL Server 2008Microsoft shipped SQL Server 2008Service Pack 1, which provides updates tothe relational database management system, but no new features.BY KURT MACKIE

LOCATOR+ CODE: VS0905RD2

Microsoft Q&A: How Does ‘Oslo’ Fitwith Visual Studio 2010?Microsoft Senior Product Manager KrisHorrocks talks about Redmond’s views on model-driven development and how the “Oslo” modeling platform fits into that vision.BY KATHLEEN RICHARDS

LOCATOR+ CODE: VS0905RD3

ADTMAG.COM

Linux Projects Shift to CostSaving money has replaced adding newfunctionality as a key reason for shiftingto open source, according to participants ina panel at the High Performance Linux onWall Street conference.BY JEFFREY SCHWARTZ

LOCATOR+ CODE: VS0905AD1

ASP.NET MVC Now Open SourceMicrosoft released the source code for its ASP.NET Model-View-Controller under the Open Source Initiative-recognized Ms-PL.BY JEFFREY SCHWARTZ

LOCATOR+ CODE: VS0905AD2

New Eclipse-Based Tools Reach for the CloudsAmazon, Salesforce.com and Oracle are among those that have released new tools at the annual EclipseCon conference. BY JOHN K. WATERS

LOCATOR+ CODE: VS0905AD3

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

0509vsm_TOC_3-4.v5 4/17/09 11:16 AM Page 4

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.

Come visit us at

Microsoft TechEd booth #554

to learn how to add m

aps into your

Silverlight ®

applications.

Project1 4/9/09 11:08 AM Page 1

VISUAL STUDIO MAGAZINE · May2009 · VisualStudioMagazine.com6

Each month, Andrew Brust writes the Redmond Review column for the backpage of Visual Studio Magazine. His first column since arriving from the pages ofRedmond Developer News focused on the late change of heart Microsoft hadregarding its SQL Data Services cloud-based data storage scheme. LongtimeVSM contributor Roger Jennings responds to Brust’s column in a blog posting.

Andrew Brust’s “What’s Old Is New Again” column for Visual StudioMagazine’s April 2009 issue recounts the history of Visual Basic 3.0’s adoptionof the Jet (Access) 1.1 relational database and the parallel with the SDS team’scourse reversal from the Entity-Attribute-Value data model to a full-featuredrelational database. Andrew concludes:

So Redmond listened to its customers, and the bizarre obsession with copying Amazon’s SimpleDB Web service is over. Microsoft has given us a trulysimple offering: the SQL Server technology that most Microsoft developers havebeen using for a decade and some have been using since even before my firstcolumn was published.

I couldn’t agree more.P.S. Andrew and I started writing for Visual Studio Magazine’s predecessor

about 15 years ago when it had just been re-named from BASIC Pro to VisualBasic Programmers Journal.

Roger JenningsPrincipal, OakLeaf Systems

Oakland, Calif.On the New Redesign VSM redesigned its cover and pages with the April 2009 issue. A reader shareshis thoughts.

I want you to know that I'm totally offended by April’s front cover.Having both the female sexual computer model and the evolution icon is

the last straw. Your magazine has bleak content anyway. I threw it in the trash.Evolution is nothing but a false faith in garbage science. I want to terminate mysubscription immediately.

Dennis ParksBeaverton, Ore.

Letters VisualStudioMagazine.comMay 2009 • Volume 19 • No. 5

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, Kathleen Dollard, 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

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.

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.

What’s Old IsNew Again

0509vsm_Letters_6.v4 4/17/09 11:48 AM Page 6

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

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com8

The HR department at a financial servicesfirm wanted to hire GlobalComp to build aWeb portal.

Getting approval was straight-forward: the purchaser set up a meet-ing between GlobalComp and an “inte-gration services” developer on the ITteam, and then waited a few days.

After a brief spiel from theGlobalComp sales rep, Steveopened with a softball question:“Is it secure?”

“Of course it’s secure,” therep said. “At GlobalComp we takesecurity very seriously. In fact, ourpages are delivered over SecureSocket Lay—”

“Wait a sec,” Steve cut him off, ashe played around with the Web portal. “Ithink I just broke into your admin console.”

The GlobalComp rep stumbled throughan apology. It was clear that the developershad never anticipated someone typing ' OR''=' in the password field. Steve thoughtit’d be a good idea to do a code review to seewhat else they had missed.

A Code TourBefore Steve was permitted to even talk to adeveloper at GlobalComp, they had him sign aan NDA. As an added security measure, Stevecould only review the code while the immacu-lately dressed Dave, GlobalComp’s lead devel-oper, watched him. “You’d be surprised,” Davesaid in a serious tone, “there are a lot of peo-ple who would steal our software ideas.”

Steve’s first port of call was login.asp.But it wasn’t the security snafus or theFrontPage meta-tags that caught his eye.Not only were they using Access, but theyhad come up with a rather interesting way ofcaching huge amounts (400K+) of user-spe-cific info. They used the ASP Session object:

<%set cn = Server.CreateObject(_"ADODB.Connection")

cn.Provider = _"Microsoft.Jet.OLEDB.4.0"

cn.Open "C:\inetpub\wwwroot\db.mdb"set rs = Server.CreateObject(_"ADODB.recordset")

rs.Open "SELECT * FROM Users " & _" WHERE Username = '" & _

Username & _"' AND Password = '" & _Password & "'", cn

do until rs.EOFsession("USERNAME") = rs("username")session("COMPANY") = rs("company")session("LOCATION") = rs("location")session("ADDRESS1") = rs("address1")session("ADDRESS2") = rs("address2")session("ADDRESS3") = rs("address3")session("ADDRESS4") = rs("address4")

session("HTML_BLOCK_1") = rs("html1")…180 columns later…

session("YET_ANOTHER_FIELD") = _Rs("yet_another_field")Rs.MoveNextlooprs.closecn.close%>

“I can’t help but noticethat this is in ASP,” Steve said to

Dave. “I’m curious: why not .NET?Do you have a lot of ASP libraries that

you’re reusing?”“It’s 2006,” Dave snapped back, “not

2015. Everyone knows that .NET hasn’treally taken off yet. It’s slow, difficult tocode and very buggy. Maybe in a few yearswe’ll consider it, but until then, ASP is farquicker and more powerful.”

“For optimization,” Steve commented,“wouldn’t it have made sense to go withSQL Server? This portal is meant to be usedby thousands of users across the country.Do you think Access is up to the job?”

“What’s wrong with Access?” Davedefensively questioned. “When I was atAccenture, we used it all the time.”

Steve had seen enough. “In light of thenumerous performance, security and data-integrity issues,” his review read, “we do notapprove GlobalComp’s Web portal softwarefor use in our production environments.”

It was the first time anyone in thedepartment had ever given a non-approvalfor vendor software. They felt relieved tohave successfully acted as the gatekeeperof bad software. VSM

{ 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>Gatekeepers of Bad Software

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.

Tell Us Your Tale

0509vsm_DevDisasters_8.v5 4/17/09 11:51 AM Page 8

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!

The World Leader in Imaging Development SDKs

Project3 4/15/09 12:46 PM Page 1

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com10

Tec

h-E

d

Microsoft’s Tech·Ed North America 2009 confab this month isexpected to center around Windows 7, Windows Server 2008R2, Exchange 14 and the numerous technologies that the com-pany has rolled out during the last 12 to 18 months.

Registered attendees will receive the latest versions ofWindows 7—likely the first release candidate (RC)—and WindowsServer 2008 R2. As part of an included TechNet Plus annual sub-scription, conference goers will also receive licensed copies of thetechnologies when they first become available later this year.

For developers, the annual conference will offer more thana sneak peek at Visual Studio 2010, which is close to beta 1; the last preview bits were offered in October at MicrosoftPDC2008 and expired in January. According to multiple sources,Microsoft is targeting Tech·Ed for the beta 1 release.

SQL Server “Kilamanjaro,” the upcoming business intelli-gence (BI) release that enables users to create reports usingSharePoint and Excel, will be highlighted during the keynote forthe database platforms and BI tracks, which are targeted at bothdevelopers and IT professionals.

“Usually Tech·Ed is not hugely filled with beta technologysessions, so the fact that some of these things that are a little prerelease are kind of coming out shows that they’re either closerto market or more important,” says Stephen Forte, chief strategyofficer at Telerik Inc. Forte is leading several Tech·Ed sessions,including a drill-down on SQL Server 2008 with Richard Campbell,co-host of .NET Rocks.

REALITY BYTES

Despite the anticipated releases, Tech·Ed is facing the same hur-dles that conferences in every industry have encountered duringthe recession: attendance issues. The conference will take placeat the Los Angeles Convention Center, the same venue as lastyear’s PDC. After a two week Tech·Ed in Orlando, Fla., in June2008 that separated the developer and IT tracks, Microsoft isback to a combined, one-week model. Last year’s event, whichmarked chairman Bill Gates’ last official keynote, attractedaround 5,000 developers and 10,000 IT professionals, accordingto Microsoft.

The current climate has meant some unwelcomechanges: In April, registrants were notified of the cancellationof on-site exams for Microsoft certifications, the traditionalThursday night attendee party and the popular JamSessions that occurred nightly at past Tech·Ed events.

The Server and Tools News Bytes blog on MicrosoftTechNet “recommended” the press attend the show virtuallythis year, noting that there would be limited access to

Microsoft executives and on-site facilities. The cutbacks are not a reflection on Microsoft or

Tech·Ed’s robust technical content. “Generally, I’m hearing conferences are just not being as well attended for obvious reasons this year,” says Rob Sanfilippo, research vice presidentof developer platforms at Directions on Microsoft. “Lookingacross at MIX, Tech·Ed and PDC, I definitely would rank PDC asthe first conference to attend from a developer standpoint forsomeone that’s interested in planning technology that will beused two or three years out for their organization.”

PDC2009, which is expected to focus on the release ofMicrosoft’s cloud-computing platform, Windows Azure, is scheduled for Nov. 17-20 in Los Angeles.

LOTS TO LEARN

Despite the troublesome economy, Microsoft received a recordnumber of more than 1,600 submissions for technical sessionsfrom inside and outside of the company, according to a post byBrian Marble, worldwide Tech·Ed lead. That has been whittleddown to 20 tracks, with about 440 “breakout” sessions and 200or so “hands-on” labs. The theme this year is “Potential LivesHere,” and the focus—as in years past—is on technical education,community and product evaluation.

Windows 7 is the clear headliner at Tech·Ed. TheWindows Azure Services Platform will also get some play with26 sessions, although the licensing and pricing structure—information that could definitely spur serious interest amongdecision makers—is expected to remain under wraps until laterthis year.

Tech·Ed will also be the first conference stateside to offerplenty of information for developers interested in Windows

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

</DevInsight>D E V E L O P E R N E W S

IST

OC

KP

HO

TO

.CO

M

Tech·Ed PreviewIs the Visual Studio 2010 beta finally here?

BY KATHLEEN RICHARDS

0509vsm_DevInsight_10-12.v5 4/17/09 12:12 PM Page 10

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 11

Dat

a M

odel

ing

Mobile, which will be covered in 31 sessions.Stephanie Ferguson, general manager ofbusiness experiences at Microsoft’s MobileCommunications Business, is scheduled togive what’s being described as the “kickofflaunch” of Windows Mobile 6.5 on May 11.

As in years past, Tech·Ed covers a broad swath of Microsoft’s technologies,including Office and SharePoint, service-oriented architecture and business process,virtualization, Windows Client, Web and user experience, developer practices anddeveloper tools, languages and frameworks.For developers, that means educational sessions on recent Windows, Web and richInternet application announcements such asWindows Presentation Foundation (WPF),ASP.NET MVC, JQuery, Silverlight, .NET 4.0, theupcoming “Dev 10” languages and the “Oslo”modeling platform. A new Oslo communitytechnology preview is anticipated in theTech·Ed time frame.

Rockford Lhotka, principal technologyevangelist at consulting firm MagenicTechnologies Inc., is leading a Silverlight session on building line-of-business apps.

“I think we’re all hoping that VisualStudio 2010 is going to have the designersupport for Silverlight and WPF that kind ofunlocks the door,” he says. “It’s very clearthat the future of Windows UI developmentis WPF—that’s where Microsoft is putting allof their energy—and they’re putting evenmore energy into Silverlight. Now is the timethat people really need to start looking atthem in some depth with the anticipationthat we’re going to get the tooling withVisual Studio 2010,” Lhotka adds.

Sanfilippo, who attended MIX09 inMarch, is skipping Tech·Ed this month. “I thinkTech·Ed is really between the big announce-ments this year, and also it’s really focusedmore on IT training than developerannouncements,” he explains.

Despite the economic slowdown andsome cutbacks at the event, most agreeTech·Ed still ranks among the largest opportunities to interact with Microsoft representatives and the IT community.

For the first time in the show’s 16-yearhistory, registered attendees will receiveaccess to the Global Tech·Ed Content Library,which includes Tech·Ed Europe, the MiddleEast and Africa (EMEA). Tech·Ed Europe, aone-week event for developers and IT, isNov. 9-13 at the Messe Convention Center in Berlin. DI

Kathleen Richards ([email protected]) is

executive editor of Visual Studio Magazine and

editor of RedDevNews.com.

PowerDesigner allows you to create a conceptual model using a variety of modeling notations and, from that model, generate a physical database designfor almost any RDBMS.

Sybase PowerDesigner Data ModelingEliminate “data model archeology” by analyzing your enterprise’s systems to find out where data is actually being used.

R E V I E W

BY PETER VOGEL

Sybase Inc.’s goals forPowerDesigner are nothing if notambitious: a single modeling tool fortracking data definitions everywherein an organization—and Sybasedoesn’t just mean databases when itsays data. Sybase PowerDesigner canalso model data represented in XMLschemas (including .WSDL files),process languages (BPEL andebXML), object definition languages(Visual Basic, C#, Java, IDL-CORBA)and even .XLS files, among otherchoices. In addition, PowerDesignersupports virtually every notationavailable, including the popular UMLand IDEF1X notations. Heck,PowerDesigner even supportsCODASYL, a notation that I usedwhen I started doing database design,way back in 1982.

Data modeling serves two pur-poses: generating database schemasand documenting data stores. I usedPowerDesigner to generate a SQLServer database drawn from one ofmy client’s projects. With a tool aspowerful as PowerDesigner, there’salways a danger that doing the sim-pler things will become unnecessarilycomplicated—I didn’t find that withPowerDesigner. I was able to add amodel to one of my existing VisualStudio projects and generate a data-

base shortly after installing the prod-uct (you can also create standalonePowerDesiger “modeling projects” inVisual Studio). PowerDesigner isn’tlimited to generating just databaseschemas: You can also generate BPELprocess files and nHibernate code,among other options.

The other purpose of data mod-eling is documenting data stores,which is only valuable if you can useyour models to support developers,make business and design decisionsand to analyze business problems.PowerDesigner supports creatingreports from your models in HTML,RTF, and in a proprietary format for local printing.You can also print reference documents in “card format,”which produces individual,two-column tables suitable for reference purposes. More critically,PowerDesigner lets you pick an objectand follow its links to see where thedata item is used—a powerful toolwhen someone asks you,“What wouldit cost to change this?”

Of course, the ability to followthose links is only useful if all ofyour data stores are documented in PowerDesigner. I foundPowerDesigner’s reverse engineeringfacilities to be robust and complete forthe various data stores that I testedagainst. While I tested against the

0509vsm_DevInsight_10-12.v5 4/17/09 12:12 PM Page 11

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com12

</DevInsight>D

atab

ase

Too

ls

Test Center Standard Editionand Connect ODBC 6.0LOWER COST APM

Two months after releasing an application performance manage-ment (APM) suite that ranges in price from $30,000 to $60,000,Linz, Austria-based dynaTrace Software is now offering a scaled-down version. dynaTrace Test Center Standard Edition has a good portion of the application testing features found in the core dynaTrace 3 suite, the company says. But it costs about 20 percent of the suite’s price.

That full-scale suite is designed to let developers tracetransactions across geographically distributed systems with large,scalable virtualized server clusters for business-critical applica-tions that require 24x7 uptime (for more on that release, seehttp://tinyurl.com/csvyn2).

Like the larger version, the Standard Edition comes with VisualStudio, Visual Studio Team System Test Edition and Eclipse plug-ins.It diagnoses and isolates typical Web application issues, notablydatabase performance problems and chattiness. The software alsodocuments issues for developers including SQL statements and bindvalues, and various other transaction characteristics. The softwaretakes every transaction and displays the slowest running ones orthose that are broken. When the developer clicks on a transaction,he can view the whole path with all the context. If a developersees hundreds of extra calls to a database, he can click on it andautomatically open up the source code in Visual Studio.

Although not as well known as some of its rivals, dynaTracesays it has made inroads in the U.S. market over the past year withcustomers such as Bank of America, Fidelity Investments, LinkedInand Macy’s. It has 100 customers but has seen rapid growth in recentquarters, the company says. But dynaTrace, which is backed by BainCapital and Bay Partners, is a much smaller player than market leaderCA, whose Wily Technology is used by more than 1,000 customers.

Test Center Standard EditiondynaTrace SoftwarePrice: $6,000 per developer licensewww.dynaTrace.com781-674-4000

DRIVING ODBC HARDER

Looking to give a boost to applications that rely on Microsoft’sOpen Database Connectivity (ODBC) standard, DataDirectTechnologies has updated its drivers.

The new DataDirect Connect for ODBC version 6.0 increasesthe speed at which data is loaded into an application or into adatabase, says Rob Steward, the company’s vice president of R&D.It allows for exporting of data from one database into another andperforms bulk transfers without having to use Microsoft’s batchprocessing utility.

Existing batch processes will run faster without requiringchanges to application code, he adds. Version 6.0 adds applicationfailover: “The features will allow developers to better tune theirapplications,” he explains.

In addition to Microsoft’s SQL Server, DataDirect’s ODBC driversprovide connectivity to databases from Oracle Corp., IBM Corp. (DB2and Informix) and Sybase Inc., among others. With the new release,the company has added connectivity to PostgresSQL and Greenblum.

DataDirect, a Bedford, Mass.-based subsidiary of ProgressSoftware Corp., is among a handful of companies that provideODBC drivers. Most leading database vendors offer their ownODBC drivers and there are a number of less-expensive, opensource alternatives as well. DataDirect says its drivers are aimedat ISVs and large enterprises. DI

Connect for ODBC 6.0DataDirect Technologies Price: $4,000 per single corewww.datadirect.com800-876-3101

P R O D U C T S

standard Microsoft tools (SQL Server andAccess), PowerDesigner also supportsOracle, DB2 and MySQL (again, amongother database engines).

Given its pricing and functionality,PowerDesigner is not for the faint hearted—and it’s also not for those with limited goals. If all you need is adatabase design tool for your organiza-tion’s RDBMS, PowerDesigner is far moretool than you need. But if you want to

create a repository for analyzing yourorganization’s data usage, PowerDesignerwill do the job. DI

Peter Vogel ([email protected]) is a principal

in PH&V Information Services, specializing in

ASP.NET development with expertise in SOA,

XML, database and User Interface design. He’s

written several books on application develop-

ment using Microsoft technologies and presents

at conferences around the world.

SYBASE POWERDESIGNER 15

Sybase Inc.www.sybase.com800-792-2735

Price: $2,995 to $7,495 per developerseat

Quick Facts: One-stop shopping fordata modeling and analysis using a variety of notations.

Pros: High functionality with support for all the tools that Microsoftdevelopers use.

Cons: Expensive; PowerDesigner is abig tool to handle big problems—not atool for developers just needing a data-base modeling tool.

Developers can examine code to trace transaction bottlenecksthrough the dynaTrace Visual Studio plug-in.

0509vsm_DevInsight_10-12.v5 4/17/09 12:12 PM Page 12

Project2 4/1/09 11:55 AM Page 1

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com14

ILLU

ST

RA

TIO

N B

Y R

YAN

ET

TE

R

0509vsm_F1_14-22.v6 4/17/09 12:21 PM Page 14

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 15

TECH-ED 2009 FEATURE

When the going gets tough, the tough get going. At least,

that’s the hope of most conference organizers in the software

development sector. With IT and dev budgets slashed and

most organizations hunkering down for a long downturn, it’s

no surprise that attendance at many industry events

is off sharply from two or three years ago. Still, Microsoft is

hoping to draw a crowd to Tech·Ed North America 2009 in Los

Angeles this month.

Despite tough times, developers, ISVs and Microsoft are keeping plenty busy.

BY MICHAEL DESMOND

HEADWINDS

0509vsm_F1_14-22.v6 4/17/09 12:21 PM Page 15

SURROUNDED, UP AGAINST IT, AND FALLING BEHIND. YOU NEED A TEAM SYSTEM.

Project6 4/7/09 4:11 PM Page 1

It takes a team to produce better code on faster timelines. Visual Studio® Team System 2008 makes it easier to track work items, update everyone, analyze code, and get the job done, from UX to database. Download a trial at microsoft.com/defyallchallenges/team

SURROUNDED, UP AGAINST IT, AND FALLING BEHIND. SURROUNDED, UP AGAINST IT, AND FALLING BEHIND. YOU NEED A TEAM SYSTEM.YOU NEED A TEAM SYSTEM.

Project6 4/7/09 4:12 PM Page 2

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com18

TECH-ED 2009FEATURE

Attendees certainly won’t be staying away for lack of thingsto explore at the four-day conference, which combines IT anddevelopment tracks focused on Microsoft platforms, servicesand products. On the dev side, Tech·Ed arrives as a host of strate-gic Microsoft development technologies emerge. From Azurecloud computing to Silverlight 3 Web development to the antici-pated beta of Visual Studio 2010,Tech·Ed offers a chance to catchup on the latest Microsoft-driven dev technologies.

No surprise, independent tool companies are busy as well,as they rush to fill gaps in Microsoft’s expanded dev platformsand tap powerful, new features in the latest versions of .NETFramework, Silverlight, Visual Studio and ASP.NET.

Nowhere to Hide: Developers Test Strategies in a Terrible MarketA market report by research firm Gartner Inc. provided grimcontext just six weeks ahead of the May Tech·Ed confab.

According to the March 31 report, worldwide spending on infor-mation technology was expected to fall 3.8 percent in 2009, to$3.2 trillion from $3.4 trillion. That decline, Gartner ResearchVice President Richard Gordon notes, would be worse than the2.1 percent reduction the industry weathered in 2001 during thedot-com bubble burst.

Ask Julian Bucknall how his company, .NET componentmaker Developer Express Inc. plans to get through the doureconomy, and he is refreshingly candid.

“The economy being what it is, we’ve concentrated a lot onmaking our current customers happy,” says Bucknall, the compa-ny’s chief technology officer, who notes the importance ofDeveloper Express’ subscription model. “The only way we couldencourage people to stick with us is to concentrate an awful loton stability, reliability, discoverability—making things easier andmore stable to use, and then adding more functionality when wefeel it’s necessary.”

Like many rank-and-file dev shops, Bucknall saysDeveloper Express has decided to pick its spots carefully, invest-ing in select areas and emphasizing maintenance and refinementover lavish new initiatives or product launches. It’s an approachbeing repeated all over the development sector.

“2009 is seriously quite a tough year, but I suspect for mostpeople it will be just carrying on doing what they’re doing,” saysBola Rotibi, principal analyst at research firm Macehiter Ward-Dutton (MWD). “Outside of the core areas of keeping thebusiness going, I think [new initiatives] are going to be few andfar between.”

Our survey of more than 350 .NET developers ahead ofTech·Ed bears out the cautious, go-slow approach.Asked about thebiggest challenge facing their organizations, the largest percentageof respondents singled out the economy (32 percent). The second most-cited response was the challenge of managing all thedeveloper technologies coming from Microsoft (23 percent). Noother response drew more than 8 percent of the vote.

Many dev shops report falling back into maintenancemode. “I’m in pharmaceuticals,” writes one senior analyst.“There are mergers, but with each merger come wholesale layoffs. My IT department is down to doing maintenance only,with a budget freeze in place.”

An application solutions architect with a major insurancecarrier says his group is trying to do more with less. “In thehealth-care insurance sector, we’re still actively trying to handlenew projects from the business, but with smaller dev staff, or atleast fewer subject-matter experts.”

While 32 percent of survey respondents report limiting workto maintenance, a surprising percentage (31 percent) say they continue to move forward with new platforms and technologies.“My opinion is that we should be focusing on migrating our largenumber of VB 6.0 and legacy ASP applications to help ramp someof the newer or more junior staff up with the latest Microsoft devtechnologies,” the solutions architect says.

A lot of developers are concerned about their ability toadopt and master all the new technologies Microsoft has beenrolling out. Survey respondents indicate excitement aboutinbound tooling like Visual Studio, .NET Framework 4.0 andWindows 7, yet nearly seven in 10 respondents expressed“fatigue” with the pace of Microsoft technology rollouts over the past year. Nearly one-quarter of all respondents (24 percent)categorized the fatigue as “significant.”

We polled 369 developers for theirthoughts on the .NET dev arena. Here’s what they said:

WHAT’S YOUR READ ON THE DEVELOPMENT MARKETFOR THE SECOND HALF OF 2009?

Difficult 39%Hopeful 29%Neutral 23%Terrible 4%Terrific 4%

HOW IS YOUR ORGANIZATION APPROACHING APPLICATION DEVELOPMENT?

Working on existing projects and app maintenance only 32%Moving forward to adopt new platforms and technologies 31%Embracing Agile development methodologies 13%Adopting more open source platforms and development tools 9%Investigating cloud computing options 8%Outsourcing 7%

DO YOU SENSE DEVELOPER FATIGUE DUE TO THE PACEOF MICROSOFT TECHNOLOGY INTRODUCTIONS?

Yes, some fatigue 45%No, little or no fatigue 26%Yes, significant fatigue 24%Don’t know 5%

IS YOUR ORGANIZATION SPECIFICALLY TARGETINGDEVELOPMENT FOR THE WINDOWS 7 CLIENT OS?

No 60%Yes, but it will take time 23%Yes, but only limited development 14%Yes, aggressively 3%

0509vsm_F1_14-22.v6 4/17/09 12:21 PM Page 18

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 19

“The staff is concerned about the ability to learn and applynew technology in products that have a solid base of code,”says thevice president of engineering for a telecommunications consultingfirm. “Our market problem is we need to maintain compliancewith .NET 2.0, .NET 3.5, multiple versions of SQL Server and mul-tiple operating systems.”

A Web application developer for a large construction andengineering firm says his shop is busy, but risks falling behind inthe adoption of new technologies.“Our biggest challenge is not theeconomy, but rather maintaining oursuite of Web applications (hundreds!) andat the same time keep up with the pace oftechnology,” he says. “We essentially fallfurther and further behind every year.Our most heavily used apps are classicASP, we have many .NET 1.1 apps, and asprinkling of .NET 2.0 apps. Our data-bases have been recently upgraded to SQLServer 2005,” he says.

One major .NET component makerisn’t surprised at these struggles:“Microsoft has been really aggressivewith new products and releases over thepast one to two years, and some of [our]customers are finding it difficult to keeppace with all the new technologies andare sometimes confused [about] what’sbest to use for their projects.”

Anthony Lombardo, lead evangel-ist for component maker Infragisticsand a Microsoft MVP, says developersneed to be smart to avoid getting over-whelmed. “Just keeping track of all ofthe different code names can be a chore.The main thing for developers to do isfocus on the technologies that areimportant to them.”

Slowdown StrategiesCorporate dev shops aren’t the only onesstruggling to keep pace. DeveloperExpress’ Bucknall says his company hasmade the decision to focus tightly onSilverlight for its next component launch,rather than aggressively update its suite of ASP.NET, Windows PresentationFoundation (WPF) and new SharePointcontrols. Case in point, Developer Expressis updating its Express App Framework(XAF) for Silverlight.

“What XAF does is very quickly allowyou to write business applications just bydefining a data model,” says Bucknall, not-ing that Developer Express has added grid,navigation, reporting and menu controlsto its Silverlight suite.“XAF requires a cer-tain number of controls before you cangenerate an application. So now we’ll beable to write a business app for Silverlightand WPF. Those are the kind of things

we’re going to be concentrating on with regard to Silverlight. Whatyou call the business control.”

A lot of firms are also looking at how they license and sellsoftware. Microsoft at the MIX09 conference in March demoedthe Web Platform Installer, which bundles together a completestack of Microsoft-based Web server products and technologiesand provides an easy-to-use installer interface.

MWD’s Rotibi calls the Microsoft utility “a neat little solu-tion” that portends things to come. She points to the All-Access

TECH-ED 2009 FEATURE

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

0509vsm_F1_14-22.v6 4/17/09 12:21 PM Page 19

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com20

TECH-ED 2009FEATURE

service provided by database tools vendor EmbarcaderoTechnologies Inc. as an example of how vendors can provide rich integration to reduce application cost and complexity.Subscribers are able to quickly download, license, provision anddeploy Embarcadero products from an online console. TheInstantOn feature enables access to Embarcadero tooling with-out installation.

“It’s about reducing friction and getting the integration par-ticularly strong. It’s about the different tools,” Rotibi says. “Beingable to download and manage a whole series of things in aninstant, that’s the next stage.”

At SAP AG, the company recently overhauled the licensingaround Crystal Reports, providing a simple, flat-rate license forcompanies wanting to distribute Crystal Reports functionality insoftware they intend to sell or distribute. The new approachreplaces a complicated scheme, whereby ISVs had to obtain aseparate license for each distributed instance of an applicationcontaining Crystal Reports.

“We found that there are tens of thousands of ISVs out therewho were building their own reporting because they felt it wastoo expensive to work with a company like us,” says JamesThomas, vice president of product management in the VolumeBusiness Unit at SAP. He cites rapid application cycles, anincreasing mix of software and services, and pressure from opensource competition for the switch.

More and more companies are looking hard at licensing andcompliance practices as a way to face down budget challenges andease management overhead. Jon Gillespie-Brown, chief executiveofficer at licensing services firm Nalpeiron, says ISVs are scramblingto adopt subscription models as a way to ensure constant revenueand provide a lower barrier to entry for customers.

“I think that the end user is clearly pushing very hard for amore flexible way to buy,” Gillespie-Brown says.

He adds that customers are attracted to the pay-as-you-gonature of Nalpeiron’s hosted license management and trackingfeatures. But what customers are looking for, says Gillespie-Brown, are more streamlined ways to track and secure licensedsoftware, and to provide feature-complete trial software withouthaving to support multiple code bases. “I think the perpetual[license] model is close to dead, personally.”

Touring Tech·EdFor all the sturm und drang of the current recession, it’s clearfrom talking to ISVs and dev tool companies that .NET toolsdevelopment remains an active endeavor. A lot of that has to dowith Microsoft, of course. Companies like Developer Express,Infragistics and ComponentOne LLC are constantly rushingaround behind major Microsoft platform releases, filling holes,bridging gaps and extending the reach of technologies like WPF,Silverlight, ASP.NET and SharePoint.

We invited dev tool providers to give us a heads up on theirplans for the May Tech·Ed event. Here’s what we learned:

Infragistics NetAdvantage for Web Clients: SilverlightLeading component maker Infragistics is rolling out a new spinon its NetAdvantage line of components, this one aimed at devel-opers working with Silverlight 3, which is currently in beta. TheNetAdvantage for Web Clients Silverlight toolset offers advanced

controls designed to help developers craft line-of-business appli-cations using Microsoft’s RIA platform. Included in the packageare data grid, Web tree, dialog window and other controls.www.infragistics.com

Altova MissionKit 2009Few companies know XML the way Altova does. As if to make thepoint, Altova in February began bundling its broad suite of XMLand data manipulation tools under the MissionKit banner, creatinga one-stop shop for .NET developers. At Tech-Ed, Altova plans todemo MissionKit Tool Suite version 2009, which now supportsExtensible Business Reporting Language (XBRL) data in XMLSpy,MapForce, and StyleVision. Version 2009 also lets developers workwith Health Level 7 messages in the MapForce module.www.altova.com

Resco MobileForms Toolkit 2009Resco MobileForms Toolkit 2009 bundles developer componentsand tools for applications developed for Microsoft .NET CompactFramework 3.5. The latest version adds tooling for touch interfaces,polished UI support and a trio of new app components includingtab, tooltip and toolbar controls. MobileForms Toolkit 2009 sup-ports Visual Studio 2008, 2005 and 2003.www.resco.net

The Imaging Source TX TextControl 15.0The TX Text Control family of word processing components forVisual Studio 2005 and 2008 has been updated to add support forAdobe .PDF file format export, enabling Microsoft Word and com-patible documents to be viewed and filled out in any browser.According to The Imaging Source, completed forms can beprocessed server-side and then printed or saved as PDF documents.Improved support for columns and structured numbered lists hasbeen added. The Imaging Source is also distributing TX TextControl RapidSpell .NET, a spell check add-on for TX Text Controlcurrently supporting English and German dictionaries, with addi-tional languages and specialist dictionaries expected.www.textcontrol.com

PureCM 2009-1Source control management (SCM) toolmaker PureCM.com hasa new version of its eponymous product, PureCM 2009-1, thataims to enable parallel development for cash-strapped organiza-tions. With a newly streamlined interface and supporting agilemethodologies, PureCM is available for Windows, Linux andMac OS environments and integrates with the Visual Studio andEclipse IDEs. The new version adds real-time tracking and guid-ance for managing merged changes. PureCM says its tooling canscale up to thousands of end users and manage terabytes ofdata—enough to handle enterprise-scale development.www.purecm.com

REALBasic 2009 Release 1 and REAL StudioSure, Silverlight 3 promises to let you take your mad VisualBasic.NET skills cross platform. But open source toolmakerREAL Software offers another option—a cross-platform tool andversion of the Basic programming language (called, you guessedit, REALbasic) that lets developers work on—and create applica-

0509vsm_F1_14-22.v6 4/17/09 12:21 PM Page 20

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 21

TECH-ED 2009 FEATURE

tions for—Windows, Linux and Mac OS. REALbasic 2009Release 1 adds ease-of-use tweaks like a Quickstart window tohelp attract new users, as well as a host of improvementsdesigned to improve reliability.

A more robust version of the tooling released in April, calledREAL Studio, targets full-time developers and adds features like aProfiler for optimizing performance and scripted build automation.www.realsoftware.com

Nevron .NET Vision Q3 2008.NET component maker Ne v ronSoftware boasts a large collection ofchart, diagram and UI controls forWindows Forms and ASP.NET (includ-ing AJAX) application development. Allthree component families are currentlyavailable as part of the company’s all-in-one Nevron .NET Vision Q3 2008 com-ponent suite, which may see a majorupgrade by the time this issue reachesyour hands. The new package, reportedlydue out at the end of April, is set to intro-duce new charts, gauge, diagram andmapping features. .NET Vision comes intwo editions, Pro and Enterprise.www.nevron.com

Telerik WebUI StudioTelerik specializes in making UI controlsfor a wide range of Microsoft and .NETplatforms, including ASP.NET AJAX,Silverlight, WinForms and WPF. Thecompany recently announced that itsRadControls for ASP.NET AJAX productfully supports the open source Monoruntime environment for enabling .NETapplications on Linux and Mac OS plat-forms. Now Telerik adds WebUI TestStudio to its RadControls for ASP.NETAJAX. The automated testing moduleuses the ArtofTest Automation DesignCanvas and WebAi i Automat ionFramework (reviewed in the April issueof Visual Studio Magazine) to let devel-opers create and run tests across InternetExplorer and Firefox browser platforms.Support for Safari and Google Chromebrowsers is expected soon, and Teleriksays Silverlight support will be added inthe next release. WebUI Test Studio inte-grates with Visual Studio Professionaland Visual Studio Team System.www.telerik.com

Nalpeiron Licensing Service

Tough times demand tough choiceswhen it comes to paying for software andservices. Licensing solutions firm

Nalpeiron aims to help ISVs streamline operations and bettercommunicate with potential customers, with its updated, hostedsuite of licensing services. New to Nalpeiron’s offering is theTrialMaximizer feature for presenting e-mail campaigns andHTML advertisements to users using a firm’s product under atrial license. The OverdraftTracker module promises to give ISVsa glimpse into hidden customer demand. ISVs can flexibly con-

0509vsm_F1_14-22.v6 4/17/09 12:21 PM Page 21

VISUAL STUDIO MAGAZINE · May 2009 · www.visualstudiomagazine.com22

figure their software so that locked feature and capabilities can beactivated by users, giving the ISV the ability to market against theextended demand.www.nalpeiron.com

VNI pyIMSL StudioAccording to the old saw, there are lies, damned lies and statistics.Visual Numerics Inc. aims to help developers remove statisticsfrom that troubling equation, by providing a numerical analysisapplication development environment that developers can use toleverage mathematics and statistics to prototype models in theirproduction applications. Released in April, PyIMSL Studio “closesthe prototype to production gap by providing modelers andimplementation teams with a common set of tested and support-ed high-quality development tools, as well as the same underlyingnumerical algorithms,” the company said in a statement. PyIMSLStudio helps developers turn prototypes into production applica-tions quickly, while reducing risk, cost and complexity.www.vni.com

ComponentOne XapOptimizerMicrosoft has been banging the Silverlight drum for what seemslike years now, and we can expect to hear plenty about the line-of-business savvy Silverlight 3 at Tech·Ed. ComponentOne is helpingwith the drum beating with a show promotion around the commu-nity technology preview release last month of ComponentOneXapOptimizer. A standalone utility that processes Silverlight appli-cation .XAP files, XapOptimizer generates optimized Silverlightapplication files that are 30 percent to 70 percent smaller in sizethan the original .XAP files. XapOptimizer integrates into the buildprocess in Visual Studio and includes the ability to obfuscateSilverlight code.www.componentone.com

PreEmptive Solutions Dotfuscator Micro Developer EditionThe Dotfuscator product has for years helped dev shops protecttheir distributed .NET code from prying eyes—the communityedition of Dotfuscator baked into Visual Studio is currently onmore than 6 million desktops. More recently, PreEmptive has gotten into the business of helping developers inject analytics andlifecycle management tracking capabilities into their apps, allowingthem to track the status and usage of .NET apps among customers.So what’s on tap for Tech·Ed? A new version of Dotfuscator formobile developers called Dotfuscator Micro Developer Edition(MDE), which will ship at the show. The new software will integratewith Visual Studio and provide injected tamper detection/defense,application expiry and feature-tracking support.www.preemptive.com

Noemax WCF-Extensions Version 4

Windows Communication Foundation (WCF) has emerged asa powerful and attractive target for developers seeking to

establish rich interaction among applications, data and compo-nents. A component maker specializing in WCF controls,Noemax Technologies in April released WCF-Xtensions version4, a major update that, in the words of the company,“expands thereach of WCF-Xtensions from .NET and .NET CompactFramework to Silverlight and Azure.”WCF-Xtensions promise tospeed communication and reduce bandwidth consumption ofWCF services and clients. The components can bind quickly tocode and can be applied to a variety of projects based on SOAP,REST Web services or Java.www.noemax.com

JNBridge WPF Updates As the company’s name implies, JNBridge offers products thathelp bridge the gap between Java and .NET components andapplications. JNBridge tools and adapters help speed and simplifycross-platform interoperability by providing adapters that presentrich Java and .NET interfaces. At Tech·Ed, JNBridge will be show-ing new updates to the JNBridge Java & .NET interoperabilitytool that address WPF.www.jnbridge.com

Atalasoft Vizit SPIn a struggling economy, one of the few bright spots in .NETdevelopment has been in the area of SharePoint application andWeb Part development. Atalasoft VizitSP is a SharePoint imageviewing module that lets organizations provide rich imageviewing and browsing capabilities on any SharePoint deploy-ment. For more robust development, the DotImage 7.0 .NETimaging toolkit offers imaging controls for ASP.NET andWindows Forms application development. DotImage is avail-able in 32-bit and 64-bit versions and supports Visual Studio2003 and later.www.atalasoft.com

NCover 3.0NCover 3.0 is a code coverage analysis toolset for .NET that targets automated build and test environments with improvedperformance, profiling and reporting capabilities. The toolingconsists of an NCover Explorer UI for developers, a build systemconsole for the build developer and a reporting module aimed at project managers. Often employed in Agile and test-drivendevelopment environments, code coverage analysis allows devel-opers to monitor what percentage of their source code is actuallytouched by unit tests by measuring how many times a line ofcode is executed, among other metrics. NCover 3.0 includes 16new reports and a “record trends” feature that can be used toautomatically create HTML reports.www.ncover.com VSM

Michael Desmond ([email protected]) is editor in chief of

Visual Studio Magazine.

TECH-ED 2009FEATURE

“The economy being what it is, we’ve concentrated a lot on makingour current customers happy. Making things easier and more stable to use, and then adding more functionality when we feel it’snecessary.” Julian Bucknall, Chief Technology Officer, Developer Express Inc.

0509vsm_F1_14-22.v6 4/17/09 12:21 PM Page 22

For maximum efficiency, follow our

three profiling tips outlined below.

1. Profile your .NET codeA code profiler is an essential

tool to have in your development

toolkit. Although manual logging

can sometimes help, it is often

impossible to fi nd performance

bottlenecks without a code profi ler.

A profiling tool takes the guesswork

out of performance analysis and

drastically reduces the amount of

time taken to find problem code.

2. Quickly locate yourperformance bottleneckRun ANTS Profiler Pro to obtain

detailed quantitative data that will

help you identify ineffi cient resource

usage. ANTS Profiler gives you hit

count and line-level timings, so you

can quickly identify the specifi c

lines of code which are affecting the

performance of your application.

No time wasting. No guessing.

Use real data instead!

3. Optimize effi cientlyNow that you know exactly where

to focus your performance-boosting

work, you can start optimizing your

code effectively. Optimize your code

only where it needs to be improved,

and don't try to make unnecessary

changes that will not solve your

performance problem.

How to boost the performance of your.NET applications with ANTS Profiler™Performance is crucial, so here are some tips to make sure

that your applications run effi ciently.

Download your 14-day, fully functionalfree trial from www.red-gate.com

ANTS Profiler shows you line-level timings, so you can drill down to the specific lines of code responsible for performance ineffi ciencies.

Select a region on the timeline and get the performance data just for that region.

"We were able to improveperformance in parts of

the application up to 10 times,and our customer noticed theresults. A powerful, instantlyunderstandable profi ler.Highly recommended."Dan Ports Lead Developer, Intrigma Inc

"ANTS Profi ler took usstraight to the specifi c areasof our code which were thecause of our performanceissues."Terry Phillips Sr. Developer,

Harley-Davidson Dealer Systems

Project2 2/11/09 11:06 AM Page 1

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

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

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com26

SILVERLIGHT HOW-TO

Silverlight 3 EnablesData-Driven App DevThe new DataForm control and enhanced support for data-driven applications make it possible for developers to deliver line-of-business applications to any user with aSilverlight-enabled Web browser. BY PETER VOGEL

0509vsm_HowTo22-29.v9 4/17/09 12:30 PM Page 26

As announced in March at the MIX09 conference in LasVegas, Silverlight 3 adds a host of data-oriented features that go along way toward providing critical support for LOB develop-ment. I’ll show you how to build a Silverlight 3 client that access-es a Web service to retrieve and update data. My initial versionwill be a form that displays a single entity. But by leveraging thenew data binding and validation features in Silverlight 3, I’llillustrate how I can migrate my solution to a full-featured master-detail page in just a few minutes.

If you want to try out the new features in Silverlight 3 your-self, you can download the beta from http://tinyurl.com/dcs3fj.There are two caveats that apply. First: Don’t install the beta on acomputer where you want to continue creating Silverlight 2applications—installing the beta converts Visual Studio to aSilverlight 3 development tool. Second: This is still a beta releaseand no “go-live” license is available. Any applications you developat this point aren’t supported by Microsoft.

A Sample ApplicationOK, enough warnings. For this article, I created asimple Silverlight application that interacts with a Web service on my server. The application pulls down a collection of objects representingCustomers entities in the Northwind Databaseand displays them in a DataForm .

To create this application yourself, afterinstalling the Silverlight 3 beta package, select File |New Project in Visual Studio and choose Silverlightunder the language of your choice (I chose VisualBasic). From the available Templates, selectSilverlight Application, enter a name for the project(I used DataDrivenSL) and click the OK button. Inthe New Silverlight Application dialog that appears,change the project type to ASP.NET Web Site beforeclicking OK. I got the solution you see in Figure 1: anASP.NET Web Site and a Silverlight app.

In the Web site, I added a service with twomethods: one that returns Customer objects(GetCustomers) and one that, when passed a sin-gle Customer object, updates the database withthe values on the object (UpdateCustomer). Imade the .ASPX page my start page. In theSilverlight app, I knocked together a simple userinterface in the MainPage.xaml file, using a Buttonand the new DataForm control inside a StackPanel:

<Grid x:Name="LayoutRoot"Background="White">

<Button Name="Get" Content="Get Customer Data"Click="ButtonGet_Click"></Button>

<StackPanel Canvas.Left="10"><dataControls:DataForm></dataControls:DataForm>

</StackPanel></Grid>

In the code file for MainPage.XAML, to retrieve the Customerentity objects from my Web service, I created an EndPoint objectfor my service’s URL, a variable to hold a reference to my serviceand a BasicHttpBinding object. In the Click event for the Button,I used those objects to retrieve a collection of Customer entitiesby calling the GetCustomers method on my service:

Private WithEvents nwd As _

While Silverlight 1 and 2 concentrated on helping developers deliver rich Internetapplications (RIAs), coders building line-of-business (LOB) applications had little tocheer about. The limited support for data binding and data validation complicatedbasic data management tasks in LOB applications. That’s about to change.

SILVERLIGHT HOW-TO

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 27

FIGURE 1. The Web site in a Silverlight solution has an HTML page and an.ASPX page, both of which host the Silverlight application that’s part of thesame solution.

IST

OC

KP

HO

TO

.CO

M

0509vsm_HowTo22-29.v9 4/17/09 12:30 PM Page 27

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com28

NorthwindData.NorthwindDataSoapClientDim bind As New System.ServiceModel.BasicHttpBindingDim ep As New System.ServiceModel.EndpointAddress( _…URL for Web Service…)Private Sub ButtonGet_Click( _

ByVal sender As System.Object, _ ByVal e As System.Windows.RoutedEventArgs)nwd = New NorthwindData.NorthwindDataSoapClient( _bind, ep)nwd.GetCustomersAsync()

End Sub

Binding to Local ObjectsIn order to take full advantage of Silverlight’s new features, youneed an object in your Silverlight application that you can deco-rate with data-related Attributes. To support that, I created aLocalCustomer object that duplicated the properties from theCustomer object I want to display in my user interface. For thisexample, I defined just three properties: CustomerId,ContactName, CompanyName. The start of the class, with theCompanyName property, looks like this:

Public Class LocalCustomerPrivate _CompanyName As StringPrivate _CustomerId As StringPrivate _ContactName As StringPublic Property CompanyName() As String

GetReturn _CompanyName

End GetSet(ByVal value As String)

_CompanyName = valueEnd Set

End Property

In order to handle the conversion from the Customer object(returned from my service) to the LocalCustomer object (used inmy Silverlight project), I would normally create a conversion class.Alas, the necessary Attribute for conversion classes isn’t yet sup-ported for Silverlight 3. Instead, I added code to the event that firesafter the service returns the Customer objects. That code creates aLocalCustomer object for each Customer object and attaches it toan ObservableCollection. Once the collection is built, I used theDataForm’s CurrentItem property to have it display the first entityin the collection:

Private custs As New System.Collections.ObjectModel. _ObservableCollection(Of LocalCustomer)

Private Sub nwd_GetCustomersCompleted( _ByVal sender As Object, ByVal e As _NorthwindData.GetCustomersCompletedEventArgs) _Handles nwd.GetCustomersCompletedDim lc As LocalCustomerFor Each cust As NorthwindData.Customer In e.Result

lc = New LocalCustomerlc.CompanyName = cust.CompanyNamelc.CustomerId = cust.CustomerIdlc.ContactName = cust.ContactNamecusts.Add(lc)

Next

SILVERLIGHT HOW-TO

.NET RIA ServicesWhen the first Silverlight community technology preview launched to much fanfare in December 2006, it carried with it a lot of promise. Despite being a somewhat limited Web media playback platform,Silverlight grabbed the attention of .NET developerskeen on moving their application logic over the network to diverse client platforms.

Easing DevelopmentWith Silverlight 3, Microsoft seems determined to winover those business developers for good.

As part of the current Silverlight 3 beta, Microsofthas released .NET RIA Services, a framework that pullstogether elements of ASP.NET and Silverlight to easedevelopment of data-centric RIA applications. The RIAServices pattern lets developers write application logicto run on the mid-tier that, in a Microsoft statement,“controls access to data for queries, changes and cus-tom operations.”

Bob Baker, a Microsoft MVP and president ofMicroApplications Inc., has been working in theSilverlight 3 early adopter program. He says .NET RIAServices will change the face of Silverlight development.

“This release will approach application develop-ment ease for quick line-of-business apps that rivalswhat we used to be able to do with Microsoft Access—before macro security and digital signatures got inthe way,” he writes in an e-mail exchange. He addsthat .NET RIA Services promises to eliminate what hecalls “that dual, object class library thing we’ve beendoing for a year or so.”

Adding Critical CapabilitiesThe new framework integrates client-side Silverlightcomponents with the ASP.NET mid-tier to add criticalcapabilities for business applications, including datavalidation, authentication and roles. Brad Abrams,product unit manager of the Application Frameworkteam at Microsoft, says RIA .NET Services grew out ofthe work Microsoft did on LINQ.

“With RIA Services we’re extending this patternby offering a prescriptive model for exposing yourdomain logic over LINQ,” Abrams writes. ”We think ofdomain logic as that part of your application that is veryspecific to your domain—that is the particular businessproblem you are solving. By following this pattern weare able to provide a number of features that help youfocus on your domain logic rather than the plumbing inyour code.”

At press time, Microsoft .NET RIA Services was in aMarch ’09 Preview. It can be downloaded for free fromhttp://tinyurl.com/cl7z7p.

—Michael Desmond

0509vsm_HowTo22-29.v9 4/17/09 12:30 PM Page 28

MyDataForm.CurrentItem = custs(0)End Sub

To make the whole collection available to the DataForm, I first cre-ate a property in MainPage that returns the ObservableCollectionof LocalCustomers. Then in MainPage’s Loaded event, I set theDataContext to the XAML’s class:

Public ReadOnly Property Customers() As _System.Collections.ObjectModel. _ObservableCollection(Of LocalCustomer)Get

If custs IsNot Nothing ThenReturn custs

ElseReturn Nothing

End IfEnd Get

End PropertyPrivate Sub MainPage_Loaded(ByVal sender As Object, _

ByVal e As System.Windows.RoutedEventArgs) _Handles Me.Loaded

nwd = New NorthwindData.NorthwindDataSoapClient( _bind, ep)

nwd.GetCustomersAsync()Me.DataContext = Me

End Sub

With those changes in place, in the .XAML file, I can bind theDataForm to the collection returned by my new property usingthe DataForm’s ItemsSource attribute:

<dataControls:DataForm ItemsSource="{Binding Customers}"Name="MyDataForm">

The solution is very basic at this stage and doesn’t, for instance,support validating the data or calling the method on the serv-ice that handles updates. Silverlight 3 provides two ways toextend this basic solution to include those activities: extendingthe DataForm and extending the local object.

Extending the DataFormYou can alter the DataForm’s behavior either by setting propertiesfrom code or, as I’ll do here, by declaratively adding attributes to theDataForm’s element. For instance, by default, the DataForm initial-ly shows each Customer in display mode. If you set the DataForm’sAutoEdit property to True, the form will automatically display eachentity in edit mode when the user moves to it. AutoCommit, on theother hand, is True by default, allowing the user to save changes justby viewing the next entity in the collection. If you would prefer theuser to explicitly click the auto-generated Save button to commitchanges, you just need to set the AutoCommit attribute to false.

You can also control what activities the user can perform withthe DataForm. The CanUserDeleteItems and CanUserAddItemsattributes allow you off turn off some of the CRUD activities sup-

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 29

SILVERLIGHT HOW-TO

X X XX X

0509vsm_HowTo22-29.v9 4/17/09 12:30 PM Page 29

30

ported by the DataForm. Extending the DataForm with theseoptions would result in a tag that looks like this:

<dataControls:DataForm ItemsSource="{Binding Customers}"Name="MyDataForm" AutoCommit="False" AutoEdit="True"CanUserDeleteItems="False">

The DataForm is a templated control, with separateDataTemplates for inserting, displaying, and updating data. Bydefault, the DataForm adds a control to every template for everyproperty on the entity. Setting the DataForm’s AutoGenerateFieldsattribute to False suppresses that behavior, allowing you to designyour own layouts for the templates. The DataForm also fires amultitude of events both before and after critical activities (such aswhen records are added or during validation, for example), allow-ing you to add code to validate data or control updates.

You’ll have some design decisions to make, though. Many ofthe items that you can control by extending the DataForm can alsobe controlled by extending the local object. In many cases, the bestpractice is to use the features of the local object to control data-related activities and limit your DataForm changes to controllingworkflow. By extending the local object, your data-related changescan “follow the object” to whatever control is handling updates.

Extending the Local ObjectFor LOB developers, the real power in Silverlight’s data enhance-ments is the ability to extend the local object. If, for instance, youwant to take command of changes being made to the object, you canhave the local object’s class implement the IEditableObject interface:

Public Class LocalCustomerImplements System.ComponentModel.IEditableObject

Implementing this interface adds three methods to your objectthat are fired when your object is placed in edit mode(BeginEdit) and when it leaves edit mode (EndEdit andCancelEdit). For instance, rather than use some event in theDataForm to perform updates, I can use the EndEdit method inthe LocalObject to persist my changes back to the database. Thisexample converts my LocalCustomer back to aCustomer object and passes it to theUpdateCustomer method on my service to haveany changes saved to the database:

Public Sub EndEdit()_cust = CustomerConverter.ConvertBack(Me)nwd.UpdateCustomerAsync(_cust)

End Sub

While I used code to give the local object the abilityto update itself, I can implement many of my data

validation activities declaratively, by decorating the local object’sproperties.

For instance, on the CustomerId property, I want to pre-vent the property from being updated so I can use the BindableAttribute to specify that the property only supports one-waydatabinding (the default is two-way). I can also use the DisplayAttribute to control the order that the fields appear on thepage, specify the text for the field’s label, and provide adescriptive ToolTip. I can also use the Required Attribute tospecify that the property must be provided with a value andwhat error message to display if it’s omitted. With all of theseAttributes in place, the property looks like this:

<System.ComponentModel.Bindable(True, _ComponentModel.BindingDirection.OneWay)> _

<System.ComponentModel.DataAnnotations.Display( _Name:="Id", Order:=0, Description:= _"Five character customer identifier")> _

<System.ComponentModel.DataAnnotations.Required( _Errormessage:="Customer Id is required")> _

Public Property CustomerId() As String

The DataForm will take all of these decorations into accountwhen working with the property. More importantly, if I changemy form and tie the local object to a different user interface con-trol, these decorations will be used by that control also—they“follow the object” to whatever control the property is used with.

The validation DataAnnotations like Required are useful,but they only handle basic validation tasks. For more extensivevalidation, you need to write code. You can put the code in theproperty itself. To communicate error conditions back to theSilverlight user interface, you just need to throw an exception,as this version of the ContactName does:

Public Property ContactName() As StringGet

Return _ContactNameEnd GetSet(ByVal value As String)

If value.Length < 5 Then

SILVERLIGHT HOW-TO

FIGURE 2. When a local object throws an exception the associated messageis automatically displayed at the bottom of the page and inside the DataForm.

While Silverlight 3 provides significant improvements needed by line-of-business applications,

it’s not a complete solution.

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com

0509vsm_HowTo22-29.v9 4/17/09 12:30 PM Page 30

Throw New Exception( _"Contact name must be"+ _"at least 5 characters long")

End If_ContactName = value

End SetEnd Property

The resulting error is automatically displayed in the user inter-face regardless of which control is bound to the object (see Figure2, opposite page).

You can also consolidate your validation code into a separate class and associate it either with the local object or with individual properties on the local object. This exampleattaches the ValidateCompanyName method on a class called CompanyValidator to the CompanyName property on mylocal object:

<System.ComponentModel.DataAnnotations.CustomValidation( _GetType(CompanyValidator), "ValidateCompanyName", _

ErrorMessage:="Invalid company name")> _Public Property CompanyName() As String

The related validator class with the ValidateCompanyNamemethod would look like this:

Public Class CompanyValidatorPublic Shared Function ValidateCompanyName( _

ByVal Name As String) As BooleanDim ValidCName As Boolean…CompanyName validation code…Return ValidCName

End FunctionEnd Class

Creating a Master-Detail PageThe real power in modifying the local objectbecomes apparent when I convert my originaldesign to a master-detail page (Figure 3). Thechanges required are minimal. I add a DataGridto my page and bind its ItemsSource attribute tothe property that returns my collection ofLocalCustomer objects. I then bind myDataForm’s CurrentItem property to theSelectedItem property of the DataGrid (andremove the DataForm’s binding through theItemsSource attribute). The resulting XAML formy master-detail page looks like this:

<data:DataGrid ItemsSource="{BindingCustomers}"

Name="MyDataGrid"></data:DataGrid><dataControls:DataForm Name="MyDataForm"

CurrentItem="{Binding SelectedItem,ElementName=MyDataGrid}"></dataControls:DataForm>

In real life, I would use templates in the DataGridto have the grid display fewer properties than the

DataForm. But this is where the changes that I’ve made to theLocalCustomer class pay off: Because my data-related code andannotations are tied to my LocalCustomer class, I can turn onediting in the DataGrid, confident that my data managementcode will follow the object to the DataGrid.

While Silverlight 3 provides significant improvements neededto craft LOB applications, it is not a complete solution. A completesolution would provide, for instance, better control over how manyobjects are returned to the client and the ability to attach Attributesto the data transfer objects created at the server to eliminate theneed to convert to a local object in the Silverlight client. That, how-ever, goes beyond Silverlight and into the domain of .NET RIAServices, which integrates Silverlight with the server-side capabili-ties of ASP.NET (see “RIA .NET Services,” p. 28, for more about theframework released with the Silverlight 3 beta).

But, while you’re waiting for .NET RIA Services,Silverlight 3 gives you the ability to create true data-driven,line-of-business applications. And all your user needs to accessyour application is a Web browser. 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

VS0905PV Read this article and download the associated code.

SILVERLIGHT HOW-TO

FIGURE 3. In this master-detail page, as the user selects a new item in thegrid at the top of the page, the item is displayed in the DataForm.

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 31

0509vsm_HowTo22-29.v9 4/17/09 12:30 PM Page 31

0905_VSL_LV_vsm_Adr3.indd Sec1:3 4/8/09 4:53:16 PM

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 vslive.com/v9m to view

the complete agenda and register.

Take advantage of $99 room rates at the Venetian, and

get a $50 Venetian gaming credit*! Be sure to use

Priority Code NQ9V04

Takeadvantage of our $99hotel room

rate

0905_VSL_LV_vsm_Adr3.indd Sec1:2 4/8/09 4:53:14 PM

Project2 4/9/09 11:19 AM Page 1

0905_VSL_LV_vsm_Adr3.indd Sec1:4 4/8/09 4:53:18 PM

Register today at vslive.com/v9mUse priority code NQ9V04

Plus, we’ve just added Problem Solving With The Pros, to provide you dedicated time

with your favorite speakers to get essential technical advice that will save you cycles

and improve your job performance.

And stick around for the Post-Conference Workshops on Thursday, June 11th where

you can soak up A Day of Windows Azure, SQL Server 2008 for Developers, or Build

Distributed Apps in .Net 3.5 SP1.

Billy Hollis with a Deep Dive on the WPF/Silverlight Control Set

Not only is he an author and software developer, Billy is the Regional Director of

Developer Relations in Nashville for Microsoft, and runs a consulting company

focusing on Microsoft .NET.

Rockford Lhotka on Achieving Balance

Rockford is Principal Technology Evangelist for Magenic Technologies as well as

a Microsoft Regional Director, MVP, well-known author and magazine contributing

editor. Rockford speaks regularly at major conferences worldwide.

Brian Randell on Customizing Team System Projects

For over 20 years, Brian has been building software solutions and educating his

fellow developers. A senior consultant with MCW Technologies, Brian spends his time

helping people get the most out of their software.

Jason Bock on Writing Better Code: Using Visual Studio to Improve Your Code Base

Jason is a Principal Consultant for Magenic, Microsoft MVP (C#), and the author

of “Applied .NET Attributes”, “CIL Programming: Under the Hood of .NET”, “.NET

Security”, and “Visual Basic 6 Win32 API Tutorial”.

Philip Japiske on Advanced Test Driven Development

As a Principal Consultant for Pinnacle Solutions Group, Phil is a practicing .Net

Application Architect, Developer, Trainer and currently holds certifi cations as an

MCSD, MCSD.Net, MCDBA, and a ScrumMaster.

Here’s just a few of the great topics and speakers you’ll find at VSLive! Las Vegas this year:

0905_VSL_LV_vsm_Adr3.indd Sec1:3 4/8/09 4:53:16 PM

1no

11

s

0905_VSL_LV_vsm_Adr3.indd Sec1:2 4/8/09 4:53:14 PM

Project2 4/9/09 11:20 AM Page 2

0905_VSL_LV_vsm_Adr3.indd Sec1:5 4/8/09 4:56:47 PM

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

Post event workshop on June 11

Conference Day 1 • Monday, June 8KEYNOTE: Building Amazing Business Centric Applications with Microsoft Silverlight 3

Brad Abrams Product Unit Manager of the Application Framework Team, Microsoft Corporation

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: TFS 2010

.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 10Oslo Azure TFS

VW1 • Introduction to OSLO - Jon Flanders VW2 • Windows Azure: A New Era of Cloud

Computing - Aaron Skonnard

VW3 • 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 • Supporting Scrum with VSTS 2008

- David Starr

GS • Software as a Service with WPF: A Case Study - Billy Hollis

Lunch

VW7 • Building Textual DSLs with Oslo

- Mark Michaelis

VW8 • How to Work with Data in the Cloud:

Azure Table Storage 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 • Agile Test Management in VSTS 2008

- David Starr

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

- Leonard Lobel

VPC3 • 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.

0905_VSL_LV_vsm_Adr3.indd Sec1:4 4/8/09 4:53:18 PM

Project2 4/9/09 11:32 AM Page 3

1no

11

0905_VSL_LV_vsm_Adr3.indd Sec1:4 4/8/09 4:53:18 PM

Make the most of your time with us and add these to your schedule!

Register today at vslive.com/v9m Use priority code NQ9V04

VSLive! Welcome Reception Monday, June 8, 5:45 p.m.Open to all conference attendees and is your chance to connect with peers, presenters, and the

VSLive! team in a relaxed, informal setting. Come meet your old friends and make some new ones.

Problem Solving With The ProsProviding dedicated time with your favorite speakers to get essential technical advice that will

save you cycles and improve your job performance.

Birds-of-a-Feather Luncheon Tuesday, June 9, 12:15 p.m. – 1:30 p.m.Sit down and brainstorm with fellow attendees and speakers working on similar projects.

Topics include:

• ASP.NET Ajax & jQuery

• ASP.NET MVC Framework

• Silverlight

• SQL Server 2008

• Team System

• Windows Presentation Foundation

• LINQ, Entity Framework, ADO.NET Data Services

• WCF & WF

• .Net 4.0/VB 10/C# 4.0

• Cloud Computing (Windows Azure & Live Mesh)

• Parallel & Concurrent Programming

What are you waiting for? We’ve even got Special Room Rates at the Venetian for VSLive! RegistrantsOnly $99/night!

Be among the first 200 to register for VSLive! Las Vegas and book two nights or more at the Venetian, and receive a $50 Venetian Gaming Credit*!

$99 Rooms at the Venetian

$50 in Venetian Gaming Credit

0905_VSL_LV_vsm_Adr3.indd Sec1:5 4/8/09 4:56:47 PM

Project2 4/9/09 11:31 AM Page 4

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com36

Generic Covariance andContravariance in C# 4.0Covariance and contravariance are precise terms thatdescribe which conversions are safe on parameters andreturn types. Learn practical definitions for those terms,what new constructs will be supported in C# 4.0 andhow to live with the current limitations until VisualStudio 2010 is adopted by your organization.BY BILL WAGNER

In this month's installment of C# Corner, we look at one of thenew features in C# 4.0, the next version of C# that will be delivered in Visual Studio (VS) 2010. Looking ahead tospecific features in C# 4.0 can help you plan how to takeadvantage of the new capabilities in your coding efforts. Itcan also help you understand problems that are occurring inyour programs today that the next version of C# may be ableto resolve. Ultimately, the exercise will help you build a busi-ness case for adopting C# 4.0 based on existing knowledge ofhow it can help you.

This month I’ll examine covariance, contravariance andhow the C# language will be addressing those features with ver-sion 4.0 in VS 2010.

Invariance, Covariance and Contravariance ExplainedBefore we go further, let’s examine what invariant, covariant,and contravariant parameters and return types mean. Youalmost certainly are familiar with the terms, even if you don’thave a grasp of the formal definitions.

A return value or parameter is invariant if you must usethe exact match of the formal type name. A parameter is covari-ant if you can use a more derived type as a substitute for the for-mal parameter type. A return value is contravariant if you canassign the return type to a variable of a less derived type thanthe formal parameter.

In most cases, C# supports covariant parameters and con-travariant return types. That’s consistent with almost every otherobject-oriented language. In fact, polymorphism is usually built

around the concepts of covariance and contravariance. Youintuitively know that you can pass a derived class object to anymethod expecting a base class object. You intuitively know thatyou can pass a derived object to any method expecting a baseobject. After all, the derived object is also an instance of the baseobject. You instinctively know that you can store the result of amethod in a variable of a less-derived object type than the for-mal method return type.

For example, you expect this to compile:

public static void PrintOutput(object thing){

if (thing != null)Console.WriteLine(thing);

}// elsewhere:PrintOutput(5);PrintOutput(“This is a string”);

This works because parameter types are covariant in C#.Similarly, you can store the result of any method in a variable oftype object, because return types in C# are contravariant:

object value = SomeMethod();

If you’ve done any work with C# or Visual Basic.NET since.NET was first released, all this is familiar ground. However, therules change as you begin to look at any type that represents acollection of objects. In too many ways, what you intuitivelythink should work just doesn’t. As you dive deeper, you mayfind that what you believe is a bug is actually the language spec-ification. Now it’s time to explain why collections work differ-ently, and what’s changing in the future.

Object-Based CollectionsThe .NET 1.x collections (ArrayList, HashTable, Queue and soon) could be treated as covariant. Unfortunately, they’re notsafely covariant. In fact, they’re invariant. However, becausethey store references to System.Object, they appear to be

Y O U R C O D E S O U R C E</Language Lab>IN THIS SECTION: C# · 36 // Ask Kathleen · 42 //////////////////////////

Cov

aria

nce

/C

ontr

avar

ian

ce

{ C # C O R N E R }

When used as a parameter, arrays are sometimesinvariant, and sometimes covariant.

Just like the classic collections, arrays are not safely covariant.

0509vsm_Langlab_36-46.v11 4/17/09 12:44 PM Page 36

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 37

covariant and contravariant. A few examples quickly illustratethe issue.

You could believe these collections act as covariant becauseyou can create an ArrayList of Employee objects and use that asa parameter to any method that uses objects of type ArrayList.Often, that approach works just fine. This method would workwith any arraylist:

private void SafeCovariance(ArrayList bunchOfItems){

foreach(object o in bunchOfItems)Console.WriteLine(o);

// reverse the items:int start = 0;int end = bunchOfItems.Count - 1;while (start < end){

object tmp = bunchOfItems[start];bunchOfItems[start] = bunchOfItems[end];bunchOfItems[end] = tmp;start++;end--;

}

foreach(object o in bunchOfItems)Console.WriteLine(o);

}

This method is safe because it doesn’t change the type of anyobject in the collection. It enumerates the collection, and itmoves items already in the collection to different indices in thecollection. However, none of the types change, so this methodwill work in all instances.

However, ArrayList, and other classic .NET 1.x collectionscannot be considered safely covariant. Look at this method:

private void UnsafeUse(ArrayList stuff){

for (int index = 0; index < stuff.Count; index++)stuff[index] = stuff[index].ToString();

}

It’s making deeper assumptions about the objects stored in thecollection. After the method exits, the collection containsobjects of type string. That may not have been the type of theoriginal collection. In fact, if the original collection containedstrings, the method does nothing. Otherwise, it transforms thecollection into a different type.

The following usage example shows the kinds of problemsencountered when you call this method. Here, a list of numbersis sent to UnsafeUse, where it’s transformed into an ArrayList ofstrings. After that call, the calling code tries again to create thesum of the items, which now causes an InvalidCastException.

// usage:public void DoTest(){

ArrayList collection = new ArrayList()

{1,2,3,4,5,6,7, 8, 9, 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30

};

SafeCovariance(collection);// create the sum:int sum = 0;foreach (int num in collection)

sum += num;Console.WriteLine(sum);

UnsafeUse(collection);// create the sum:sum = 0;try{

foreach (int num in collection)sum += num;

Console.WriteLine(sum);}catch (InvalidCastException){

Console.WriteLine("Not safely covariant");

}}

This example shows that while classic collections are invari-ant, you could, for all practical purposes, treat them as thoughthey were covariant (or contravariant). But these collectionsare not safely covariant. The compiler does nothing to keepyou from making mistakes in how you treat the objects in aclassic collection.

ArraysWhen used as a parameter, arrays are sometimes invariant, andsometimes covariant. Once again, just like the classic collec-tions, arrays are not safely covariant.

First and foremost, only arrays containing reference typescan be treated as either covariant or contravariant. Arrays ofvalue types are always invariant. That’s true even when trying tocall a method that expects an object array. This method can becalled with any array of reference types, but you cannot pass itan array of integers or any other value type:

private void PrintCollection(object[] collection){

foreach (object o in collection)Console.WriteLine(o);

}

As long as you constrain yourself to reference types, arrays arecovariant and contravariant. However, they’re not safely covariantor safely contravariant. The more often you treat arrays as covari-ant or contravariant, the more you’ll find that you need to handleArrayTypeMismatchException. Let’s examine some of the ways.

C# Corner

Cov

aria

nce

/C

ontr

avar

ian

ce

0509vsm_Langlab_36-46.v11 4/17/09 12:44 PM Page 37

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com38

</Language Lab>

Array parameters are covariant, but not safely covariant.Examine this dangerous method:

private class B{

public override string ToString(){

return "This is a B";}

}

private class D : B{

public override string ToString(){

return "This is a D";}

}

private class D2 : B{

public override string ToString(){

return "This is a D2";}

}

private void DestroyCollection(B[] storage){

try{

for (int index = 0; index < storage.Length;index++)

storage[index] = new D2();}catch (ArrayTypeMismatchException){

Console.WriteLine("ArrayTypeMismatch");}

}

The following calling sequence will cause the loop to throw anArrayTypeMismatch exception:

D[] array = new D[]{new D(),new D(),new D(),new D(),new D(),new D(),new D(),new D(),new D(),new D()};

DestroyCollection(array);

The reason is obvious when you see the two blocks together.The call site created an array of D objects, then calls a methodthat expects an array of B objects. Because arrays are covariant,you can pass the D[] to the method expecting B[]. But, insideDestroyCollection(), the array can be modified. In this case, itcreates new objects for the collection, objects of type D2. That’sfine in the context of that method: D2 objects can be stored in aB[] because D2 is derived from B. But, the combination oftencauses errors.

The same thing happens when you introduce somemethod that returns the array storage and treat that as a con-travariant value. This code looks like it would work fine:

B[] storage = GenerateCollection();storage[0] = new B();

However, if the body of GenerateCollection looks like this, itwill cause an ArrayTypeMismatch exception when the stor-age[0] element is set to a B object.

Generic CollectionsArrays suffer from being treated as covariant and contravariant,even when that’s not safe. The .NET 1.x collection types areinvariant, but stored references to System.Object, which wasn’ttype safe in any practical sense. The generic collections in .NET2.x and beyond suffer from being invariant. That means youcannot ever substitute a collection containing a more derivedobject type where a collection containing a less derived type isexpected. That’s a lengthy way to say that a lot of substitutions

C# Corner

Cov

aria

nce

/C

ontr

avar

ian

ce

The generic collections in .NET 2.x and beyond suffer from being invariant. That means you cannot ever substitute a collection containing a more derived object type where a collection

containing a less derived type is expected. That’s a lengthy way to say that a lot of substitutions you expect to work, don’t.

0509vsm_Langlab_36-46.v11 4/17/09 12:44 PM Page 38

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

you expect to work don’t. You’d think that you could write amethod like this:

private void WriteItems(IEnumerable<object> sequence){

foreach (var item in sequence)Console.WriteLine(item);

}

You’d think you could call it with any collection that implementsIEnumerable<T> because any T must derive from object. Thatmay be your expectation, but because generics are invariant, thefollowing will not compile:

IEnumerable<int> items = Enumerable.Range(1, 50);WriteItems(items); // generates CS1502, CS1503

You can’t treat generic collection types as contravariant, either.This line will not compile because you cannot convertIEnumerable<int> into IEnumerable<object> when assigning thereturn value:

IEnumerable<object> moreItems =Enumerable.Range(1, 50);

You might think IEnumerable<int> derives fromIEnumerable<object>, but it doesn’t. IEnumerable<int> is aClosed Generic Type based on the Generic Type Definition forIEnumerable<T>. IEnumerable<object> is another ClosedGeneric Type based on the Generic Type Definition forIEnumerable<T>. One does not derive from the other. There’sno inheritance relationship, and you cannot treat them ascovariant. Even though there’s an inheritance relationshipbetween the two type parameters (int, and object), there’s nocorresponding inheritance relationship between any generictypes using those type parameters. It feels like it should work,and strictly speaking, it does work correctly.

C# treating generics invariantly has some very powerfuladvantages. Most significantly, you can’t make the mistakes Idemonstrated earlier with arrays and the 1.x style collections.Once you get generic code to compile, you’ve got a much betterchance of making it work correctly. That’s consistent with C#’sheritage as a strongly typed language that leverages the compilerto remove possible bugs in your code.

However, that heavy reliance on strong typing feels restric-tive. Both of the constructs I just showed for generic conversionsfeel like they should just work. And yet, you don’t want to revertto the same behavior used for the .NET 1.x collections andarrays. What we really want is to treat generic types as covariantor contravariant only when it works, not when it simply substi-tutes a runtime error for a compile time error.

C# 4.0 syntaxC# 4.0 will introduce a set of changes to the language thatremoves the surprising behavior that closed generic typescan’t be treated as covariant or contravariant without intro-ducing yet another breach in the type safety system. C# 4.0introduces syntax to treat some generic types as safely covari-ant and safely contravariant.

0509vsm_Langlab_36-46.v11 4/17/09 12:44 PM Page 39

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com40

</Language Lab>

The C# 4.0 language specification uses the terms “outputsafe” and “input safe” to describe type parameters that aresafely covariant or contravariant, respectively. Those termsare somewhat more descriptive, if less precise, to describehow covariance and contravariance work. A couple exampleswill make it clearer.

The familiar IEnumerable<T> and IEnumerator<T>interfaces are output safe. Therefore, both interfaces can betreated as covariant. Furthermore, those methods are safelycovariant. In C# 4.0, both of those interfaces have been anno-tated with the new “out” contextual keyword to indicate thatthey can be treated safely covariant:

public interface IEnumerable<out T> : IEnumerable{

IEnumerator<T> GetEnumerator();}public interface IEnumerator<out T> : IEnumerator{

bool MoveNext();T Current { get; }

}

Notice the addition of the “out” contextual keyword. That sig-nifies that T is covariant. It will compile cleanly because Tappears only in output positions, and is output safe. Thatmeans, beginning with C# 4.0, you can use anIEnumerable<string> where the formal parameter list expectsan IEnumerable<object>. The earlier example:

WriteObjects(IEnumerable<object> items)

can be called using a List<string>, or other reference type.Similarly, some interfaces contain type parameters that are

input safe. For example, IEquatable<T> has been updated not-ing that it’s input safe:

public interface IEquatable<in T>{

bool Equals(T other);}

Throughout IEquatable, T appears only in input positions.Furthermore, those input positions are never annotated with theref or out modifier. T is therefore input safe and can be treated as

contravariant. Because T only appears in input locations, a lessderived type can be used in the formal parameter list where amore derived type is used as the actual parameter. AnIEquatable<object> can be used where you expect anIEquatable<string>.

Other interfaces are still invariant. ICollection<T> con-tains methods where T appears in input positions as well asmethods where T appears in output positions:

public ICollection<T> : IEnumerable<T>{

void Add(T item);// other methods elidedIEnumerator<T> GetEnumerator();

}

The Add() method is not output safe. The GetEnumerator()method is not input safe. Because the entire interface is neitherinput safe nor output safe, the ICollection<T> interface cannotbe treated as either covariant or contravariant. Therefore,ICollection<T> will remain invariant.

There are quite a few limitations on covariance and con-travariance in the C# language. Those limitations are meant tominimize potential runtime errors related to misuse of thosefeatures. The limitations can be easily remembered by a couplebroad guidelines.

First off, the “in” and “out” contextual keywords can onlybe applied to interface and delegate generic type definitions.You can’t create covariant or contravariant generic class defini-tions. Therefore, MyClass<in T> is illegal.

The other limitations apply when you attempt to treat aparticular type parameter as covariant or contravariant.Covariance and contravariance only apply when there’s a refer-ence conversion between the two specific type parameters. As Imentioned earlier, IEnumerable<string> can be used whereIEnumerable<object> is expected. There’s a reference conver-sion from string to object. However, IEnumerable<int> can’tbe used where IEnumerable<long> is expected. There’s a con-version from int to long, but that’s a widening conversion, not areference conversion. In addition, IEnumerable<int> cannotbe used where IEnumerable<object> is expected. Again, thereis a conversion from int to object, but it’s a boxing conversion,not a reference conversion.

In practice, the reference conversion rule means that youcan only treat different closed generic types as covariant or

C# Corner

Cov

aria

nce

/C

ontr

avar

ian

ce

In practice, the reference conversion rule means that you can only treat different closed generic types as covariant or

contravariant when the type parameters are both reference types,and are related by some inheritance relationship.

0509vsm_Langlab_36-46.v11 4/17/09 12:44 PM Page 40

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 41

Cov

aria

nce

/C

ontr

avar

ian

ce

contravariant when the type parameters are both referencetypes, and are related by some inheritance relationship.

In order to support covariance and contravariance, the.NET 4.0 BCL will have several generic interfaces and delegatetypes updated to be safely covariant and contravariant. As youlearn more about Visual Studio 2010, take the time to learnabout how those language extensions on the interfaces enableyou to express designs in less code, and reuse more logic safely.

What Can You Do Now?At this point, you may be asking how this matters. After all, VS2010 is still a future technology, and it will be some time beforeit will make its way to the corporate developer.

The question is how to author your code today such that itcan easily take advantage of the new covariant and contravari-ant additions when they become available. Knowledge of thenew features will help you create code that’s ready to accept thein or out contextual keywords on your interface and delegatetypes. It will become more important to factor those interfacesinto input only and output only portions, so that your inter-faces can support both covariance and contravariance, asappropriate. You should examine your generic interfaces andmethods to see if the parameters and return values are inputsafe or output safe. That will make it easier to use them in eithera covariant or contravariant manner in the near future.

A more immediate need is to be able to emulate the covari-ant and contravariant features using the current language ele-ments. You can’t replicate all the features, because if it alreadyworked, there’s no reason for the language teams to add thesefeatures. That said, you can get close in some usages.

There are two techniques that you can often use to miti-gate the need for covariance and contravariance. You can useCast<T> or you can create generic methods instead of covari-ant and contravariant methods.

The earlier WriteItems() method could be modified as ageneric method easily:

private void WriteItemsGeneric<T>(IEnumerable<T> sequence)

{foreach (T item in sequence)

Console.WriteLine(item);}

Now, you can call WriteItems() for any sequence, including asequence of integers. In other uses, where your methods needcapabilities beyond those methods in System.Object, you’llneed to add constraints on the generic method, possibly evenfactoring out an interface contract as part of the genericmethod constraints. However, there will almost always be a wayto create a generic method that can be used where you want tocreate a covariant method, or a contravariant method. When

you write the method, you should convert the method to ageneric method.

When you don’t have access to the core method because it’sin a third-party library, you can use the Cast<T> method in the specific cast where you need to convert betweenIEnumerable<T> types for two different type parameters. Ofcourse, this can occur only where a conversion between thosetypes exist.

Remember that the original generic WriteItems() methodwas coded this way:

private void WriteItems(IEnumerable<object> sequence){

foreach (var item in sequence)Console.WriteLine(item);

}

You can call that method using a sequence of integers by apply-ing the Cast<T> method at the call site:

IEnumerable<int> items = Enumerable.Range(1, 50);WriteItems(items.Cast<object>());

The Cast<T>() method enumerates the input collection, con-verting each element, and yields the converted collection as itsoutput. While this option will not work for other types, it willalways work where you need an IEnumerable<T> conversionfor different types.

In this article, I’ve shown you the motivation behind theaddition of the generic covariance and contravariance in C#4.0. They’re being added because invariant generic types are toorestrictive for most uses. There are covariant and contravariantconversions that we expect to work. In C# 3.0, those conversionsdon’t work, to the surprise of many developers. The languageteam is addressing that in C# 4.0. In the meantime, there areways to mitigate the need for those features. 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 is a Microsoft Regional Director and a Visual C# MVP. His

interests include the C# language, .NET Framework and software design.

GO ONLINE

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

READ & DOWNLOAD

VS0905CC Read this article and download the sample code.

C# Corner

The question is how to author your code today such that it can easily take advantage of the new covariant and

contravariant additions when they become available.

0509vsm_Langlab_36-46.v11 4/17/09 12:44 PM Page 41

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com42

</Language Lab></Language Lab>T

4 T

emp

late

s

Visual Studio’s T4 CodeGeneration Learn how to create and debug templates usingMicrosoft’s T4 templating language.BY KATHLEEN DOLLARD

Q: I want to generate some of the code for my application and afriend of mine said that Microsoft has a code generator, but I can’tfind one. Do you know what he’s talking about?

A: Microsoft actually has two major code-generation tools—theCodeDOM and T4. Your friend was probably referring to T4because the CodeDOM is so difficult to read and maintain thatit’s inappropriate for almost all business applications. T4 (pre-viously called T3) stands for Text Transformation TemplatingToolkit. T4 is an ASP.NET-style syntax that has direct literal textoutput, embedded expressions and code logic.

T4 is already on your machine if you’re using Visual Studio2008, or you can download the DSL Toolkit if you’re using VS2005. T4 can generate any type of textual artifact. That’s goodnews. The bad news is that the support is not complete andVisual Studio is missing critical capabilities. But there’s moregood news: adding two free tools to your environment gives youa solid base for generating code. I’ll show you how to create anddebug a T4 template and three ways to run T4 templates, includ-ing a Managed Extensibility Framework-based harness, whichacts as an ecosystem for evolving code generation.

T4 templates begin with a template directive. Directivesare identified by the <#@ #> tag. In addition to initiating thetemplate, the template directive indicates the language of thetemplate and allows debugging. T4 templates include .NETcode and the language attribute indicates the language of coderunning in the template, not the artifact you’re creating. Bydefault, T4 uses the 2.0 version of the language, but you canchange this by appending “v3.5” to the language attribute.

Following the template directive, you can include any com-bination of literal text (in grey below) and code and expressionswithin statement blocks identified with the <# #> tags:

template language="C#" debug="true"

Good Morning World!

Good Afternoon World!<#

Good Evening World!

In this sample template, statement blocks indicate which greet-ing to output. VS doesn’t provide coloration, which makes itextremely difficult to read the templates. I recommend down-loading an editor from Clarius Consulting. Clarius has both afree community edition and a more sophisticated retail editionat http://tinyurl.com/dkqkmc.

This is enough background to create your first T4 tem-plate. Open VS and create a new project of any type. Add a NewItem and select the type Text File. Name the file with the exten-sion .TT. Enter the code in the previous sample or some varia-tion. VS maps the .TT extension to a custom tool namedTextTemplatingFileGenerator. This custom tool provides adefault mechanism for running simple templates and learningabout T4. When you save the template, the custom tool runs,calls the T4 engine and outputs code to a dependent file. When

#>}<#

#>{

else}

#>{else if(hour > 12 && hour < 17)}

<##>{

if(hour < 12)int hour = DateTime.Now.Hour;<#

#><#@

Code GenerationPrinciplesAs I started working on code generation, I began uncovering underly-ing principles. No one meets them all, but these are the goals we’restriving for:1. Code generation must be in your control. If something goes

wrong with your application, you’re responsible for fixing it. Youcan’t fix something you can’t change. You need control of the tem-plates behind your code generation.

2. Metadata is distinct and morphable. Metadata is the data thatdrives your application and makes it unique from other applica-tions. It needs to be distinct so you can find and debug it, and itneeds to be morphable so your database and business objectsaren’t required to match.

3. Code generation should fit into your development process. Ifyou’re doing nightly builds, code generation should be part of it,otherwise it should be a simple one-click process. Generated codeshould be included in source control as all other code.

4. Handcrafted code is sacred and protected. People are creativeand may not do the same thing the same way a second time, soyou should have a place for handcrafted code in the design(derived or partial classes) and protect against accidental change.

5. Generated code is of extremely high quality. One of the greatest benefits of code generation is high-quality architecturesthat can evolve to meet changing demands.

6. Designing an application based on generation should beeasy. T4 templates and a simple ecosystem-based harness is onestep in this direction. —K.D.

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

0509vsm_Langlab_36-46.v11 4/17/09 12:44 PM Page 42

Ask Kathleen

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 43

you expand the plus sign on the template file, you’ll find theoutput with a .CS extension containing Good Morning World!,Good Afternoon World! or Good Evening World!

If you use a VB project, you might be surprised that theextension of the generated file is .CS. The custom tool defaultsto .CS, but you can fix this by specifying the extension in anoutput directive:

output extension=".vb"

The T4 engine first parses the template to create a temporary classderived from the TextTransformation class. This class is compiledand run to produce output. The code you put inside statementblocks is placed in the body of the TransformText property in thetemporary class. The literal text of your template (shown in grey)is included in calls to the Write method of a string builder withinthis temporary class. You can debug by placing breakpoints insideyour template and stepping through the code. You’ll step throughyour template, not the compiled temporary class. While debug-ging, you can access any data available to the template. In addition

to any fields and properties you declare, you can access base class.Members of the base class allow you to control indentation(PushIndent, PopIndent, ClearIndent, CurrentIndent), reportissues (Error, Warning, Errors) and directly access the stringbuilder (Write, WriteLine, GenerationEnvironment).

Code within statement blocks is run, but is not treated asoutput. Often you’ll need to include calculated or retrieved fields.You can do this using the expression block, differentiated by <#= #>.Also, because the code of your template becomes code in amethod, you’ll need a different type of block to include additionalmethods or additional classes. The class feature block offset by <#+ #> offers this capability.You can write the template above in adifferent way to demonstrate these features:

template language="C#" debug="true"

int hour = DateTime.Now.Hour;{

public string OutputGreeting()<#=

#>OutputGreeting() <#=#><#@

#><#@

Exceptional Software Protection

CodeMeter for .NET

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

Software Protection

Access Protection

Document Protection

Media Protection

More than 1000 Key-Storage License Entries�

- Different ISV´s can share one dongle

Secure 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“ users

Create “Standby“ Licenses�

- Hot Standby and Cold Standby- Provide Overfl ow Licenses

Pay-Per-Use Counter�

PERFECTION IN SOFTWARE PROTECTION

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

T4

Tem

pla

tes

The templates you use to create application code will be a smooth integration of three elements: statement blocks to guide

template logic, expression blocks for output, and class feature blocks for methods and classes to facilitate reuse.

0509vsm_Langlab_36-46.v11 4/17/09 12:44 PM Page 43

T4

Tem

pla

tes

Ask Kathleen

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com44

</Language Lab>

The templates you use to create application codewill be a smooth integration of three elements:statement blocks to guide template logic, expres-sion blocks for output, and class feature blocksfor methods and classes to facilitate reuse.

In addition to the template and output direc-tives, T4 natively provides four other directives.The import directive provides namespace recog-nition similar to Imports in Visual Basic or theusing statement in C#. The include directiveplaces the contents of another T4 template intothe current template. The assembly directiveadds .NET assemblies for the template code,similar to adding a reference in VS. Using thedefault tools, assemblies must include the fullfile path (from the root directory), be in theGAC or be referenced by the current project. Ifthe include directive uses a relative path and theincluded template contains additional includedirectives, all relative paths are in relation to thefirst or root template location, making “doublejumps” for code reuse difficult.

You can play with templates using VS’sautomatic generation, but you’re likely to soonrun into limitations: Code reuse is hampered byputting the template directly into your outputdirectory. You can’t pass input parameters. It’s apain to write .NET code without IntelliSenseand syntax checking. It hopelessly intertwinesthe output project with the generation mecha-nism, which breaks the Single ResponsibilityPrinciple and Separation of Concerns. I prefer tomove out of VS and focus on self-containedtemplates running in a harness, which separatethe action of generation from the activity of thegenerated application. If you wish to work with-in the VS model, the T4 Toolbox on CodePlex(www.codeplex.com/t4toolbox) takes the VScustom tool usage to amazing lengths and OlegSych’s blog (www.OlegSych.com) has good cov-erage of T4 intricacies. Another option workinginside VS is to write your own custom tool forgeneration. (See “Generate Code from CustomFile Formats,” March 2009, and the September2008 Ask Kathleen column, “Customize CodeGeneration in EF.”) Custom tools can provide aT4 wrapper and use an alternate T4 host to solve

some issues, such as assembly and include file location resolution.However, you’ll still face challenges as you stuff your generationprocess inside your application project.

T4 HarnessI prefer to write an independent generation harness that canrun multiple templates to build your app and is focused on

#>}{ return "Good Evening!"; }else{ return "Good Afternoon!"; }else if(hour > 12 && hour < 17){ return "Good Morning!"; }if(hour < 12)

template language="C#" debug="true" hostspecific="true" output extension=".sql" assembly name="CommonDatabaseContracts.dll" property name="table" type=

"AppVenture.Common.IDbTableMetadata" import namespace="System.Collections.Generic" import namespace="AppVenture.Common"

SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO

CREATE PROCEDURE Select

ASBEGIN

SET NOCOUNT ON;

SELECT

FROM

ENDGO

#>}

return ret.Substring(0, ret.Length - 2);}

ret += item.Name + ", " ;{foreach (IDbTableColumnMetadata item in list)

string ret = String.Empty;{Metadata> list)

string ConcatenateWithComma(IEnumerable<IDbTableColumn<#+

#>table.Name <#=

#>ConcatenateWithComma(table.TableColumns) <#=

#>table.Name <#=

#>TemplateOutputFileName = table.Name; <##><#@

#><#@#>

<#@#><#@

#><#@#><#@

TEMPLATE HARNESS

LISTING 1 A simple select stored procedure can be created from database metadata. The AppVenture Community Generation Harness (available withsource code) retrieves the corresponding tables from a Managed ExtensibilityFramework part and loops through them calling this template once for each loop.Within the context of the harness, this template is entirely self-contained.

???

C#

0509vsm_Langlab_36-46.v11 4/17/09 12:44 PM Page 44

VisualStudioMagazine.com · May 2009 · VISUAL STUDIO MAGAZINE 45

Ask Kathleen

T4

Tem

pla

tes

reuse. I’ll explain in broad terms how a T4 harness works, andhow you can download a working harness with source code.

If you’re using a separate harness, you don’t want thedefault VS behavior of creating the dependent file because yourtemplate will rely on features not present and fail. The easiestway to block this behavior is to give your templates a .T4 exten-sion. The Clarius editor will still recognize your templates withthis extension.

To provide extra functionality, such as passing parameters,the generation harness uses a custom T4 host. The host mustimplement ITextTemplatingEngineHost and may also imple-ment IServiceProvider. The host is responsible for all interac-tions with the environment: managing links to custom directiveprocessors, finding assemblies and include files, and providingservices. By creating your own custom host, you can provideextra functionality and data, such as a dictionary of parameternames and values.

Creating custom directives allows you to expand the infor-mation the template author provides. For example, the tem-plate author can provide a list of parameters. Within the tem-plate, parameters are treated as properties, so by conventionparameters are declared using a custom directive named prop-

erty (see Listing 1, opposite page). Including explicit parameterrequests in the template leads to better encapsulation.

Custom directives require a directive processor, whichinserts the required code into the temporary class when calledby the engine. Custom directive processors inherit fromDirectiveProcessor. Its ProcessDirective method is called oncefor each directive. This method creates the code required by thedirective and the engine inserts this text into the temporaryclass. The property directive processor creates a .NET propertyfor each directive. The backing data for the property is retrievedby casting the host to an IServiceProvider that offers thePropertyDictionary.

Code Generation and MEFIf that sounds like a lot of gnarly code—it is. To make it easierfor you to use T4, I’ve created a T4 harness based on theManaged Extensibility Framework (MEF).

Code generation and MEF are a perfect fit. Templatesbecome MEF parts that are discoverable simply by beingplaced in a directory pointed to by a configuration file. Youcan add or remove templates just by altering the contents ofthis directory.

The pieces of the harness are like Lego blocks—pick the ones that make sense in your environment.

0509vsm_Langlab_36-46.v11 4/17/09 12:44 PM Page 45

T4

Tem

pla

tes

Ask Kathleen

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com46

</Language Lab>

Metadata, output services, and eventhe property directive processor are MEFparts. The pieces of the harness are likeLego blocks—pick the ones that makesense in your environment. The purposeof the harness is to empower a creative andflexible ecosystem that expands as yourneeds change.

I’ve glossed over a few details that areworth returning to. MEF parts must be.NET objects, and T4 templates are justtext files until they’re executed. Each T4template must be wrapped in an instanceof a class that is a non-shared MEF partand the harness needs to perform discov-ery. Because discovery is directory based,the harness just needs to grab the T4 tem-plates in a particular directory, place themin the MEF part wrapper and ensure MEFcan find the part. Discovery itself is an MEFpart, so if you’d rather use a different dis-covery scheme such as a script, feel free.

While I’ve talked about the interac-tions between a host parameter dictionary and a propertydirective processor, I haven’t explained how the host knowswhat parameters to expect or where to get the values. Becausea T4 template is just a text file, the MEF wrapper can crack itopen, parse, and extract a list of expected parameters fromthe property directives. Property directives are used twice—to create a dictionary of parameters and to generate code forthe temporary T4 class.

Because MEF creates an ecosystem, the wrapper does notneed to explicitly find values for the parameters; it merely asksthe MEF container first for any match on the parameter name,then for a match on the type. To avoid unnecessary dependen-cies, use the name only for simple types such as string or date,and base other matches on the data type.

While I’ve only discussed property directives, you can cre-ate any other type of directive you want. The directive processoris retrieved via MEF, and I’ve provided a base class which makescreating new directive processors very easy.

Generation often requires that templates run multiple timeswith different data to create multiple files. It would break theSingle Responsibility Principle for the template itself to definelooping behavior. The harness solves this problem by searchingfor parts that export a special ILoopValues interface with a customMetadataView attribute that provides the loop type. If a parame-ter is a type supported by a loop value provider, the T4 template iscalled once for every item in the collection.

Because many files are output, each needs a unique name.To make this easy, the harness provides a special parameternamed TemplateOutputFileName. Assign a name based on thedata in each pass of the template.

The generation harness assumes you have control andknow what code is running during generation. MEF parts and

T4 templates run code and can therefore run malicious code.You need to ensure the integrity of the parts and the T4 tem-plates you place into your environment.

I’m releasing my T4 harness with full source code for youto work with and explore. You can download AppVentureCommunity Generation Harness with source code from thedownload section at www.appventure.com and you can readmore about its ongoing development in my blog atwww.msmvps.com/blogs/kathleen. Our intention is to makethe project open source as soon it stabilizes and we start build-ing a community. If you’re interested in helping out as we movetoward that goal, let me know. VSM

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

AppVenture (www.appventure.com)—building relationships that

leverage our application generation experience to speed and improve

your application development. She’s been a Microsoft MVP for 11 years

and is a member of the INETA Speaker’s Bureau. Dollard has worked

extensively with application code generation and is the author of “Code

Generation in Microsoft .NET” (Apress, 2004). She speaks at dozens of

conferences and user groups each year and is active in the Northern

Colorado .NET SIG, Denver Visual Studio User Group, Northern

Colorado Architect’s Group and IASA Denver.

GO ONLINE

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

READ & DOWNLOAD

VS0905AK Read this article and download the sample code.

FIGURE 1. The ExportContainer of MEF acts like a schoolyard where different players can raise their hands and shout “I need a xxx” or “Use my xxx.” Whenteamed with intelligent granularity, this creates an ecosystem for evolution ofindividual parts without disrupting the whole.

0509vsm_Langlab_36-46.v11 4/17/09 12:44 PM Page 46

VisualStudioMagazine.com · May 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.comAccusoft Pegasus 21www.accusoft.comAspose C3www.apose.comAtalasoft, Inc 19www.atalasoft.comComponentArt, Inc. 24, 25www.componentart.comdtSearch 39www.dtsearch.comESRI 5www.esri.comGrapeCity, Inc. 13www.grapecity.comIntel Corporation C4www.intel.comLEAD Technologies, Inc. 9www.leadtools.comMicrosoft Corporation 16, 17www.microsoft.comPureCM.com 29www.purecm.comRallySoftware 45www.rallydev.comRed Gate Software 23www.red-gate.comSoftware FX C2, 1www.softwarefx.comVSLive! Events 32, 33, 34, 35www.vslive.comWayside Technology Group, Inc 2www.waysidetechnology.comWIBU-SYSTEMS USA, Inc 43www.wibu.com

Editorial IndexCA Inc. 12www.ca.comComponentOne LLC 20, 22www.componentone.comDataDirect Technologies 12www.datadirect.comDeveloper Express Inc. 18, 20www.devexpress.comdynaTrace Software 12www.dynatrace.comEmbarcadero Technologies Inc. 20www.embarcadero.comIBM Corp. 12www.ibm.comInfragistics 19, 20www.infragistics.comJNBridge 22www.jnbridge.comMagenic Technologies Inc. 11www.magenic.comNalpeiron 20, 22www.nalpeiron.comNcover 22www.ncover.comNevron Software 21www.nevron.comNoemax Technologies 22www.noemax.comOracle Corp. 12www.oracle.comPreEmptive Solutions 22www.preemptive.comPureCM.com 20www.purecm.comREAL Software 20, 21www.realsoftware.comResco 20www.resco.netSAP AG 20www.sap.comSun Microsystems Inc. 48www.sun.comSybase Inc. 11, 12www.sybase.comTelerik 21www.telerik.comThe Imaging Source 20www.textcontrol.comVisual Numerics Inc. 22www.vni.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

0509vsm_AdIndex 4/17/09 11:51 AM Page 47

</RedmondReview>

VISUAL STUDIO MAGAZINE · May 2009 · VisualStudioMagazine.com

I’ve been on a nostalgic binge lately. I’ve been watching oldmovies, sharing tales of my childhood with my son and thinkingabout how much the neighborhood I grew up in has changed. Thenostalgia extends to technology, too: In my column last month(“What’s Old Is New Again,” April 2009) I remarked how a 15-year-oldMicrosoft technology and a new one reflect similar industry trends.

I’m not the only one finding value in classic coding—something I realized while taking a look at PHP and MySQL. Microsoft is really interested in these products, though at first blush it’s hard to tell why. They’re open source technologies, have nodependency on Windows, pose a competitive threat to .NET, and one of them, MySQL, is even owned by a longtime Microsoftnemesis in Sun Microsystems.

And yet, Microsoft is promoting Windows Server 2008 andIIS7 (with its FastCGI support) as a great place to run PHP. This ismore than rhetoric: Microsoft has built something called the PHPon Windows Training Kit. It’s free, it’s online (get the March releasecandidate at http://tinyurl.com/cemn2o), and every attendee atMicrosoft’s MIX09 conference in March received the kit on a USBthumb drive.

I was at MIX09 and walked away with one of the thumbdrives. On the flight home, I looked it over and, forgive me forsaying so, it makes PHP programming look very attractive. You can do PHP development using simple script code inlinewith HTML—the language is quite intuitive and easy to follow.Plus, the kit shows you how to use PHP with SQL Server. It’s easy: you use individual function calls to connect to a database, submit queries, manage parameters and fetch rowsinto simple arrays.

At first I couldn’t put my finger on why this model was soappealing. Then I realized: It was the continuing pull of nostalgia.PHP code looks an awful lot like classic Active Server Pages. Andthe SQL Server driver for PHP, the code for which is similar to thatfor MySQL, turns out to be the thinnest of wrappers around theODBC API. This was the coding equivalent of comfort food; I’d gone

back home again. But the significance of this extends beyond mereconnecting with my past; it actually underscores why Microsoftneeds to do the same.

Redmond wonders why PHP is so popular and why so manyof the biggest open source applications—WordPress, Drupal, takeyour pick—are written in it. More significantly, Microsoft is strug-gling to understand how MySQL, the relational database that’s“good enough,” is stealing an increasing amount of momentumfrom SQL Server.

The truth is right there. The very simplicity and productivityof classic VB, ASP and earlier data-access models is what madethe Microsoft developer ecosystem so huge. As important and successful as .NET has been, the framework has pushed Microsoftto abandon much of that simplicity and de-prioritize the wants andneeds of the developers who once flocked to it.

PHP and MySQL have beaten Microsoft at the game it practically invented. Together, they offer a programming environment with a low barrier to entry, high productivity, more-than-sufficient functionality, low cost and a wildly enthusiastic ecosystem of developers. Dial back to the early

1990s, and that was Microsoft. In the latter partof this decade, it most certainly is not.

There were good reasons for Microsoft tofocus on the enterprise. There were good reasonsto make .NET a stack that required a caliber ofdeveloper perhaps more senior than those in theVB and ASP constituencies. Yes, COM was long inthe tooth. Sure, VB’s lack of inheritance and otherprogramming niceties meant the Java bullies

picked on the VB kids in the developer schoolyard. .NET wasabsolutely necessary, and its success gave Microsoft some desperately needed momentum in the developer community.

But now, more than seven years after .NET 1.0, Microsoftneeds to get back to its roots. This is not a zero-sum game:Microsoft can still serve the hardcore professional developer with.NET, its base class libraries, and technologies like WindowsCommunication Foundation, Windows Workflow Foundation, “Oslo”and “Dublin.” But Microsoft can, and must, serve the productivityprogrammer as well. Because if it doesn’t, others clearly will. VSM

Andrew J. 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).

Remembrance of Code Past

BY ANDREW J. BRUST

PHP and MySQL have beaten Microsoft at the game

it practically invented.

48

0509vsm_RedReview_48.v3 4/17/09 12:48 PM Page 48

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

EVOLVE YOUR CODE.Parallelism breakthrough.

Preorder now. Product shipping May 26.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.

Project2 4/16/09 10:36 AM Page 1