Sunteți pe pagina 1din 52

VisualStudioMagazine.

com

Headwinds

How are Microsoft, tool vendors


and development shops dealing
with the downturn? Our TechEd
preview offers a .NET forecast.

PLUS

Create Data-Driven Apps


with Silverlight 3
Generate Code Using
T4 Templates

MAY 2009 Volume 19, No. 5

Why Redmond Needs to


Return to Its Roots

Project4

4/17/09

1:23 PM

Page 1

Be The Master On Any Platform

VTCVirtual Training
Center for SharePoint

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.

Project4

4/17/09

1:24 PM

Page 2

Choose AHigher Power For DataVisualization


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 thats clearly on top.
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 past 15 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.

Introducing our new products for SharePoint 2007


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.

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

Data visualization for every need, every platform

Project3

3/30/09

12:50 PM

Page 1

Your best source for


software development tools!

LEADTOOLS Document
Imaging v 16:
by LEAD Technologies
LEADTOOLS Document Imaging has every
component you need to develop powerful
image-enabled business applications including
specialized bi-tonal image display and
processing, document clean up, high-speed
scanning, advanced compression (CCITT
G3/G4, JBIG2, MRC, ABC) and more.
Multi-threaded OCR/ICR/OMR/
MICR/Barcodes (1D/2D)
Forms recognition/processing
PDF and PDF/A
Paradise #
L05 03201A01 Annotation (Image Mark-up)
C/C++, .NET, WPF - Win32/64
$
99
programmers.com/lead

2,007.

Pragma Fortress SSH


SSH Server for Windows

dtSearch Engine for Win & .NET


Add dtSearchs blazing speeds
(CRN Test Center) searching and
New
file format support
64-bit
Version!
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

VMware View Premier


Starter Kit

Single Server
Paradise #
D29 02101A07

Bottom line: dtSearch manages a terabyte of


text in a single index and returns results in
$
99
less than a second.
InfoWorld
programmers.com/dtsearch

949.

91.99

FarPoint Spread
for Windows Forms
The Best Grid is a Spreadsheet. Give your users
the look, feel, and power of Microsoft Excel,
without needing Excel installed on their machines.
Join the professional developers around the
world who consistently turn to FarPoint Spread
to add powerful, extendable spreadsheet solutions to their COM, ASP.NET, .NET, BizTalk Server
and SharePoint Server applications.
Worlds #1 selling development spreadsheet
Read/Write native Microsoft Excel Files
Cross-sheet formula referencing
Paradise #
F02 01101A01 Fully extensible models
Royalty-free, run-time free

936.99

by Datacore
DataCore SANmelody overcomes the high
cost barrier and complexity of traditional
SAN storage. SANmelody converts standard
Intel/AMD servers, blades or virtual machines
(VMs) into fully capable storage servers that
virtualize disks and serve them over existing
networks to application servers. They are simple
to operate, take only minutes to install, and
let you cost-effectively optimize, manage and
protect data storage and disk space.
Paradise #
DCA 01101A06

CALL

programmers.com/datacore

800-445-7899
Prices subject to change. Not responsible for typographical errors.

CALLI

VDI Included

programmers.com/vmware

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

Paradise #
F01 0131

711.

99

.NET WinForms control for VB.NET and C#


ActiveX for VB6, Delphi, VBScript/HTML, ASP
File formats DOCX, DOC, RTF, HTML, XML, TXT
Professional Edition
PDF and PDF/A export, PDF text import
Paradise #
Tables, headers & footers, text frames, bullets,
T79 02101A02
structured numbered lists, multiple undo/redo,
$
99
sections, merge fields, columns
Ready-to-use toolbars and dialog boxes

848.

Download a demo today.

Make your applications faster, easier to deploy,


and more affordable with c-treeACE.
programmers.com/faircom

Crystal Reports 2008

programmers.com/theimagingsource

Enterprise Architect 7.1

by SAP BusinessObjects
Crystal 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 reports
with stunning visualizations, conduct
on report business modeling, and
execute decisions instantly from the
report itselfreducing dependency
on IT and developers.

Visualize, Document and


Control Your Software Project
by Sparx Systems
Enterprise Architect is a comprehensive,
integrated UML 2.1 modeling suite
providing key benefits at each stage of
system development. Enterprise Architect
7.1 supports UML, SysML, BPMN and
other open standards to analyze, design,
Corporate Edition
test and construct reliable, well under1-4 Users
stood systems. Additional plug-ins are
Paradise #
Paradise #
also available for Zachman Framework,
C0N 17201A01
SP6 0001
MODAF, DoDAF and TOGAF, and to
$
99
$
99
integrate with Eclipse and Visual Studio
2005/2008.
programmers.com/sap
programmers.com/sparxsystems

455.

programmers.com/farpoint

SANmelody Kit v2.0

View Premier
Paradise #
V55 66101A01

by FairCom

The c-treeACE database engine is a high performance


database alternative proven by developers in mission
Contains Windows SSH & SFTP Servers. Certified
for Windows Server 2008. Works with PowerShell. critical enterprise systems, desktop deployments, and
embedded devices for over 25 years.
Full-featured server with centralized
Complete set of APIs including ADO.NET, LINQ,
& graphical management
C#, C/C++, ODBC, JDBC, VCL, and dbExpress
GSSAPI Kerberos & NTLM authentication
Graphical productivity tools
Fastest SFTP & SCP file transfer
Simple deployment
Supports over 1000 sessions
No DBA or ongoing administration
Runs console applications & allows history
Low deployment licensing costs
scroll back within the same session
Cross-platform support for all major platforms
Runs in Windows 2008/2003/Vista/XP/2000
including Windows, UNIX, Linux, and Mac OS X
programmers.com/pragma

New
Release!

c-treeACE Professional

by Pragma Systems

Paradise #
P35 043X

View Premier is an Enterprise-class


Desktop and Application virtualization
suite that enables you to take control
of your desktops and applications while
providing storage optimization. The
Starter Kit is the entry level solution
that includes 10 concurrent user licenses
of VMware Infrastructure Enterprise,
vCenter Foundation, ThinApp, View
Composer and View Manager. SnS
is required and sold separately.

182.

Orion Network
Performance Monitor

Virtual Iron Extended


Enterprise Edition

by Solarwinds
Orion 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.

by Virtual Iron
Virtual Iron Extended Enterprise Edition
provides the most advanced server
virtualization and virtual infrastructure
management capabilities available at
a fraction of the cost.

Paradise #
S4A 08201E02

4,606.99

programmers.com/solarwinds

Unlimited virtual servers


Virtual SMP
Local, iSCSI, FC storage
VLAN
LiveMigration
LiveMaintenance
LiveRecovery

Paradise #
V87L01101A01
$

799.99

programmers.com/virtualiron

programmersparadise.com

0509vsm_TOC_3-4.v5

4/17/09

11:16 AM

Page 3

May 2009 // Volume19 // No. 5

Contents

{ FRAMEWORKS }

Michael Desmond, Editor in Chief,


Visual Studio Magazine

Depressing
Developments

14
FEATURES

14 Headwinds
Despite a troubled economy and falling IT budgets, Microsoft and its partners are
busy rolling out new tools and platforms. We preview some of the goings on at
Microsoft TechEd North America 2009, and talk to developers and ISVs about how
theyre managing in a sluggish software market. BY MICHAEL DESMOND

26 Silverlight 3 Enables Data-Driven App Dev


The latest version of Silverlight boasts a new DataForm control and enhanced
support for data-driven applications, enabling developers to deliver line-of-business
applications 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

DEPARTMENTS

Letters to the Editor

DevDisasters
Gatekeepers of Bad Software BY ALEX PAPADIMOULIS (TheDailyWTF.com)

10 DevInsights DEVELOPER

NEWS, REVIEWS, PRODUCT BRIEFS

News: TechEd Preview PAGE 10


Product Review: Sybase PowerDesigner Data Modeling PAGE 11
Product Briefs: Test Center Standard Edition and Connect ODBC 6.0 PAGE 12

36 LANGUAGE LAB

COVER ILLUSTRATION BY RYAN ETTER

C# Corner PAGE 36
Covariance and contravariance are precise terms that describe which conversions are
safe 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 is
adopted by your organization. BY BILL WAGNER
Ask Kathleen PAGE 42
Learn how to create and debug templates using Microsofts Text Transformation
Templating Toolkit (T4) language, which is included with Visual Studio 2008.
BY KATHLEEN DOLLARD

COLUMNS

Frameworks BY MICHAEL DESMOND

48 Redmond Review

BY ANDREW BRUST

47 Index of Advertisers

The economic downturn doesnt offer


many places to hide. Gartner predicts that
global IT spending this year will decline 3.8
percent from 2008. How is this slowdown
affecting the .NET developer community?
We checked in with developers and ISVs to
get a sense of how theyre adapting as
TechEd North America 2009 approaches.
The results, which are the basis of this
months cover story, were enlightening.
It turns out that different sectors are
experiencing different levels of dislocation.
One survey respondent in the building
industry says all new development is on
hold, we are working on maintenenance
only. But few are taking it harder than
the auto industry.
A developer at a supplier of steering
columns and shifters for auto and
trucking manufacturers from Michigan
says, Our departmental budgets are
virtually non-existent.
Similar tales of layoffs, cutbacks and
bare maintenance-only budgets abound in
the travel, finance, energy utility and other
sectors. Heck, even collection agencies are
hurting. Yes, we have a lot of incoming
business. But while placements are up,
collections numbers are down, and we
cant spend money for new projects, says
the information services director of a
Houston-based collection agency.
Not everyone is cutting back.
Government, military, security and areas of
health care remain active. Respondents
working in the U.S. Army and Air Force say
dev activity is strong, and one government
developer writes, Were moving forward
with all current initiatives as planned.
Funding, while potentially reduced, will just
extend the time toward project completion.
How is your dev organization weathering the downturn? And how is the slowdown impacting your ability to adopt major
new Microsoft technologies? E-mail me at
mdesmond@1105media.com.

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 3

0509vsm_TOC_3-4.v5

4/17/09

11:16 AM

Page 4

Online Contents
Get the complete picture
the latest dev news, analysis
and how-to contentat
VisualStudioMagazine.com
and our partner sites in
the Redmond Developer
Network.

VISUALSTUDIOMAGAZINE.COM

REDDEVNEWS.COM

ADTMAG.COM

Online Tutorials
Wahlin on .NET
Using Silverlights WebClient Class: The
WebClient class gives you a straightforward way to access distributed service
data without having to worry about a lot
of asynchronous complexities.

RDN Express: Avalon Take 2


Developers can expect a lot of progress in
Windows Presentation Foundation 4.0,
which is part of the upcoming .NET
Framework 4.0 beta expected this month.

Linux Projects Shift to Cost


Saving money has replaced adding new
functionality as a key reason for shifting
to open source, according to participants in
a panel at the High Performance Linux on
Wall Street conference.

BY DAN WAHLIN

BY KATHLEEN RICHARDS
LOCATOR+ CODE: VS0905RD1

BY JEFFREY SCHWARTZ
LOCATOR+ CODE: VS0905AD1

LOCATOR+ CODE: VS0905DW1

Classic VB Corner
Prisoner of Geography: When it comes to
our understanding of Unicode issues, the
Born in the USA! chant (no matter how
you feel about The Boss) can almost
amount to a proclamation of cultural
ignorance.

First Service Pack Released for


SQL Server 2008
Microsoft shipped SQL Server 2008
Service Pack 1, which provides updates to
the relational database management
system, but no new features.

ASP.NET MVC Now Open Source


Microsoft released the source code for
its ASP.NET Model-View-Controller
under the Open Source Initiativerecognized Ms-PL.

BY KURT MACKIE

BY JEFFREY SCHWARTZ

LOCATOR+ CODE: VS0905RD2

LOCATOR+ CODE: VS0905AD2

BY KARL E. PETERSON
LOCATOR+ CODE: VS0905KP1

Inside VSTS
Adding Events to User Controls: To fully
exploit User Controls, you need to treat
them as objects, which includes having
them fire events. This is a step-by-step
guide.
BY PETER VOGEL

Microsoft Q&A: How Does Oslo Fit


with Visual Studio 2010?
Microsoft Senior Product Manager Kris
Horrocks talks about Redmonds views
on model-driven development and how
the Oslo modeling platform fits into
that vision.
BY KATHLEEN RICHARDS

New Eclipse-Based Tools


Reach for the Clouds
Amazon, Salesforce.com and Oracle
are among those that have released
new tools at the annual EclipseCon
conference.
BY JOHN K. WATERS
LOCATOR+ CODE: VS0905AD3

LOCATOR+ CODE: VS0905RD3

VisualStudioMagazine.com

RedDevNews.com

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

ADTmag.com

ISTOCKPHOTO.COM

LOCATOR+ CODE: VS0905PV1

Project1

4/9/09

11:08 AM

Page 1

r
5 4 ou
#5 y
o
at
s o t h int .
s
tu o s
s i b ap t i o n
vi d
e hE m c a
m c dd pli
e
Co f t T o a a p
t
so w ht
ro o g
ic h rli
M arn lve
i
le S

to

Integrate Mapping and GIS into Your Applications


Give your users an effective way to visualize and analyze their data so they can make more informed
decisions and solve business problems.
By subscribing to the ESRI Developer Network (EDN ), you have access to the complete ESRI
SM

geographic information system (GIS) software suite for developing and testing applications on
every platform. Whether youre a desktop, mobile, server, or Web developer, EDN provides the
tools you need to quickly and cost-effectively integrate mapping and GIS into your applications.

Subscribe to EDN and leverage the power of GIS to get


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

Copyright 2009 ESRI. All rights reserved. The ESRI globe logo, ESRI, EDN, and www.esri.com are trademarks, registered trademarks, or service marks of ESRI in the United States, the European Community, or certain
other jurisdictions. Other companies and products mentioned herein may be trademarks or registered trademarks of their respective trademark owners.

0509vsm_Letters_6.v4

4/17/09

11:48 AM

Page 6

Letters

VisualStudioMagazine.com
May 2009 Volume 19 No. 5
Editorial Staff
Vice President, Doug Barney
Editorial Director
Editor in Chief

Michael Desmond

Executive Editor

Kathleen Richards

News Editor

Whats Old Is
New Again
Each month, Andrew Brust writes the Redmond Review column for the back
page of Visual Studio Magazine. His first column since arriving from the pages of
Redmond Developer News focused on the late change of heart Microsoft had
regarding its SQL Data Services cloud-based data storage scheme. Longtime
VSM contributor Roger Jennings responds to Brusts column in a blog posting.

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 Media
Editor, VisualStudio Becky Nagel
Magazine.com
Executive Editor, New Media
Online News Editor
Associate Editor, Web

Andrew Brusts Whats Old Is New Again column for Visual Studio
Magazines April 2009 issue recounts the history of Visual Basic 3.0s adoption
of the Jet (Access) 1.1 relational database and the parallel with the SDS teams
course reversal from the Entity-Attribute-Value data model to a full-featured
relational database. Andrew concludes:
So Redmond listened to its customers, and the bizarre obsession with
copying Amazons SimpleDB Web service is over. Microsoft has given us a truly
simple offering: the SQL Server technology that most Microsoft developers have
been using for a decade and some have been using since even before my first
column was published.
I couldnt agree more.
P.S. Andrew and I started writing for Visual Studio Magazines predecessor
about 15 years ago when it had just been re-named from BASIC Pro to Visual
Basic Programmers Journal.
Roger Jennings
Principal, OakLeaf Systems
Oakland, Calif.
On the New Redesign
VSM redesigned its cover and pages with the April 2009 issue. A reader shares
his thoughts.
I want you to know that I'm totally offended by Aprils 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 my
subscription immediately.
Dennis Parks
Beaverton, Ore.

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

VISUAL STUDIO MAGAZINE May2009 VisualStudioMagazine.com

Jeffrey Schwartz

Managing Editor

Web Producer

Michael Domingo
Kurt Mackie
Gladys Rama
Shane Lee

Director, Web Development

Rita Zurcher

President

Henry Allain

Vice President, Publishing


Director of Marketing
Online Marketing Director

President &
Chief Executive Officer
Senior Vice President
& Chief Financial Officer
Executive Vice President

Vice President, Finance


& Administration
Vice President, Digital Media,
Audience Development

Matt N. Morollo
Michele Imgrund
Tracy S. Cook

Neal Vitale
Richard Vitale
Michael J. Valenti

Christopher M. Coates
Abraham M. Langer

Vice President, Information


Technology & Web Operations

Erik A. Lindgren

Vice President, Digital Media,


Advertising

Doug Mashkuri

Vice President,
Attendee Marketing
Chairman of the Board

Carmel McDonagh

Jeffrey S. Klein

REACHING THE EDITORS


Editors can be reached via e-mail, fax, telephone or mail.
A list of editors and contact information is available at
VisualStudioMagazine.com.
E-mail: E-mail is routed to individuals desktops. Please use the
following form: FirstnameinitialLastname@1105media.com.
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 Magazine
The opinions expressed within the articles and other contents
herein do not necessarily express those of the publisher.

Project3

3/18/09

9:10 AM

Page 1

0509vsm_DevDisasters_8.v5

4/17/09

11:51 AM

Page 8

S E RVE D U P BY A L E X PA PA D I M O U L I S

</DevDisasters>
{ SOFTWARE DEVELOPMENT GONE WRONG }

Gatekeepers of Bad Software


The HR department at a financial services
firm wanted to hire GlobalComp to build a
Web portal.
Getting approval was straightforward: the purchaser set up a meeting between GlobalComp and an integration services developer on the IT
team, and then waited a few days.
After a brief spiel from the
GlobalComp sales rep, Steve
opened with a softball question:
Is it secure?
Of course its secure, the
rep said. At GlobalComp we take
security very seriously. In fact, our
pages are delivered over Secure
Socket Lay
Wait a sec, Steve cut him off, as
he played around with the Web portal. I
think I just broke into your admin console.
The GlobalComp rep stumbled through
an apology. It was clear that the developers
had never anticipated someone typing ' OR
''=' in the password field. Steve thought
itd be a good idea to do a code review to see
what else they had missed.

A Code Tour
Before Steve was permitted to even talk to a
developer at GlobalComp, they had him sign a
an NDA. As an added security measure, Steve
could only review the code while the immaculately dressed Dave, GlobalComps lead developer, watched him. Youd be surprised, Dave
said in a serious tone, there are a lot of people who would steal our software ideas.
Steves first port of call was login.asp.
But it wasnt the security snafus or the
FrontPage meta-tags that caught his eye.
Not only were they using Access, but they
had come up with a rather interesting way of
caching huge amounts (400K+) of user-specific info. They used the ASP Session object:
<%
set cn = Server.CreateObject(_
"ADODB.Connection")

session("HTML_BLOCK_1") = rs("html1")
180 columns later
session("YET_ANOTHER_FIELD") = _
Rs("yet_another_field")
Rs.MoveNext
loop
rs.close
cn.close
%>

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.EOF
session("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")

I cant help but notice


that this is in ASP, Steve said to
Dave. Im curious: why not .NET?
Do you have a lot of ASP libraries that
youre reusing?
Its 2006, Dave snapped back, not
2015. Everyone knows that .NET hasnt
really taken off yet. Its slow, difficult to
code and very buggy. Maybe in a few years
well consider it, but until then, ASP is far
quicker and more powerful.
For optimization, Steve commented,
wouldnt it have made sense to go with
SQL Server? This portal is meant to be used
by thousands of users across the country.
Do you think Access is up to the job?
Whats wrong with Access? Dave
defensively questioned. When I was at
Accenture, we used it all the time.
Steve had seen enough. In light of the
numerous performance, security and dataintegrity issues, his review read, we do not
approve GlobalComps Web portal software
for use in our production environments.
It was the first time anyone in the
department had ever given a non-approval
for vendor software. They felt relieved to
have successfully acted as the gatekeeper
of bad software. VSM

Tell Us Your Tale


Each issue Alex Papadimoulis, publisher of the popular Web site The Daily WTF (thedailywtf.com),
recounts first-person tales of software development gone terribly wrong. Have you
experienced the darker side of development? We want to publish your story. E-mail your tale
to Executive Editor Kathleen Richards at krichards@1105media.com and put DevDisasters
as the subject line.

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

Project3

4/15/09

12:46 PM

Page 1

The World Leader in Imaging Development SDKs


Document

Form Recognition & Processing

Barcode

Mark-up

DICOM Medical

Multimedia

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.

LEADTOOLS v.16 .NET, WPF, WCF, WF, C API, C++ Class Lib, COM & more!
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 LEADs 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-threaded
recognition with formatted output including PDF, DOC and
TXT for Win32 and x64.
Barcode: Read/write all industry standard 1D and 2D barcodes (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 builtin 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 DICOM
messaging and secure communication enabling quick
implementation 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.

LEADTOOLS SDKs feature LEADs iCompress Technologies.


Free 60 Day Evaluation! www.leadtools.com/vsm
866-530-3399

0509vsm_DevInsight_10-12.v5

4/17/09

12:12 PM

Page 10

DEVELOPER NEWS /// REVIEWS /// PRODUCTS

</DevInsight>
DEVELOPER NEWS

Tech-Ed

Is the Visual Studio 2010 beta finally here?


BY KATHLEEN RICHARDS

Microsofts TechEd North America 2009 confab this month is


expected to center around Windows 7, Windows Server 2008
R2, Exchange 14 and the numerous technologies that the company has rolled out during the last 12 to 18 months.
Registered attendees will receive the latest versions of
Windows 7likely the first release candidate (RC)and Windows
Server 2008 R2. As part of an included TechNet Plus annual subscription, conference goers will also receive licensed copies of the
technologies when they first become available later this year.
For developers, the annual conference will offer more than
a sneak peek at Visual Studio 2010, which is close to beta 1;
the last preview bits were offered in October at Microsoft
PDC2008 and expired in January. According to multiple sources,
Microsoft is targeting TechEd for the beta 1 release.
SQL Server Kilamanjaro, the upcoming business intelligence (BI) release that enables users to create reports using
SharePoint and Excel, will be highlighted during the keynote for
the database platforms and BI tracks, which are targeted at both
developers and IT professionals.
Usually TechEd is not hugely filled with beta technology
sessions, so the fact that some of these things that are a little
prerelease are kind of coming out shows that theyre either closer
to market or more important, says Stephen Forte, chief strategy
officer at Telerik Inc. Forte is leading several TechEd sessions,
including a drill-down on SQL Server 2008 with Richard Campbell,
co-host of .NET Rocks.

10

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

Despite the anticipated releases, TechEd is facing the same hurdles that conferences in every industry have encountered during
the recession: attendance issues. The conference will take place
at the Los Angeles Convention Center, the same venue as last
years PDC. After a two week TechEd in Orlando, Fla., in June
2008 that separated the developer and IT tracks, Microsoft is
back to a combined, one-week model. Last years event, which
marked chairman Bill Gates last official keynote, attracted
around 5,000 developers and 10,000 IT professionals, according
to Microsoft.
The current climate has meant some unwelcome
changes: In April, registrants were notified of the cancellation
of on-site exams for Microsoft certifications, the traditional
Thursday night attendee party and the popular Jam
Sessions that occurred nightly at past TechEd events.
The Server and Tools News Bytes blog on Microsoft
TechNet recommended the press attend the show virtually
this year, noting that there would be limited access to
Microsoft executives and on-site facilities.
The cutbacks are not a reflection on Microsoft or
TechEds robust technical content. Generally, Im hearing
conferences are just not being as well attended for obvious
reasons this year, says Rob Sanfilippo, research vice president
of developer platforms at Directions on Microsoft. Looking
across at MIX, TechEd and PDC, I definitely would rank PDC as
the first conference to attend from a developer standpoint for
someone thats interested in planning technology that will be
used two or three years out for their organization.
PDC2009, which is expected to focus on the release of
Microsofts cloud-computing platform, Windows Azure, is
scheduled for Nov. 17-20 in Los Angeles.
LOTS TO LEARN

Despite the troublesome economy, Microsoft received a record


number of more than 1,600 submissions for technical sessions
from inside and outside of the company, according to a post by
Brian Marble, worldwide TechEd lead. That has been whittled
down to 20 tracks, with about 440 breakout sessions and 200
or so hands-on labs. The theme this year is Potential Lives
Here, and the focusas in years pastis on technical education,
community and product evaluation.
Windows 7 is the clear headliner at TechEd. The
Windows Azure Services Platform will also get some play with
26 sessions, although the licensing and pricing structure
information that could definitely spur serious interest among
decision makersis expected to remain under wraps until later
this year.
TechEd will also be the first conference stateside to offer
plenty of information for developers interested in Windows

ISTOCKPHOTO.COM

TechEd Preview

REALITY BYTES

0509vsm_DevInsight_10-12.v5

4/17/09

12:12 PM

Page 11

REVIEW

Kathleen Richards (krichards@1105media.com) is


executive editor of Visual Studio Magazine and
editor of RedDevNews.com.

Sybase PowerDesigner
Data Modeling
Eliminate data model archeology by analyzing your enterprises
systems to find out where data is actually being used.
BY PETER VOGEL
Sybase Inc.s goals for
PowerDesigner are nothing if not
ambitious: a single modeling tool for

tracking data definitions everywhere


in an organizationand Sybase
doesnt just mean databases when it
says data. Sybase PowerDesigner can
also model data represented in XML
schemas (including .WSDL files),
process languages (BPEL and
ebXML), object definition languages
(Visual Basic, C#, Java, IDL-CORBA)
and even .XLS files, among other
choices. In addition, PowerDesigner
supports virtually every notation
available, including the popular UML
and IDEF1X notations. Heck,
PowerDesigner even supports
CODASYL, a notation that I used
when I started doing database design,
way back in 1982.
Data modeling serves two purposes: generating database schemas
and documenting data stores. I used
PowerDesigner to generate a SQL
Server database drawn from one of
my clients projects. With a tool as
powerful as PowerDesigner, theres
always a danger that doing the simpler things will become unnecessarily
complicatedI didnt find that with
PowerDesigner. I was able to add a
model to one of my existing Visual
Studio projects and generate a data-

base shortly after installing the product (you can also create standalone
PowerDesiger modeling projects in
Visual Studio). PowerDesigner isnt
limited to generating just database
schemas: You can also generate BPEL
process files and nHibernate code,
among other options.
The other purpose of data modeling is documenting data stores,
which is only valuable if you can use
your models to support developers,
make business and design decisions
and to analyze business problems.
PowerDesigner supports creating
reports 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 object
and follow its links to see where the
data item is useda powerful tool
when someone asks you,What would
it cost to change this?
Of course, the ability to follow
those links is only useful if all of
your data stores are documented
in PowerDesigner. I found
PowerDesigners reverse engineering
facilities to be robust and complete for
the various data stores that I tested
against. While I tested against the

Data Modeling

Mobile, which will be covered in 31 sessions.


Stephanie Ferguson, general manager of
business experiences at Microsofts Mobile
Communications Business, is scheduled to
give whats being described as the kickoff
launch of Windows Mobile 6.5 on May 11.
As in years past, TechEd covers a
broad swath of Microsofts technologies,
including Office and SharePoint, serviceoriented architecture and business process,
virtualization, Windows Client, Web and
user experience, developer practices and
developer tools, languages and frameworks.
For developers, that means educational
sessions on recent Windows, Web and rich
Internet application announcements such as
Windows Presentation Foundation (WPF),
ASP.NET MVC, JQuery, Silverlight, .NET 4.0, the
upcoming Dev 10 languages and the Oslo
modeling platform. A new Oslo community
technology preview is anticipated in the
TechEd time frame.
Rockford Lhotka, principal technology
evangelist at consulting firm Magenic
Technologies Inc., is leading a Silverlight
session on building line-of-business apps.
I think were all hoping that Visual
Studio 2010 is going to have the designer
support for Silverlight and WPF that kind of
unlocks the door, he says. Its very clear
that the future of Windows UI development
is WPFthats where Microsoft is putting all
of their energyand theyre putting even
more energy into Silverlight. Now is the time
that people really need to start looking at
them in some depth with the anticipation
that were going to get the tooling with
Visual Studio 2010, Lhotka adds.
Sanfilippo, who attended MIX09 in
March, is skipping TechEd this month. I think
TechEd is really between the big announcements this year, and also its really focused
more on IT training than developer
announcements, he explains.
Despite the economic slowdown and
some cutbacks at the event, most agree
TechEd still ranks among the largest
opportunities to interact with Microsoft
representatives and the IT community.
For the first time in the shows 16-year
history, registered attendees will receive
access to the Global TechEd Content Library,
which includes TechEd Europe, the Middle
East and Africa (EMEA). TechEd Europe, a
one-week event for developers and IT, is
Nov. 9-13 at the Messe Convention Center
in Berlin. DI

PowerDesigner allows you to create a conceptual model using a variety of


modeling notations and, from that model, generate a physical database design
for almost any RDBMS.

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 11

0509vsm_DevInsight_10-12.v5

4/17/09

12:12 PM

Page 12

</DevInsight>

Database Tools

standard Microsoft tools (SQL Server and


Access), PowerDesigner also supports
Oracle, DB2 and MySQL (again, among
other database engines).
Given its pricing and functionality,
PowerDesigner is not for the faint
heartedand its also not for those
with limited goals. If all you need is a
database design tool for your organizations RDBMS, PowerDesigner is far more
tool than you need. But if you want to

SYBASE POWERDESIGNER 15
Sybase Inc.
www.sybase.com
800-792-2735

create a repository for analyzing your


organizations data usage, PowerDesigner
will do the job. DI
Peter Vogel (peter.vogel@phvis.com) is a principal
in PH&V Information Services, specializing in
ASP.NET development with expertise in SOA,
XML, database and User Interface design. Hes
written several books on application development using Microsoft technologies and presents
at conferences around the world.

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


seat
Quick Facts: One-stop shopping for
data modeling and analysis using a
variety of notations.
Pros: High functionality with
support for all the tools that Microsoft
developers use.
Cons: Expensive; PowerDesigner is a
big tool to handle big problemsnot a
tool for developers just needing a database modeling tool.

PRODUCTS

Test Center Standard Edition


and Connect ODBC 6.0
LOWER COST APM

Two months after releasing an application performance management (APM) suite that ranges in price from $30,000 to $60,000,
Linz, Austria-based dynaTrace Software is now offering a scaleddown 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 suites price.
That full-scale suite is designed to let developers trace
transactions across geographically distributed systems with large,
scalable virtualized server clusters for business-critical applications that require 24x7 uptime (for more on that release, see
http://tinyurl.com/csvyn2).
Like the larger version, the Standard Edition comes with Visual
Studio, Visual Studio Team System Test Edition and Eclipse plug-ins.
It diagnoses and isolates typical Web application issues, notably
database performance problems and chattiness. The software also
documents issues for developers including SQL statements and bind
values, and various other transaction characteristics. The software
takes every transaction and displays the slowest running ones or
those that are broken. When the developer clicks on a transaction,
he can view the whole path with all the context. If a developer
sees hundreds of extra calls to a database, he can click on it and
automatically open up the source code in Visual Studio.
Although not as well known as some of its rivals, dynaTrace
says it has made inroads in the U.S. market over the past year with
customers such as Bank of America, Fidelity Investments, LinkedIn
and Macys. It has 100 customers but has seen rapid growth in recent
quarters, the company says. But dynaTrace, which is backed by Bain
Capital and Bay Partners, is a much smaller player than market leader
CA, whose Wily Technology is used by more than 1,000 customers.
Test Center Standard Edition
dynaTrace Software
Price: $6,000 per developer license
www.dynaTrace.com
781-674-4000

12

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

Developers can examine code to trace transaction bottlenecks


through the dynaTrace Visual Studio plug-in.
DRIVING ODBC HARDER

Looking to give a boost to applications that rely on Microsofts


Open Database Connectivity (ODBC) standard, DataDirect
Technologies has updated its drivers.
The new DataDirect Connect for ODBC version 6.0 increases
the speed at which data is loaded into an application or into a
database, says Rob Steward, the companys vice president of R&D.
It allows for exporting of data from one database into another and
performs bulk transfers without having to use Microsofts batch
processing utility.
Existing batch processes will run faster without requiring
changes to application code, he adds. Version 6.0 adds application
failover: The features will allow developers to better tune their
applications, he explains.
In addition to Microsofts SQL Server, DataDirects ODBC drivers
provide connectivity to databases from Oracle Corp., IBM Corp. (DB2
and 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 Progress
Software Corp., is among a handful of companies that provide
ODBC drivers. Most leading database vendors offer their own
ODBC drivers and there are a number of less-expensive, open
source alternatives as well. DataDirect says its drivers are aimed
at ISVs and large enterprises. DI
Connect for ODBC 6.0
DataDirect Technologies
Price: $4,000 per single core
www.datadirect.com
800-876-3101

Project2

4/1/09

11:55 AM

Page 1

4/17/09

12:21 PM

Page 14

ILLUSTRATION BY RYAN ETTER

0509vsm_F1_14-22.v6

14

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

0509vsm_F1_14-22.v6

4/17/09

12:21 PM

Page 15

TECH-ED 2009

FEATURE

HEADWINDS
Despite tough times, developers, ISVs
and Microsoft are keeping plenty busy.
BY MICHAEL DESMOND

When the going gets tough, the tough get going. At least,
thats 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, its
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 TechEd North America 2009 in Los
Angeles this month.

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 15

Project6

4/7/09

4:11 PM

Page 1

Project6

4/7/09

4:12 PM

Page 2

SURROUNDED, UP AGAINST IT, AND FALLING BEHIND.


YOU NEED A TEAM SYSTEM.

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

0509vsm_F1_14-22.v6

FEATURE

4/17/09

12:21 PM

Page 18

TECH-ED 2009

We polled 369 developers for their


thoughts on the .NET dev arena.
Heres what they said:
WHATS YOUR READ ON THE DEVELOPMENT MARKET
FOR THE SECOND HALF OF 2009?
Difficult
Hopeful
Neutral
Terrible
Terrific

39%
29%
23%
4%
4%

HOW IS YOUR ORGANIZATION APPROACHING


APPLICATION DEVELOPMENT?
Working on existing projects and app
maintenance only
Moving forward to adopt new platforms and
technologies
Embracing Agile development methodologies
Adopting more open source platforms and
development tools
Investigating cloud computing options
Outsourcing

32%
31%
13%
9%
8%
7%

DO YOU SENSE DEVELOPER FATIGUE DUE TO THE PACE


OF MICROSOFT TECHNOLOGY INTRODUCTIONS?
Yes, some fatigue
No, little or no fatigue
Yes, significant fatigue
Dont know

45%
26%
24%
5%

IS YOUR ORGANIZATION SPECIFICALLY TARGETING


DEVELOPMENT FOR THE WINDOWS 7 CLIENT OS?
No
Yes, but it will take time
Yes, but only limited development
Yes, aggressively

60%
23%
14%
3%

Attendees certainly wont be staying away for lack of things


to explore at the four-day conference, which combines IT and
development tracks focused on Microsoft platforms, services
and products. On the dev side, TechEd arrives as a host of strategic Microsoft development technologies emerge. From Azure
cloud computing to Silverlight 3 Web development to the anticipated beta of Visual Studio 2010,TechEd offers a chance to catch
up on the latest Microsoft-driven dev technologies.
No surprise, independent tool companies are busy as well,
as they rush to fill gaps in Microsofts expanded dev platforms
and tap powerful, new features in the latest versions of .NET
Framework, Silverlight, Visual Studio and ASP.NET.
Nowhere to Hide:
Developers Test Strategies in a Terrible Market
A market report by research firm Gartner Inc. provided grim
context just six weeks ahead of the May TechEd confab.
18

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

According to the March 31 report, worldwide spending on information technology was expected to fall 3.8 percent in 2009, to
$3.2 trillion from $3.4 trillion. That decline, Gartner Research
Vice President Richard Gordon notes, would be worse than the
2.1 percent reduction the industry weathered in 2001 during the
dot-com bubble burst.
Ask Julian Bucknall how his company, .NET component
maker Developer Express Inc. plans to get through the dour
economy, and he is refreshingly candid.
The economy being what it is, weve concentrated a lot on
making our current customers happy, says Bucknall, the companys chief technology officer, who notes the importance of
Developer Express subscription model. The only way we could
encourage people to stick with us is to concentrate an awful lot
on stability, reliability, discoverabilitymaking things easier and
more stable to use, and then adding more functionality when we
feel its necessary.
Like many rank-and-file dev shops, Bucknall says
Developer Express has decided to pick its spots carefully, investing in select areas and emphasizing maintenance and refinement
over lavish new initiatives or product launches. Its an approach
being repeated all over the development sector.
2009 is seriously quite a tough year, but I suspect for most
people it will be just carrying on doing what theyre doing, says
Bola Rotibi, principal analyst at research firm Macehiter
Ward-Dutton (MWD). Outside of the core areas of keeping the
business going, I think [new initiatives] are going to be few and
far between.
Our survey of more than 350 .NET developers ahead of
TechEd bears out the cautious, go-slow approach. Asked about the
biggest challenge facing their organizations, the largest percentage
of respondents singled out the economy (32 percent). The
second most-cited response was the challenge of managing all the
developer technologies coming from Microsoft (23 percent). No
other response drew more than 8 percent of the vote.
Many dev shops report falling back into maintenance
mode. Im 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 insurance
carrier says his group is trying to do more with less. In the
health-care insurance sector, were still actively trying to handle
new projects from the business, but with smaller dev staff, or at
least fewer subject-matter experts.
While 32 percent of survey respondents report limiting work
to 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 large
number of VB 6.0 and legacy ASP applications to help ramp some
of the newer or more junior staff up with the latest Microsoft dev
technologies, the solutions architect says.
A lot of developers are concerned about their ability to
adopt and master all the new technologies Microsoft has been
rolling out. Survey respondents indicate excitement about
inbound tooling like Visual Studio, .NET Framework 4.0 and
Windows 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.

0509vsm_F1_14-22.v6

4/17/09

12:21 PM

Page 19

TECH-ED 2009

FEATURE

The staff is concerned about the ability to learn and apply were going to be concentrating on with regard to Silverlight. What
new technology in products that have a solid base of code, says the you call the business control.
A lot of firms are also looking at how they license and sell
vice president of engineering for a telecommunications consulting
firm. Our market problem is we need to maintain compliance software. Microsoft at the MIX09 conference in March demoed
with .NET 2.0, .NET 3.5, multiple versions of SQL Server and mul- the Web Platform Installer, which bundles together a complete
stack of Microsoft-based Web server products and technologies
tiple operating systems.
A Web application developer for a large construction and and provides an easy-to-use installer interface.
MWDs Rotibi calls the Microsoft utility a neat little soluengineering firm says his shop is busy, but risks falling behind in
the adoption of new technologies.Our biggest challenge is not the tion that portends things to come. She points to the All-Access
economy, but rather maintaining our
suite of Web applications (hundreds!) and
at the same time keep up with the pace of
technology, he says. We essentially fall
further and further behind every year.
Our most heavily used apps are classic
ASP, we have many .NET 1.1 apps, and a
sprinkling of .NET 2.0 apps. Our databases have been recently upgraded to SQL
Server 2005, he says.
One major .NET component maker
isnt surprised at these struggles:
Microsoft has been really aggressive
with new products and releases over the
past one to two years, and some of [our]
customers are finding it difficult to keep
pace with all the new technologies and
are sometimes confused [about] whats
best to use for their projects.
Anthony Lombardo, lead evangelist for component maker Infragistics
and a Microsoft MVP, says developers
need to be smart to avoid getting overwhelmed. Just keeping track of all of
the different code names can be a chore.
The main thing for developers to do is
focus on the technologies that are
Powerful Imaging for .NET
important to them.
Slowdown Strategies
Corporate dev shops arent the only ones
struggling to keep pace. Developer
Express Bucknall says his company has
made the decision to focus tightly on
Silverlight for its next component launch,
rather than aggressively update its suite
of ASP.NET, Windows Presentation
Foundation (WPF) and new SharePoint
controls. Case in point, Developer Express
is updating its Express App Framework
(XAF) for Silverlight.
What XAF does is very quickly allow
you to write business applications just by
defining a data model, says Bucknall, noting that Developer Express has added grid,
navigation, reporting and menu controls
to its Silverlight suite. XAF requires a certain number of controls before you can
generate an application. So now well be
able to write a business app for Silverlight
and WPF. Those are the kind of things

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

www.atalasoft.com

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 19

0509vsm_F1_14-22.v6

FEATURE

4/17/09

12:21 PM

Page 20

TECH-ED 2009

service provided by database tools vendor Embarcadero


Technologies 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 and
deploy Embarcadero products from an online console. The
InstantOn feature enables access to Embarcadero tooling without installation.
Its about reducing friction and getting the integration particularly strong. Its about the different tools, Rotibi says. Being
able to download and manage a whole series of things in an
instant, thats the next stage.
At SAP AG, the company recently overhauled the licensing
around Crystal Reports, providing a simple, flat-rate license for
companies wanting to distribute Crystal Reports functionality in
software they intend to sell or distribute. The new approach
replaces a complicated scheme, whereby ISVs had to obtain a
separate license for each distributed instance of an application
containing Crystal Reports.
We found that there are tens of thousands of ISVs out there
who were building their own reporting because they felt it was
too expensive to work with a company like us, says James
Thomas, vice president of product management in the Volume
Business Unit at SAP. He cites rapid application cycles, an
increasing mix of software and services, and pressure from open
source competition for the switch.
More and more companies are looking hard at licensing and
compliance practices as a way to face down budget challenges and
ease management overhead. Jon Gillespie-Brown, chief executive
officer at licensing services firm Nalpeiron, says ISVs are scrambling
to adopt subscription models as a way to ensure constant revenue
and provide a lower barrier to entry for customers.
I think that the end user is clearly pushing very hard for a
more flexible way to buy, Gillespie-Brown says.
He adds that customers are attracted to the pay-as-you-go
nature of Nalpeirons hosted license management and tracking
features. But what customers are looking for, says GillespieBrown, are more streamlined ways to track and secure licensed
software, and to provide feature-complete trial software without
having to support multiple code bases. I think the perpetual
[license] model is close to dead, personally.
Touring TechEd
For all the sturm und drang of the current recession, its clear
from talking to ISVs and dev tool companies that .NET tools
development remains an active endeavor. A lot of that has to do
with Microsoft, of course. Companies like Developer Express,
Infragistics and ComponentOne LLC are constantly rushing
around 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 their
plans for the May TechEd event. Heres what we learned:

controls designed to help developers craft line-of-business applications using Microsofts RIA platform. Included in the package
are data grid, Web tree, dialog window and other controls.
www.infragistics.com
Altova MissionKit 2009

Few companies know XML the way Altova does. As if to make the
point, Altova in February began bundling its broad suite of XML
and data manipulation tools under the MissionKit banner, creating
a one-stop shop for .NET developers. At Tech-Ed, Altova plans to
demo MissionKit Tool Suite version 2009, which now supports
Extensible Business Reporting Language (XBRL) data in XMLSpy,
MapForce, and StyleVision. Version 2009 also lets developers work
with Health Level 7 messages in the MapForce module.
www.altova.com
Resco MobileForms Toolkit 2009

Resco MobileForms Toolkit 2009 bundles developer components


and tools for applications developed for Microsoft .NET Compact
Framework 3.5. The latest version adds tooling for touch interfaces,
polished UI support and a trio of new app components including
tab, tooltip and toolbar controls. MobileForms Toolkit 2009 supports Visual Studio 2008, 2005 and 2003.
www.resco.net
The Imaging Source TX TextControl 15.0

The TX Text Control family of word processing components for


Visual Studio 2005 and 2008 has been updated to add support for
Adobe .PDF file format export, enabling Microsoft Word and compatible documents to be viewed and filled out in any browser.
According to The Imaging Source, completed forms can be
processed server-side and then printed or saved as PDF documents.
Improved support for columns and structured numbered lists has
been added. The Imaging Source is also distributing TX Text
Control RapidSpell .NET, a spell check add-on for TX Text Control
currently supporting English and German dictionaries, with additional languages and specialist dictionaries expected.
www.textcontrol.com
PureCM 2009-1

Source control management (SCM) toolmaker PureCM.com has


a new version of its eponymous product, PureCM 2009-1, that
aims to enable parallel development for cash-strapped organizations. With a newly streamlined interface and supporting agile
methodologies, PureCM is available for Windows, Linux and
Mac OS environments and integrates with the Visual Studio and
Eclipse IDEs. The new version adds real-time tracking and guidance for managing merged changes. PureCM says its tooling can
scale up to thousands of end users and manage terabytes of
dataenough to handle enterprise-scale development.
www.purecm.com
REALBasic 2009 Release 1 and REAL Studio

Infragistics NetAdvantage for Web Clients: Silverlight

Leading component maker Infragistics is rolling out a new spin


on its NetAdvantage line of components, this one aimed at developers working with Silverlight 3, which is currently in beta. The
NetAdvantage for Web Clients Silverlight toolset offers advanced
20

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

Sure, Silverlight 3 promises to let you take your mad Visual


Basic.NET skills cross platform. But open source toolmaker
REAL Software offers another optiona cross-platform tool and
version of the Basic programming language (called, you guessed
it, REALbasic) that lets developers work onand create applica-

0509vsm_F1_14-22.v6

4/17/09

12:21 PM

Page 21

TECH-ED 2009

tions forWindows, Linux and Mac OS. REALbasic 2009


Release 1 adds ease-of-use tweaks like a Quickstart window to
help attract new users, as well as a host of improvements
designed to improve reliability.
A more robust version of the tooling released in April, called
REAL Studio, targets full-time developers and adds features like a
Profiler for optimizing performance and scripted build automation.
www.realsoftware.com

FEATURE

Nalpeiron aims to help ISVs streamline operations and better


communicate with potential customers, with its updated, hosted
suite of licensing services. New to Nalpeirons offering is the
TrialMaximizer feature for presenting e-mail campaigns and
HTML advertisements to users using a firms product under a
trial license. The OverdraftTracker module promises to give ISVs
a glimpse into hidden customer demand. ISVs can flexibly con-

Nevron .NET Vision Q3 2008

. N E T co m p o n e n t m a ke r Ne v ro n
Software boasts a large collection of
chart, diagram and UI controls for
Windows Forms and ASP.NET (including AJAX) application development. All
three component families are currently
available as part of the companys all-inone Nevron .NET Vision Q3 2008 component suite, which may see a major
upgrade by the time this issue reaches
your hands. The new package, reportedly
due out at the end of April, is set to introduce new charts, gauge, diagram and
mapping features. .NET Vision comes in
two editions, Pro and Enterprise.
www.nevron.com
Telerik WebUI Studio

Telerik specializes in making UI controls


for a wide range of Microsoft and .NET
platforms, including ASP.NET AJAX,
Silverlight, WinForms and WPF. The
company recently announced that its
RadControls for ASP.NET AJAX product
fully supports the open source Mono
runtime environment for enabling .NET
applications on Linux and Mac OS platforms. Now Telerik adds WebUI Test
Studio to its RadControls for ASP.NET
AJAX. The automated testing module
uses the ArtofTest Automation Design
C a nv a s a n d We b Ai i Au to m a t i o n
Framework (reviewed in the April issue
of Visual Studio Magazine) to let developers create and run tests across Internet
Explorer and Firefox browser platforms.
Support for Safari and Google Chrome
browsers is expected soon, and Telerik
says Silverlight support will be added in
the next release. WebUI Test Studio integrates with Visual Studio Professional
and Visual Studio Team System.
www.telerik.com
Nalpeiron Licensing Service

Tough times demand tough choices


when it comes to paying for software and
services. Licensing solutions firm
VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 21

0509vsm_F1_14-22.v6

FEATURE

4/17/09

12:21 PM

Page 22

TECH-ED 2009

The economy being what it is, weve concentrated a lot on making


our current customers happy. Making things easier and more
stable to use, and then adding more functionality when we feel its
necessary. Julian Bucknall, Chief Technology Officer, Developer Express Inc.
figure their software so that locked feature and capabilities can be
activated by users, giving the ISV the ability to market against the
extended demand.
www.nalpeiron.com
VNI pyIMSL Studio

According to the old saw, there are lies, damned lies and statistics.
Visual Numerics Inc. aims to help developers remove statistics
from that troubling equation, by providing a numerical analysis
application development environment that developers can use to
leverage mathematics and statistics to prototype models in their
production applications. Released in April, PyIMSL Studio closes
the prototype to production gap by providing modelers and
implementation teams with a common set of tested and supported high-quality development tools, as well as the same underlying
numerical algorithms, the company said in a statement. PyIMSL
Studio helps developers turn prototypes into production applications quickly, while reducing risk, cost and complexity.
www.vni.com
ComponentOne XapOptimizer

Microsoft has been banging the Silverlight drum for what seems
like years now, and we can expect to hear plenty about the line-ofbusiness savvy Silverlight 3 at TechEd. ComponentOne is helping
with the drum beating with a show promotion around the community technology preview release last month of ComponentOne
XapOptimizer. A standalone utility that processes Silverlight application .XAP files, XapOptimizer generates optimized Silverlight
application files that are 30 percent to 70 percent smaller in size
than the original .XAP files. XapOptimizer integrates into the build
process in Visual Studio and includes the ability to obfuscate
Silverlight code.
www.componentone.com

establish rich interaction among applications, data and components. A component maker specializing in WCF controls,
Noemax Technologies in April released WCF-Xtensions version
4, a major update that, in the words of the company,expands the
reach of WCF-Xtensions from .NET and .NET Compact
Framework to Silverlight and Azure. WCF-Xtensions promise to
speed communication and reduce bandwidth consumption of
WCF services and clients. The components can bind quickly to
code 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 companys name implies, JNBridge offers products that


help bridge the gap between Java and .NET components and
applications. JNBridge tools and adapters help speed and simplify
cross-platform interoperability by providing adapters that present
rich Java and .NET interfaces. At TechEd, JNBridge will be showing new updates to the JNBridge Java & .NET interoperability
tool that address WPF.
www.jnbridge.com
Atalasoft Vizit SP

In a struggling economy, one of the few bright spots in .NET


development has been in the area of SharePoint application and
Web Part development. Atalasoft VizitSP is a SharePoint image
viewing module that lets organizations provide rich image
viewing and browsing capabilities on any SharePoint deployment. For more robust development, the DotImage 7.0 .NET
imaging toolkit offers imaging controls for ASP.NET and
Windows Forms application development. DotImage is available in 32-bit and 64-bit versions and supports Visual Studio
2003 and later.
www.atalasoft.com

PreEmptive Solutions Dotfuscator Micro Developer Edition

The Dotfuscator product has for years helped dev shops protect
their distributed .NET code from prying eyesthe community
edition of Dotfuscator baked into Visual Studio is currently on
more than 6 million desktops. More recently, PreEmptive has
gotten into the business of helping developers inject analytics and
lifecycle management tracking capabilities into their apps, allowing
them to track the status and usage of .NET apps among customers.
So whats on tap for TechEd? A new version of Dotfuscator for
mobile developers called Dotfuscator Micro Developer Edition
(MDE), which will ship at the show. The new software will integrate
with Visual Studio and provide injected tamper detection/defense,
application expiry and feature-tracking support.
www.preemptive.com

NCover 3.0

NCover 3.0 is a code coverage analysis toolset for .NET that


targets automated build and test environments with improved
performance, profiling and reporting capabilities. The tooling
consists of an NCover Explorer UI for developers, a build system
console for the build developer and a reporting module aimed
at project managers. Often employed in Agile and test-driven
development environments, code coverage analysis allows developers to monitor what percentage of their source code is actually
touched by unit tests by measuring how many times a line of
code is executed, among other metrics. NCover 3.0 includes 16
new reports and a record trends feature that can be used to
automatically create HTML reports.
www.ncover.com VSM

Noemax WCF-Extensions Version 4

Windows Communication Foundation (WCF) has emerged as


a powerful and attractive target for developers seeking to
22

VISUAL STUDIO MAGAZINE May 2009 www.visualstudiomagazine.com

Michael Desmond (mdesmond@1105media.com) is editor in chief of


Visual Studio Magazine.

Project2

2/11/09

11:06 AM

Page 1

How to boost the performance of your


.NET applications with ANTS Proler
Performance is crucial, so here are some tips to make sure
that your applications run efciently.

or maximum efciency, follow our


three proling tips outlined below.

1. Prole your .NET code


A code proler is an essential
tool to have in your development
toolkit. Although manual logging
can sometimes help, it is often
impossible to nd performance
bottlenecks without a code proler.
A proling tool takes the guesswork
out of performance analysis and
drastically reduces the amount of
time taken to nd problem code.

2. Quickly locate your


performance bottleneck
Run ANTS Proler Pro to obtain
detailed quantitative data that will
help you identify inefcient resource
usage. ANTS Proler gives you hit
count and line-level timings, so you
can quickly identify the specic
lines of code which are affecting the

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

3. Optimize efciently
Now 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.

performance of your application.


No time wasting. No guessing.
Use real data instead!

"ANTS Proler took us


straight to the specic areas
of our code which were the
cause of our performance
issues."
Terry Phillips Sr. Developer,
Harley-Davidson Dealer Systems

"We were able to improve


performance in parts of
the application up to 10 times,
and our customer noticed the
results. A powerful, instantly
understandable proler.
Highly recommended."
Dan Ports Lead Developer, Intrigma Inc

ANTS Proler shows you line-level timings, so you can drill down to the specic lines of code responsible
for performance inefciencies.

Download your 14-day, fully functional


free trial from www.red-gate.com

Project3

3/19/09

9:08 AM

Page 1

Project3

3/19/09

9:09 AM

Page 2

0509vsm_HowTo22-29.v9

HOW-TO

4/17/09

12:30 PM

Page 26

SILVERLIGHT

Silverlight 3 Enables

Data-Driven App Dev


The 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 a
Silverlight-enabled Web browser. BY PETER VOGEL

26

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

0509vsm_HowTo22-29.v9

4/17/09

12:30 PM

Page 27

SILVERLIGHT

HOW-TO

While Silverlight 1 and 2 concentrated on helping developers deliver rich Internet


applications (RIAs), coders building line-of-business (LOB) applications had little to
cheer about. The limited support for data binding and data validation complicated
basic data management tasks in LOB applications. Thats about to change.

ISTOCKPHOTO.COM

As announced in March at the MIX09 conference in Las


Vegas, Silverlight 3 adds a host of data-oriented features that go a
long way toward providing critical support for LOB development. Ill show you how to build a Silverlight 3 client that accesses a Web service to retrieve and update data. My initial version
will be a form that displays a single entity. But by leveraging the
new data binding and validation features in Silverlight 3, Ill
illustrate 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 yourself, you can download the beta from http://tinyurl.com/dcs3fj.
There are two caveats that apply. First: Dont install the beta on a
computer where you want to continue creating Silverlight 2
applicationsinstalling the beta converts Visual Studio to a
Silverlight 3 development tool. Second: This is still a beta release
and no go-live license is available. Any applications you develop
at this point arent supported by Microsoft.
A Sample Application
OK, enough warnings. For this article, I created a
simple Silverlight application that interacts with
a Web service on my server. The application
pulls down a collection of objects representing
Customers entities in the Northwind Database
and displays them in a DataForm .
To create this application yourself, after
installing the Silverlight 3 beta package, select File |
New Project in Visual Studio and choose Silverlight
under the language of your choice (I chose Visual
Basic). From the available Templates, select
Silverlight Application, enter a name for the project
(I used DataDrivenSL) and click the OK button. In
the New Silverlight Application dialog that appears,
change the project type to ASP.NET Web Site before
clicking OK. I got the solution you see in Figure 1: an
ASP.NET Web Site and a Silverlight app.
In the Web site, I added a service with two
methods: one that returns Customer objects
(GetCustomers) and one that, when passed a single Customer object, updates the database with
the values on the object (UpdateCustomer). I
made the .ASPX page my start page. In the
Silverlight app, I knocked together a simple user
interface in the MainPage.xaml file, using a Button
and 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 Customer


entity objects from my Web service, I created an EndPoint object
for my services URL, a variable to hold a reference to my service
and a BasicHttpBinding object. In the Click event for the Button,
I used those objects to retrieve a collection of Customer entities
by calling the GetCustomers method on my service:
Private WithEvents nwd As _

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

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 27

0509vsm_HowTo22-29.v9

HOW-TO

4/17/09

12:30 PM

Page 28

SILVERLIGHT

NorthwindData.NorthwindDataSoapClient
Dim bind As New System.ServiceModel.BasicHttpBinding
Dim 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 Objects


In order to take full advantage of Silverlights new features, you
need an object in your Silverlight application that you can decorate with data-related Attributes. To support that, I created a
LocalCustomer object that duplicated the properties from the
Customer object I want to display in my user interface. For this
example, I defined just three properties: CustomerId,
ContactName, CompanyName. The start of the class, with the
CompanyName property, looks like this:
Public Class LocalCustomer
Private _CompanyName As String
Private _CustomerId As String
Private _ContactName As String
Public Property CompanyName() As String
Get
Return _CompanyName
End Get
Set(ByVal value As String)
_CompanyName = value
End Set
End Property

In order to handle the conversion from the Customer object


(returned from my service) to the LocalCustomer object (used in
my Silverlight project), I would normally create a conversion class.
Alas, the necessary Attribute for conversion classes isnt yet supported for Silverlight 3. Instead, I added code to the event that fires
after the service returns the Customer objects. That code creates a
LocalCustomer object for each Customer object and attaches it to
an ObservableCollection. Once the collection is built, I used the
DataForms CurrentItem property to have it display the first entity
in 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.GetCustomersCompleted
Dim lc As LocalCustomer
For Each cust As NorthwindData.Customer In e.Result
lc = New LocalCustomer
lc.CompanyName = cust.CompanyName
lc.CustomerId = cust.CustomerId
lc.ContactName = cust.ContactName
custs.Add(lc)
Next

28

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

.NET RIA Services


When 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 developers
keen on moving their application logic over the
network to diverse client platforms.

Easing Development
With Silverlight 3, Microsoft seems determined to win
over those business developers for good.
As part of the current Silverlight 3 beta, Microsoft
has released .NET RIA Services, a framework that pulls
together elements of ASP.NET and Silverlight to ease
development of data-centric RIA applications. The RIA
Services pattern lets developers write application logic
to run on the mid-tier that, in a Microsoft statement,
controls access to data for queries, changes and custom operations.
Bob Baker, a Microsoft MVP and president of
MicroApplications Inc., has been working in the
Silverlight 3 early adopter program. He says .NET RIA
Services will change the face of Silverlight development.
This release will approach application development ease for quick line-of-business apps that rivals
what we used to be able to do with Microsoft Access
before macro security and digital signatures got in
the way, he writes in an e-mail exchange. He adds
that .NET RIA Services promises to eliminate what he
calls that dual, object class library thing weve been
doing for a year or so.

Adding Critical Capabilities


The new framework integrates client-side Silverlight
components with the ASP.NET mid-tier to add critical
capabilities for business applications, including data
validation, authentication and roles. Brad Abrams,
product unit manager of the Application Framework
team at Microsoft, says RIA .NET Services grew out of
the work Microsoft did on LINQ.
With RIA Services were extending this pattern
by offering a prescriptive model for exposing your
domain logic over LINQ, Abrams writes. We think of
domain logic as that part of your application that is very
specific to your domainthat is the particular business
problem you are solving. By following this pattern we
are able to provide a number of features that help you
focus on your domain logic rather than the plumbing in
your code.
At press time, Microsoft .NET RIA Services was in a
March 09 Preview. It can be downloaded for free from
http://tinyurl.com/cl7z7p.
Michael Desmond

0509vsm_HowTo22-29.v9

4/17/09

12:30 PM

Page 29

SILVERLIGHT

MyDataForm.CurrentItem = custs(0)
End Sub

To make the whole collection available to the DataForm, I first create a property in MainPage that returns the ObservableCollection
of LocalCustomers. Then in MainPages Loaded event, I set the
DataContext to the XAMLs class:
Public ReadOnly Property Customers() As _
System.Collections.ObjectModel. _
ObservableCollection(Of LocalCustomer)
Get
If custs IsNot Nothing Then
Return custs
Else
Return Nothing
End If
End Get
End Property
Private 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

HOW-TO

With those changes in place, in the .XAML file, I can bind the
DataForm to the collection returned by my new property using
the DataForms ItemsSource attribute:
<dataControls:DataForm ItemsSource="{Binding Customers}"
Name="MyDataForm">

The solution is very basic at this stage and doesnt, for instance,
support validating the data or calling the method on the service that handles updates. Silverlight 3 provides two ways to
extend this basic solution to include those activities: extending
the DataForm and extending the local object.
Extending the DataForm
You can alter the DataForms behavior either by setting properties
from code or, as Ill do here, by declaratively adding attributes to the
DataForms element. For instance, by default, the DataForm initially shows each Customer in display mode. If you set the DataForms
AutoEdit property to True, the form will automatically display each
entity in edit mode when the user moves to it. AutoCommit, on the
other hand, is True by default, allowing the user to save changes just
by viewing the next entity in the collection. If you would prefer the
user to explicitly click the auto-generated Save button to commit
changes, you just need to set the AutoCommit attribute to false.
You can also control what activities the user can perform with
the DataForm. The CanUserDeleteItems and CanUserAddItems
attributes allow you off turn off some of the CRUD activities sup-

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 29

0509vsm_HowTo22-29.v9

HOW-TO

4/17/09

12:30 PM

Page 30

SILVERLIGHT

While Silverlight 3 provides significant


improvements needed by line-of-business applications,
its not a complete solution.
ported by the DataForm. Extending the DataForm with these
options 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 separate


DataTemplates for inserting, displaying, and updating data. By
default, the DataForm adds a control to every template for every
property on the entity. Setting the DataForms AutoGenerateFields
attribute to False suppresses that behavior, allowing you to design
your own layouts for the templates. The DataForm also fires a
multitude of events both before and after critical activities (such as
when records are added or during validation, for example), allowing you to add code to validate data or control updates.
Youll have some design decisions to make, though. Many of
the items that you can control by extending the DataForm can also
be controlled by extending the local object. In many cases, the best
practice is to use the features of the local object to control datarelated activities and limit your DataForm changes to controlling
workflow. By extending the local object, your data-related changes
can follow the object to whatever control is handling updates.
Extending the Local Object
For LOB developers, the real power in Silverlights data enhancements is the ability to extend the local object. If, for instance, you
want to take command of changes being made to the object, you can
have the local objects class implement the IEditableObject interface:
Public Class LocalCustomer
Implements System.ComponentModel.IEditableObject

Implementing this interface adds three methods to your object


that are fired when your object is placed in edit mode
(BeginEdit) and when it leaves edit mode (EndEdit and
CancelEdit). For instance, rather than use some event in the
DataForm to perform updates, I can use the EndEdit method in
the LocalObject to persist my changes back to the database. This
example converts my LocalCustomer back to a
Customer object and passes it to the
UpdateCustomer method on my service to have
any changes saved to the database:

validation activities declaratively, by decorating the local objects


properties.
For instance, on the CustomerId property, I want to prevent the property from being updated so I can use the Bindable
Attribute to specify that the property only supports one-way
databinding (the default is two-way). I can also use the Display
Attribute to control the order that the fields appear on the
page, specify the text for the fields label, and provide a
descriptive ToolTip. I can also use the Required Attribute to
specify that the property must be provided with a value and
what error message to display if its omitted. With all of these
Attributes 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 account


when working with the property. More importantly, if I change
my form and tie the local object to a different user interface control, these decorations will be used by that control alsothey
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 extensive
validation, you need to write code. You can put the code in the
property itself. To communicate error conditions back to the
Silverlight user interface, you just need to throw an exception,
as this version of the ContactName does:
Public Property ContactName() As String
Get
Return _ContactName
End Get
Set(ByVal value As String)
If value.Length < 5 Then

Public Sub EndEdit()


_cust = CustomerConverter.ConvertBack(Me)
nwd.UpdateCustomerAsync(_cust)
End Sub

While I used code to give the local object the ability


to update itself, I can implement many of my data
30

FIGURE 2. When a local object throws an exception the associated message


is automatically displayed at the bottom of the page and inside the DataForm.

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

0509vsm_HowTo22-29.v9

4/17/09

12:30 PM

Page 31

SILVERLIGHT

HOW-TO

End Function
End Class

Creating a Master-Detail Page


The real power in modifying the local object
becomes apparent when I convert my original
design to a master-detail page (Figure 3). The
changes required are minimal. I add a DataGrid
to my page and bind its ItemsSource attribute to
the property that returns my collection of
LocalCustomer objects. I then bind my
DataForms CurrentItem property to the
SelectedItem property of the DataGrid (and
remove the DataForms binding through the
ItemsSource attribute). The resulting XAML for
my master-detail page looks like this:
<data:DataGrid ItemsSource="{Binding
Customers}"
Name="MyDataGrid">
</data:DataGrid>
<dataControls:DataForm Name="MyDataForm"
CurrentItem="{Binding SelectedItem,
ElementName=MyDataGrid}">
</dataControls:DataForm>

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

Throw New Exception( _


"Contact name must be"+ _
"at least 5 characters long")
End If
_ContactName = value
End Set
End Property

The resulting error is automatically displayed in the user interface regardless of which control is bound to the object (see Figure
2, 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 example
attaches the ValidateCompanyName method on a class
called CompanyValidator to the CompanyName property on my
local object:
<System.ComponentModel.DataAnnotations.CustomValidation( _
GetType(CompanyValidator), "ValidateCompanyName", _
ErrorMessage:="Invalid company name")> _
Public Property CompanyName() As String

The related validator class with the ValidateCompanyName


method would look like this:

In real life, I would use templates in the DataGrid


to have the grid display fewer properties than the
DataForm. But this is where the changes that Ive made to the
LocalCustomer class pay off: Because my data-related code and
annotations are tied to my LocalCustomer class, I can turn on
editing in the DataGrid, confident that my data management
code will follow the object to the DataGrid.
While Silverlight 3 provides significant improvements needed
to craft LOB applications, it is not a complete solution. A complete
solution would provide, for instance, better control over how many
objects are returned to the client and the ability to attach Attributes
to the data transfer objects created at the server to eliminate the
need to convert to a local object in the Silverlight client. That, however, goes beyond Silverlight and into the domain of .NET RIA
Services, which integrates Silverlight with the server-side capabilities of ASP.NET (see RIA .NET Services, p. 28, for more about the
framework released with the Silverlight 3 beta).
But, while youre 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 access
your application is a Web browser. VSM
Peter Vogel (peter.vogel@phvis.com) is a principal in PH&V Information
Services, specializing in ASP.NET development with expertise in SOA, XML,
database and UI design. Hes written several books on app development using
Microsoft technologies and presents at conferences around the world.
GO ONLINE

Public Class CompanyValidator


Public Shared Function ValidateCompanyName( _
ByVal Name As String) As Boolean
Dim ValidCName As Boolean
CompanyName validation code
Return ValidCName

Use this Locator+ code at VisualStudioMagazine.com to go


directly to these related resources.
READ & DOWNLOAD
VS0905PV Read this article and download the associated code.

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 31

Project2

4/9/09

11:19 AM

Page 1

Las Vegas June 8-11


The Venetian Resort Hotel Casino

Post event workshop on June 11

VSLive! Returns to Las Vegas


Attend 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 todays 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

Take
advantage
of our $99
hotel room
rate

* Venetian gaming credit of $50 available to the rst 200


VSLive! registrants who book 2 or more nights at the Venetian.

0905_VSL_LV_vsm_Adr3.indd Sec1:2

4/8/09 4:53:14 PM

0905_VSL

Project2

4/9/09

11:20 AM

Page 2

no

11

Register today at vslive.com/v9m


Use priority code NQ9V04

Heres just a few of the great topics and speakers


youll nd at VSLive! Las Vegas this year:
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 certications as an
MCSD, MCSD.Net, MCDBA, and a ScrumMaster.

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

4:53:14 PM

0905_VSL_LV_vsm_Adr3.indd Sec1:3

4/8/09 4:53:16 PM

0905_VSL

Project2

4/9/09

11:32 AM

Page 3

Las Vegas June 8-11


The Venetian Resort Hotel Casino

Post event workshop on June 11


Conference Day 1 Monday, June 8
KEYNOTE: 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

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 Workow and WCF Help Make


Software + Services a Reality - Michael Stiefel

Lunch

Welcome Reception

Conference Day 2 Tuesday, June 9


KEYNOTE: 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 10


Oslo

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 11


VPC1 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

0905_VSL

Project2

4/9/09

11:31 AM

Page 4

no

11
Register today at vslive.com/v9m Use priority code NQ9V04
Make the most of your time with us and add these to your schedule!
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 Pros


Providing 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

$99 Rooms at the Venetian


What are you waiting for?
Weve even got Special Room Rates
at the Venetian for VSLive! Registrants
Only $99/night!

$50 in Venetian Gaming Credit


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

4:53:18 PM

0905_VSL_LV_vsm_Adr3.indd Sec1:5

4/8/09 4:56:47 PM

0509vsm_Langlab_36-46.v11

4/17/09

12:44 PM

Page 36

</Language Lab>
YO U R CO D E S OU RC E

IN THIS SECTION:

C# 36 // Ask Kathleen 42 //////////////////////////

Covariance/
Contravariance

{ C#CORNER }

Generic Covariance and


Contravariance in C# 4.0
Covariance and contravariance are precise terms that
describe which conversions are safe on parameters and
return types. Learn practical definitions for those terms,
what new constructs will be supported in C# 4.0 and
how to live with the current limitations until Visual
Studio 2010 is adopted by your organization.

around the concepts of covariance and contravariance. You


intuitively know that you can pass a derived class object to any
method expecting a base class object. You intuitively know that
you can pass a derived object to any method expecting a base
object. After all, the derived object is also an instance of the base
object. You instinctively know that you can store the result of a
method in a variable of a less-derived object type than the formal method return type.
For example, you expect this to compile:

BY BILL WAGNER
In this month's installment of C# Corner, we look at one of the

new features in C# 4.0, the next version of C# that will


be delivered in Visual Studio (VS) 2010. Looking ahead to
specific features in C# 4.0 can help you plan how to take
advantage of the new capabilities in your coding efforts. It
can also help you understand problems that are occurring in
your programs today that the next version of C# may be able
to resolve. Ultimately, the exercise will help you build a business case for adopting C# 4.0 based on existing knowledge of
how it can help you.
This month Ill examine covariance, contravariance and
how the C# language will be addressing those features with version 4.0 in VS 2010.
Invariance, Covariance and Contravariance Explained
Before we go further, lets examine what invariant, covariant,
and contravariant parameters and return types mean. You
almost certainly are familiar with the terms, even if you dont
have a grasp of the formal definitions.
A return value or parameter is invariant if you must use
the exact match of the formal type name. A parameter is covariant if you can use a more derived type as a substitute for the formal parameter type. A return value is contravariant if you can
assign the return type to a variable of a less derived type than
the formal parameter.
In most cases, C# supports covariant parameters and contravariant return types. Thats consistent with almost every other
object-oriented language. In fact, polymorphism is usually built

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 of
type object, because return types in C# are contravariant:
object value = SomeMethod();

If youve done any work with C# or Visual Basic.NET since


.NET was first released, all this is familiar ground. However, the
rules change as you begin to look at any type that represents a
collection of objects. In too many ways, what you intuitively
think should work just doesnt. As you dive deeper, you may
find that what you believe is a bug is actually the language specification. Now its time to explain why collections work differently, and whats changing in the future.
Object-Based Collections
The .NET 1.x collections (ArrayList, HashTable, Queue and so
on) could be treated as covariant. Unfortunately, theyre not
safely covariant. In fact, theyre invariant. However, because
they store references to System.Object, they appear to be

When used as a parameter, arrays are sometimes


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

36

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

0509vsm_Langlab_36-46.v11

4/17/09

12:44 PM

Page 37

C# Corner

covariant and contravariant. A few examples quickly illustrate


the issue.
You could believe these collections act as covariant because
you can create an ArrayList of Employee objects and use that as
a parameter to any method that uses objects of type ArrayList.
Often, that approach works just fine. This method would work
with any 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
};

// 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--;
}

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");
}

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

Covariance/
Contravariance

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

private void SafeCovariance(ArrayList bunchOfItems)


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

This method is safe because it doesnt change the type of any


object in the collection. It enumerates the collection, and it
moves items already in the collection to different indices in the
collection. However, none of the types change, so this method
will work in all instances.
However, ArrayList, and other classic .NET 1.x collections
cannot 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();
}

Its making deeper assumptions about the objects stored in the


collection. After the method exits, the collection contains
objects of type string. That may not have been the type of the
original collection. In fact, if the original collection contained
strings, the method does nothing. Otherwise, it transforms the
collection into a different type.
The following usage example shows the kinds of problems
encountered when you call this method. Here, a list of numbers
is sent to UnsafeUse, where its transformed into an ArrayList of
strings. After that call, the calling code tries again to create the
sum of the items, which now causes an InvalidCastException.
// usage:
public void DoTest()
{
ArrayList collection = new ArrayList()

This example shows that while classic collections are invariant, you could, for all practical purposes, treat them as though
they were covariant (or contravariant). But these collections
are not safely covariant. The compiler does nothing to keep
you from making mistakes in how you treat the objects in a
classic collection.
Arrays
When used as a parameter, arrays are sometimes invariant, and
sometimes covariant. Once again, just like the classic collections, arrays are not safely covariant.
First and foremost, only arrays containing reference types
can be treated as either covariant or contravariant. Arrays of
value types are always invariant. Thats true even when trying to
call a method that expects an object array. This method can be
called with any array of reference types, but you cannot pass it
an 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 are


covariant and contravariant. However, theyre not safely covariant
or safely contravariant. The more often you treat arrays as covariant or contravariant, the more youll find that you need to handle
ArrayTypeMismatchException. Lets examine some of the ways.

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 37

0509vsm_Langlab_36-46.v11

4/17/09

12:44 PM

Page 38

</Language Lab>
C# Corner

Covariance/
Contravariance

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. Thats a lengthy way to say that
a lot of substitutions you expect to work, dont.
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 an


ArrayTypeMismatch exception:
38

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

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 method
that expects an array of B objects. Because arrays are covariant,
you can pass the D[] to the method expecting B[]. But, inside
DestroyCollection(), the array can be modified. In this case, it
creates new objects for the collection, objects of type D2. Thats
fine in the context of that method: D2 objects can be stored in a
B[] because D2 is derived from B. But, the combination often
causes errors.
The same thing happens when you introduce some
method that returns the array storage and treat that as a contravariant 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, it


will cause an ArrayTypeMismatch exception when the storage[0] element is set to a B object.
Generic Collections
Arrays suffer from being treated as covariant and contravariant,
even when thats not safe. The .NET 1.x collection types are
invariant, but stored references to System.Object, which wasnt
type safe in any practical sense. 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. Thats a lengthy way to say that a lot of substitutions

0509vsm_Langlab_36-46.v11

4/17/09

12:44 PM

Page 39

Instantly Search
Terabytes of Text
you expect to work dont. Youd think that you could write a
method like this:
private void WriteItems(IEnumerable<object> sequence)
{
foreach (var item in sequence)
Console.WriteLine(item);
}

Youd think you could call it with any collection that implements
IEnumerable<T> because any T must derive from object. That
may be your expectation, but because generics are invariant, the
following will not compile:
IEnumerable<int> items = Enumerable.Range(1, 50);
WriteItems(items); // generates CS1502, CS1503

You cant treat generic collection types as contravariant, either.


This line will not compile because you cannot convert
IEnumerable<int> into IEnumerable<object> when assigning the
return value:
IEnumerable<object> moreItems =
Enumerable.Range(1, 50);

You might think IEnumerable<int> derives from


IEnumerable<object>, but it doesnt. IEnumerable<int> is a
Closed Generic Type based on the Generic Type Definition for
IEnumerable<T>. IEnumerable<object> is another Closed
Generic Type based on the Generic Type Definition for
IEnumerable<T>. One does not derive from the other. Theres
no inheritance relationship, and you cannot treat them as
covariant. Even though theres an inheritance relationship
between the two type parameters (int, and object), theres no
corresponding inheritance relationship between any generic
types using those type parameters. It feels like it should work,
and strictly speaking, it does work correctly.
C# treating generics invariantly has some very powerful
advantages. Most significantly, you cant make the mistakes I
demonstrated earlier with arrays and the 1.x style collections.
Once you get generic code to compile, youve got a much better
chance of making it work correctly. Thats consistent with C#s
heritage as a strongly typed language that leverages the compiler
to remove possible bugs in your code.
However, that heavy reliance on strong typing feels restrictive. Both of the constructs I just showed for generic conversions
feel like they should just work. And yet, you dont want to revert
to the same behavior used for the .NET 1.x collections and
arrays. What we really want is to treat generic types as covariant
or contravariant only when it works, not when it simply substitutes a runtime error for a compile time error.
C# 4.0 syntax
C# 4.0 will introduce a set of changes to the language that
removes the surprising behavior that closed generic types
cant be treated as covariant or contravariant without introducing yet another breach in the type safety system. C# 4.0
introduces syntax to treat some generic types as safely covariant and safely contravariant.

N dozens of indexed,

unindexed,
fielded data and
full-text search
options (including
Unicode support
for hundreds
of international
languages)
N file parsers /

converters for
hit-highlighted
display of all
popular file
types
N Spider supports

static and
dynamic web
data; highlights
hits while
displaying links,
formatting and
images intact

h Spider
Desktop wit
h Spider
Network wit
CD/DVDs
Publish for
pider
Web with S
Win & .NET
Engine for
Linux
Engine for

New
64-bit

N API supports .NET, C++, Java, databases, etc.

New .NET Spider API

The Smart Choice for Text Retrieval


since 1991
N Bottom line: dtSearch manages a terabyte of text

in a single index and returns results in less than a


second InfoWorld
N For combing through large amounts of data,

dtSearch leads the market Network Computing


N dtSearch covers all data sources ... powerful

Web-based engines eWEEK


N dtSearch searches at blazing speeds Computer

Reseller News Test Center


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

Contact dtSearch for


fully-functional evaluations

1-800-IT-FINDS www.dtsearch.com
VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 39

0509vsm_Langlab_36-46.v11

4/17/09

12:44 PM

Page 40

</Language Lab>

Covariance/
Contravariance

C# Corner

The C# 4.0 language specification uses the terms output


safe and input safe to describe type parameters that are
safely covariant or contravariant, respectively. Those terms
are somewhat more descriptive, if less precise, to describe
how covariance and contravariance work. A couple examples
will make it clearer.
The familiar IEnumerable<T> and IEnumerator<T>
interfaces are output safe. Therefore, both interfaces can be
treated as covariant. Furthermore, those methods are safely
covariant. In C# 4.0, both of those interfaces have been annotated with the new out contextual keyword to indicate that
they 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 signifies that T is covariant. It will compile cleanly because T
appears only in output positions, and is output safe. That
means, beginning with C# 4.0, you can use an
IEnumerable<string> where the formal parameter list expects
an 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 noting that its 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 the
ref or out modifier. T is therefore input safe and can be treated as

contravariant. Because T only appears in input locations, a less


derived type can be used in the formal parameter list where a
more derived type is used as the actual parameter. An
IEquatable<object> can be used where you expect an
IEquatable<string>.
Other interfaces are still invariant. ICollection<T> contains methods where T appears in input positions as well as
methods where T appears in output positions:
public ICollection<T> : IEnumerable<T>
{
void Add(T item);
// other methods elided
IEnumerator<T> GetEnumerator();
}

The Add() method is not output safe. The GetEnumerator()


method is not input safe. Because the entire interface is neither
input safe nor output safe, the ICollection<T> interface cannot
be treated as either covariant or contravariant. Therefore,
ICollection<T> will remain invariant.
There are quite a few limitations on covariance and contravariance in the C# language. Those limitations are meant to
minimize potential runtime errors related to misuse of those
features. The limitations can be easily remembered by a couple
broad guidelines.
First off, the in and out contextual keywords can only
be applied to interface and delegate generic type definitions.
You cant create covariant or contravariant generic class definitions. Therefore, MyClass<in T> is illegal.
The other limitations apply when you attempt to treat a
particular type parameter as covariant or contravariant.
Covariance and contravariance only apply when theres a reference conversion between the two specific type parameters. As I
mentioned earlier, IEnumerable<string> can be used where
IEnumerable<object> is expected. Theres a reference conversion from string to object. However, IEnumerable<int> cant
be used where IEnumerable<long> is expected. Theres a conversion from int to long, but thats a widening conversion, not a
reference conversion. In addition, IEnumerable<int> cannot
be used where IEnumerable<object> is expected. Again, there
is a conversion from int to object, but its a boxing conversion,
not a reference conversion.
In practice, the reference conversion rule means that you
can only treat different closed generic types as covariant or

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.

40

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

0509vsm_Langlab_36-46.v11

4/17/09

12:44 PM

Page 41

C# Corner

The question is how to author your code

contravariant when the type parameters are both reference


types, 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 delegate
types updated to be safely covariant and contravariant. As you
learn more about Visual Studio 2010, take the time to learn
about how those language extensions on the interfaces enable
you 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, VS
2010 is still a future technology, and it will be some time before
it will make its way to the corporate developer.
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. Knowledge of the
new features will help you create code thats ready to accept the
in or out contextual keywords on your interface and delegate
types. It will become more important to factor those interfaces
into input only and output only portions, so that your interfaces can support both covariance and contravariance, as
appropriate. You should examine your generic interfaces and
methods to see if the parameters and return values are input
safe or output safe. That will make it easier to use them in either
a covariant or contravariant manner in the near future.
A more immediate need is to be able to emulate the covariant and contravariant features using the current language elements. You cant replicate all the features, because if it already
worked, theres no reason for the language teams to add these
features. That said, you can get close in some usages.
There are two techniques that you can often use to mitigate the need for covariance and contravariance. You can use
Cast<T> or you can create generic methods instead of covariant and contravariant methods.
The earlier WriteItems() method could be modified as a
generic 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 a


sequence of integers. In other uses, where your methods need
capabilities beyond those methods in System.Object, youll
need to add constraints on the generic method, possibly even
factoring out an interface contract as part of the generic
method constraints. However, there will almost always be a way
to create a generic method that can be used where you want to
create a covariant method, or a contravariant method. When

you write the method, you should convert the method to a


generic method.
When you dont have access to the core method because its
in a third-party library, you can use the Cast<T> method in
the specific cast where you need to convert between
IEnumerable<T> types for two different type parameters. Of
course, this can occur only where a conversion between those
types exist.
Remember that the original generic WriteItems() method
was coded this way:
private void WriteItems(IEnumerable<object> sequence)
{
foreach (var item in sequence)
Console.WriteLine(item);
}

Covariance/
Contravariance

today such that it can easily take advantage of the new covariant and
contravariant additions when they become available.

You can call that method using a sequence of integers by applying 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, converting each element, and yields the converted collection as its
output. While this option will not work for other types, it will
always work where you need an IEnumerable<T> conversion
for different types.
In this article, Ive shown you the motivation behind the
addition of the generic covariance and contravariance in C#
4.0. Theyre being added because invariant generic types are too
restrictive for most uses. There are covariant and contravariant
conversions that we expect to work. In C# 3.0, those conversions
dont work, to the surprise of many developers. The language
team is addressing that in C# 4.0. In the meantime, there are
ways to mitigate the need for those features. VSM
Bill Wagner (wwagner@srtsolutions.com), 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 go


directly to these related resources.

READ & DOWNLOAD


VS0905CC Read this article and download the sample code.

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 41

0509vsm_Langlab_36-46.v11

4/17/09

12:44 PM

Page 42

</Language Lab>
{ A S K K AT H L E E N }

Visual Studios T4 Code


Generation
T4 Templates

Learn how to create and debug templates using


Microsofts T4 templating language.
BY KATHLEEN DOLLARD
Q: I want to generate some of the code for my application and a
friend of mine said that Microsoft has a code generator, but I cant
find one. Do you know what hes talking about?
A: Microsoft actually has two major code-generation toolsthe

CodeDOM and T4. Your friend was probably referring to T4


because the CodeDOM is so difficult to read and maintain that
its inappropriate for almost all business applications. T4 (previously called T3) stands for Text Transformation Templating
Toolkit. T4 is an ASP.NET-style syntax that has direct literal text
output, embedded expressions and code logic.
T4 is already on your machine if youre using Visual Studio
2008, or you can download the DSL Toolkit if youre using VS
2005. T4 can generate any type of textual artifact. Thats good
news. The bad news is that the support is not complete and
Visual Studio is missing critical capabilities. But theres more
good news: adding two free tools to your environment gives you
a solid base for generating code. Ill show you how to create and
debug a T4 template and three ways to run T4 templates, including a Managed Extensibility Framework-based harness, which
acts as an ecosystem for evolving code generation.
T4 templates begin with a template directive. Directives
are identified by the <#@ #> tag. In addition to initiating the
template, the template directive indicates the language of the
template and allows debugging. T4 templates include .NET
code and the language attribute indicates the language of code
running in the template, not the artifact youre creating. By
default, T4 uses the 2.0 version of the language, but you can
change this by appending v3.5 to the language attribute.
Following the template directive, you can include any combination of literal text (in grey below) and code and expressions
within statement blocks identified with the <# #> tags:
<#@ template language="C#" debug="true" #>
<#
int hour = DateTime.Now.Hour;
if(hour < 12)
{ #>
Good Morning World! <#
}
else if(hour > 12 && hour < 17)
{ #>
Good Afternoon World!<#
}
else

42

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

{ #>
Good Evening World! <#
} #>

In this sample template, statement blocks indicate which greeting to output. VS doesnt provide coloration, which makes it
extremely difficult to read the templates. I recommend downloading an editor from Clarius Consulting. Clarius has both a
free community edition and a more sophisticated retail edition
at http://tinyurl.com/dkqkmc.
This is enough background to create your first T4 template. Open VS and create a new project of any type. Add a New
Item and select the type Text File. Name the file with the extension .TT. Enter the code in the previous sample or some variation. VS maps the .TT extension to a custom tool named
TextTemplatingFileGenerator. This custom tool provides a
default mechanism for running simple templates and learning
about T4. When you save the template, the custom tool runs,
calls the T4 engine and outputs code to a dependent file. When

Code Generation
Principles
As I started working on code generation, I began uncovering underlying principles. No one meets them all, but these are the goals were
striving for:
1. Code generation must be in your control. If something goes
wrong with your application, youre responsible for fixing it. You
cant fix something you cant change. You need control of the templates behind your code generation.
2. Metadata is distinct and morphable. Metadata is the data that
drives your application and makes it unique from other applications. It needs to be distinct so you can find and debug it, and it
needs to be morphable so your database and business objects
arent required to match.
3. Code generation should fit into your development process. If
youre doing nightly builds, code generation should be part of it,
otherwise it should be a simple one-click process. Generated code
should be included in source control as all other code.
4. Handcrafted code is sacred and protected. People are creative
and may not do the same thing the same way a second time, so
you 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 architectures
that can evolve to meet changing demands.
6. Designing an application based on generation should be
easy. T4 templates and a simple ecosystem-based harness is one
step in this direction.
K.D.

0509vsm_Langlab_36-46.v11

4/17/09

12:44 PM

Page 43

Ask Kathleen

The templates you use to create application code

you expand the plus sign on the template file, youll find the
output 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 the
extension of the generated file is .CS. The custom tool defaults
to .CS, but you can fix this by specifying the extension in an
output directive:
<#@ output extension=".vb" #>

The T4 engine first parses the template to create a temporary class


derived from the TextTransformation class. This class is compiled
and run to produce output. The code you put inside statement
blocks is placed in the body of the TransformText property in the
temporary class. The literal text of your template (shown in grey)
is included in calls to the Write method of a string builder within
this temporary class. You can debug by placing breakpoints inside
your template and stepping through the code. Youll step through
your template, not the compiled temporary class. While debugging, 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), report
issues (Error, Warning, Errors) and directly access the string
builder (Write, WriteLine, GenerationEnvironment).
Code within statement blocks is run, but is not treated as
output. Often youll 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 a
method, youll need a different type of block to include additional
methods or additional classes. The class feature block offset by
<#+ #> offers this capability. You can write the template above in a
different way to demonstrate these features:

T4 Templates

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.

<#@ template language="C#" debug="true" #>


<#= OutputGreeting() #>
<#= public string OutputGreeting()
{
int hour = DateTime.Now.Hour;

PERFECTION IN SOFTWARE PROTECTION

Exceptional Software Protection


Software Protection
Document Protection
Order your Free Software Development Kit now!
Phone 1-800-6-GO-WIBU | order@wibu.us

Access Protection

CodeMeter for .NET

WIBU-SYSTEMS USA Inc.


110 W Dayton Street,
Edmonds, WA 98020
United States
www.wibu.us
info@wibu.us

More than 1000 Key-Storage License Entries

- Different ISVs can share one dongle


3

Secure Expiration Date with a Real-Time-Clock

- Unique Time Certication Feature


- Control Relative and/or Absolute time
3
3

More ways to sell = More sales


Create Student and Version Licenses

Media Protection

Control Network Licensing

- Control concurrent users


- Control roaming users
3

Create Standby Licenses

- Hot Standby and Cold Standby


- Provide Overow Licenses
3

Pay-Per-Use Counter

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 43

0509vsm_Langlab_36-46.v11

4/17/09

12:44 PM

Page 44

</Language Lab>
Ask Kathleen

T4 Templates

if(hour < 12)


{ return "Good
else if(hour >
{ return "Good
else
{ return "Good
} #>

44

some issues,
such as assembly and include file location resolution.
???
However, youll still face challenges as you stuff your generation
process inside your application project.

Morning!"; }
12 && hour < 17)
Afternoon!"; }

T4 Harness
I prefer to write an independent generation harness that can
run multiple templates to build your app and is focused on

Evening!"; }

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.
In addition to the template and output directives, T4 natively provides four other directives.
The import directive provides namespace recognition similar to Imports in Visual Basic or the
using statement in C#. The include directive
places the contents of another T4 template into
the current template. The assembly directive
adds .NET assemblies for the template code,
similar to adding a reference in VS. Using the
default tools, assemblies must include the full
file path (from the root directory), be in the
GAC or be referenced by the current project. If
the include directive uses a relative path and the
included template contains additional include
directives, all relative paths are in relation to the
first or root template location, making double
jumps for code reuse difficult.
You can play with templates using VSs
automatic generation, but youre likely to soon
run into limitations: Code reuse is hampered by
putting the template directly into your output
directory. You cant pass input parameters. Its a
pain to write .NET code without IntelliSense
and syntax checking. It hopelessly intertwines
the output project with the generation mechanism, which breaks the Single Responsibility
Principle and Separation of Concerns. I prefer to
move out of VS and focus on self-contained
templates running in a harness, which separate
the action of generation from the activity of the
generated application. If you wish to work within the VS model, the T4 Toolbox on CodePlex
(www.codeplex.com/t4toolbox) takes the VS
custom tool usage to amazing lengths and Oleg
Sychs blog (www.OlegSych.com) has good coverage of T4 intricacies. Another option working
inside VS is to write your own custom tool for
generation. (See Generate Code from Custom
File Formats, March 2009, and the September
2008 Ask Kathleen column, Customize Code
Generation in EF.) Custom tools can provide a
T4 wrapper and use an alternate T4 host to solve

TEMPLATE HARNESS

C#

<#@
<#@
<#@
<#@

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" #>
<# TemplateOutputFileName = table.Name; #>
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE Select <#=

table.Name

#>

AS
BEGIN
SET NOCOUNT ON;
SELECT <#=
FROM <#=

ConcatenateWithComma(table.TableColumns) #>
table.Name #>

END
GO
<#+ string ConcatenateWithComma(IEnumerable<IDbTableColumn
Metadata> list)
{
string ret = String.Empty;
foreach (IDbTableColumnMetadata item in list)
{
ret += item.Name + ", " ;
}
return ret.Substring(0, ret.Length - 2);
}
#>

LISTING 1 A simple select stored procedure can be created from database


metadata. The AppVenture Community Generation Harness (available with
source code) retrieves the corresponding tables from a Managed Extensibility
Framework part and loops through them calling this template once for each loop.
Within the context of the harness, this template is entirely self-contained.

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

0509vsm_Langlab_36-46.v11

4/17/09

12:44 PM

Page 45

Ask Kathleen

The pieces of the harness are like Lego blocks


reuse. Ill explain in broad terms how a T4 harness works, and
how you can download a working harness with source code.
If youre using a separate harness, you dont want the
default VS behavior of creating the dependent file because your
template will rely on features not present and fail. The easiest
way to block this behavior is to give your templates a .T4 extension. The Clarius editor will still recognize your templates with
this extension.
To provide extra functionality, such as passing parameters,
the generation harness uses a custom T4 host. The host must
implement ITextTemplatingEngineHost and may also implement IServiceProvider. The host is responsible for all interactions with the environment: managing links to custom directive
processors, finding assemblies and include files, and providing
services. By creating your own custom host, you can provide
extra functionality and data, such as a dictionary of parameter
names and values.
Creating custom directives allows you to expand the information the template author provides. For example, the template author can provide a list of parameters. Within the template, parameters are treated as properties, so by convention
parameters are declared using a custom directive named prop-

erty (see Listing 1, opposite page). Including explicit parameter


requests in the template leads to better encapsulation.
Custom directives require a directive processor, which
inserts the required code into the temporary class when called
by the engine. Custom directive processors inherit from
DirectiveProcessor. Its ProcessDirective method is called once
for each directive. This method creates the code required by the
directive and the engine inserts this text into the temporary
class. The property directive processor creates a .NET property
for each directive. The backing data for the property is retrieved
by casting the host to an IServiceProvider that offers the
PropertyDictionary.
Code Generation and MEF
If that sounds like a lot of gnarly codeit is. To make it easier
for you to use T4, Ive created a T4 harness based on the
Managed Extensibility Framework (MEF).
Code generation and MEF are a perfect fit. Templates
become MEF parts that are discoverable simply by being
placed in a directory pointed to by a configuration file. You
can add or remove templates just by altering the contents of
this directory.

T4 Templates

pick the ones that make sense in your environment.

8VcNdj8ji9ZkZadebZci8dhih
7n>cXgZVh^c\EgdYjXi^k^in4
7Z[dgZGVaan!lZhigj\\aZYideg^dg^i^oZl]VidjgXjhidbZgh
gZVaancZZYZY#CdllZldg`dci]Z]^\]ZhikVajZegd_ZXih
ZkZgnildlZZ`h#6cY!lZkZgZYjXZYgZaZVhZi^bZhWn*%#

6\^aZVcYGVaanXVcXjindjgi^bZ"id"bVg`Zi
Wn*%VcY^cXgZVhZegdYjXi^k^inWn'*#
;h_a>kZZb[ijed" 8ID!>cdk^h

=ZVgi]Zl]daZhidgnVcYhZZl]nGVaan^hi]Zdcan
6\^aZA^[ZXnXaZBVcV\ZbZcikZcYdgid\jVgVciZZndjghjXXZhh#
AZVgcbdgZVilll#gVaanYZk#Xdb

'%%.GVaanHd[ilVgZ9ZkZadebZci8dge

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE 45

0509vsm_Langlab_36-46.v11

4/17/09

12:44 PM

Page 46

</Language Lab>

T4 Templates

Ask Kathleen

46

Metadata, output services, and even


the property directive processor are MEF
parts. The pieces of the harness are like
Lego blockspick the ones that make
sense in your environment. The purpose
of the harness is to empower a creative and
flexible ecosystem that expands as your
needs change.
Ive glossed over a few details that are
worth returning to. MEF parts must be
.NET objects, and T4 templates are just
text files until theyre executed. Each T4
template must be wrapped in an instance
of a class that is a non-shared MEF part
and the harness needs to perform discovery. Because discovery is directory based,
the harness just needs to grab the T4 templates in a particular directory, place them
FIGURE 1. The ExportContainer of MEF acts like a schoolyard where different
in the MEF part wrapper and ensure MEF players can raise their hands and shout I need a xxx or Use my xxx. When
can find the part. Discovery itself is an MEF teamed with intelligent granularity, this creates an ecosystem for evolution of
part, so if youd rather use a different dis- individual parts without disrupting the whole.
covery scheme such as a script, feel free.
While Ive talked about the interacT4 templates run code and can therefore run malicious code.
tions between a host parameter dictionary and a property
You need to ensure the integrity of the parts and the T4 temdirective processor, I havent explained how the host knows
plates you place into your environment.
what parameters to expect or where to get the values. Because
Im releasing my T4 harness with full source code for you
a T4 template is just a text file, the MEF wrapper can crack it
to work with and explore. You can download AppVenture
open, parse, and extract a list of expected parameters from
Community Generation Harness with source code from the
the property directives. Property directives are used twice
download section at www.appventure.com and you can read
to create a dictionary of parameters and to generate code for
more about its ongoing development in my blog at
the temporary T4 class.
www.msmvps.com/blogs/kathleen. Our intention is to make
Because MEF creates an ecosystem, the wrapper does not
the project open source as soon it stabilizes and we start buildneed to explicitly find values for the parameters; it merely asks
ing a community. If youre interested in helping out as we move
the MEF container first for any match on the parameter name,
toward that goal, let me know. VSM
then for a match on the type. To avoid unnecessary dependencies, use the name only for simple types such as string or date,
and base other matches on the data type.
While Ive only discussed property directives, you can creKathleen Dollard (kathleen@mvps.org) is the chief technologist for
ate any other type of directive you want. The directive processor
AppVenture (www.appventure.com)building relationships that
is retrieved via MEF, and Ive provided a base class which makes
leverage our application generation experience to speed and improve
creating new directive processors very easy.
your application development. Shes been a Microsoft MVP for 11 years
Generation often requires that templates run multiple times
and is a member of the INETA Speakers Bureau. Dollard has worked
with different data to create multiple files. It would break the
extensively with application code generation and is the author of Code
Single Responsibility Principle for the template itself to define
Generation in Microsoft .NET (Apress, 2004). She speaks at dozens of
looping behavior. The harness solves this problem by searching
conferences and user groups each year and is active in the Northern
for parts that export a special ILoopValues interface with a custom
Colorado .NET SIG, Denver Visual Studio User Group, Northern
MetadataView attribute that provides the loop type. If a parameColorado Architects Group and IASA Denver.
ter is a type supported by a loop value provider, the T4 template is
called once for every item in the collection.
Because many files are output, each needs a unique name.
GO ONLINE
To make this easy, the harness provides a special parameter
Use these Locator+ codes at VisualStudioMagazine.com to go
named TemplateOutputFileName. Assign a name based on the
directly to these related resources.
data in each pass of the template.
The generation harness assumes you have control and
READ & DOWNLOAD
know what code is running during generation. MEF parts and
VS0905AK Read this article and download the sample code.
VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

0509vsm_AdIndex

4/17/09

11:51 AM

Page 47

Advertising Sales

Ad Index
Advertiser

Page

/n Software Inc.

www.nsoftware.com

Accusoft Pegasus

21

www.accusoft.com

Aspose

C3

Atalasoft, Inc

19

www.apose.com
www.atalasoft.com

East

ComponentArt, Inc.

24, 25

www.componentart.com

Andrew Mintz
National Sales Manager
Phone: 508-532-1433
amintz@1105media.com

dtSearch

39

www.dtsearch.com

ESRI

www.esri.com

GrapeCity, Inc.

13

Intel Corporation

C4

www.grapecity.com
www.intel.com

West

LEAD Technologies, Inc.

www.leadtools.com

Chris Kourtoglou
Regional Sales Manager
Phone: 650-579-0121
ckourtoglou@1105media.com

Microsoft Corporation

16, 17

www.microsoft.com

PureCM.com

29

RallySoftware

45

Red Gate Software

23

www.purecm.com
www.rallydev.com

National Accounts Director


William Smith
Phone: 603-886-3466
wsmith@1105media.com

Director, Print Production


Jenny Hernandez-Asandas
Phone: 818-734-1520 ext 101
Fax: 818-734-1528
jhernandez@1105media.com

www.red-gate.com

Software FX

C2, 1

www.softwarefx.com

VSLive! Events

www.vslive.com

32, 33, 34, 35

Wayside Technology Group, Inc


www.waysidetechnology.com

Microsoft Account Manager


Danna Vedder
Phone: 253-514-8015
dvedder@1105media.com

Production Coordinator
Serena Barnes
Phone: 818-734-1520 ext 164
vsmadproduction@1105media.com
sbarnes@1105media.com

WIBU-SYSTEMS USA, Inc


www.wibu.com

CA Inc.

www.ca.com

ComponentOne LLC

DataDirect Technologies
www.datadirect.com
Visual Studio Magazine (ISSN 1537-002X) is published
monthly by 1105 Media Inc., 9121 Oakdale Avenue,
Ste. 101, Chatsworth, CA 91311. Periodicals postage
paid at Chatsworth, CA 91311-9998, and at additional
mailing offices. Complimentary subscriptions are sent
to qualifying subscribers. Annual subscription rates for
non-qualified subscribers are: U.S. $34.97, Canada
$52.97 (U.S. funds); International $78.97 (U.S. funds).
Subscription inquiries, back issue requests, and
address changes: Mail to: Visual Studio Magazine,
P.O. Box 1164, Skokie, IL 60076-8164, e-mail
VSMmag@1105service.com or call toll free 888-7688759, fax number 847-763-9564. International calls
847-763-9135. POSTMASTER: Send address changes
to Visual Studio Magazine, P.O. Box 1164, Skokie, IL
60076-8164. Canada Publications Mail Agreement No:
40612608. Return Undeliverable Canadian Addresses
to Circulation Dept. or Bleuchip International, P.O. Box
25542, London, ON N6C 6B2.

Copyright Statement
Copyright 2009 by 1105 Media, Inc. All rights
reserved. Printed in the U.S.A. Reproductions in
whole or part prohibited except by written permission. Mail requests to "Permissions Editor," c/o Visual
Studio Magazine, 2600 El Camino Real, Ste 300, San
Mateo, CA 94403.

Legal Disclaimer
The information in this magazine has not undergone
any formal testing by 1105 Media, Inc. and is distributed without any warranty expressed or implied.
Implementation or use of any information contained
herein is the reader's sole responsibility. While the

information has been reviewed for accuracy, there is


no guarantee that the same or similar results may be
achieved in all environments. Technical inaccuracies
may result from printing errors and/or new developments in the industry.

Developer Express Inc.


www.devexpress.com

IBM Corp.

12

www.embarcadero.com

Infragistics

22

Magenic Technologies Inc.

11

www.magenic.com

Nalpeiron

www.nalpeiron.com

20, 22

Ncover

22

Nevron Software

21

www.ncover.com
www.nevron.com

Noemax Technologies

22

Oracle Corp.

12

PreEmptive Solutions

22

www.noemax.com
www.oracle.com

www.preemptive.com

PureCM.com

www.purecm.com

REAL Software

www.realsoftware.com

Resco

www.resco.net

20
20, 21
20

SAP AG

20

Sun Microsystems Inc.

48

www.sap.com
This publications 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-1000
E-mail: 1105media@meritdirect.com
Online: www.meritdirect.com

19, 20

JNBridge

www.jnbridge.com

List Rental

18, 20
12

www.infragistics.com

For single article reprints (in minimum quantities of


250-500), e-prints, plaques and posters contact:
PARS International
Phone: 212-221-9595
E-mail: 1105reprints@parsintl.com
Online: www.magreprints.com/QuickQuote.asp

12

20

1105 Media Inc.


9121 Oakdale Ave. Ste 101
Chatsworth, CA 91311
www.1105media.com

Reprints

20, 22

Embarcadero Technologies Inc.

www.dynatrace.com

www.ibm.com

Direct your Media Kit requests to Matt Morollo, VP


Publishing.
Phone: 508-532-1418
Fax: 508-875-6622
E-mail: mmorollo@1105media.com

12

dynaTrace Software

Corporate Address

Media Kits

43

Editorial Index
www.componentone.com

ID Statement

www.sun.com

Sybase Inc.

www.sybase.com

11, 12

Telerik

21

The Imaging Source

20

Visual Numerics Inc.

22

www.telerik.com
www.textcontrol.com
www.vni.com

VisualStudioMagazine.com May 2009 VISUAL STUDIO MAGAZINE

47

0509vsm_RedReview_48.v3

4/17/09

12:48 PM

Page 48

</Redmond
Review>

BY ANDREW J. BRUST

Remembrance of Code Past


Ive been on a nostalgic binge lately. Ive been watching old
movies, sharing tales of my childhood with my son and thinking
about how much the neighborhood I grew up in has changed. The
nostalgia extends to technology, too: In my column last month
(Whats Old Is New Again, April 2009) I remarked how a 15-year-old
Microsoft technology and a new one reflect similar industry trends.
Im not the only one finding value in classic codingsomething
I realized while taking a look at PHP and MySQL. Microsoft is
really interested in these products, though at first blush its
hard to tell why. Theyre open source technologies, have no
dependency on Windows, pose a competitive threat to .NET,
and one of them, MySQL, is even owned by a longtime Microsoft
nemesis in Sun Microsystems.
And yet, Microsoft is promoting Windows Server 2008 and
IIS7 (with its FastCGI support) as a great place to run PHP. This is
more than rhetoric: Microsoft has built something called the PHP
on Windows Training Kit. Its free, its online (get the March release
candidate at http://tinyurl.com/cemn2o), and every attendee at
Microsofts MIX09 conference in March received the kit on a USB
thumb drive.

back home again. But the significance of this extends beyond me


reconnecting with my past; it actually underscores why Microsoft
needs to do the same.
Redmond wonders why PHP is so popular and why so many
of the biggest open source applicationsWordPress, Drupal, take
your pickare written in it. More significantly, Microsoft is struggling to understand how MySQL, the relational database thats
good enough, is stealing an increasing amount of momentum
from SQL Server.
The truth is right there. The very simplicity and productivity
of classic VB, ASP and earlier data-access models is what made
the Microsoft developer ecosystem so huge. As important and
successful as .NET has been, the framework has pushed Microsoft
to abandon much of that simplicity and de-prioritize the wants and
needs of the developers who once flocked to it.
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 part
of this decade, it most certainly is not.
There were good reasons for Microsoft to
focus on the enterprise. There were good reasons
to make .NET a stack that required a caliber of
developer perhaps more senior than those in the
VB and ASP constituencies. Yes, COM was long in
the tooth. Sure, VBs lack of inheritance and other
programming niceties meant the Java bullies
picked on the VB kids in the developer schoolyard. .NET was
absolutely necessary, and its success gave Microsoft some
desperately needed momentum in the developer community.
But now, more than seven years after .NET 1.0, Microsoft
needs 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 Windows
Communication Foundation, Windows Workflow Foundation, Oslo
and Dublin. But Microsoft can, and must, serve the productivity
programmer as well. Because if it doesnt, others clearly will. VSM

PHP and MySQL have


beaten Microsoft at the game
it practically invented.

I was at MIX09 and walked away with one of the thumb


drives. On the flight home, I looked it over and, forgive me for
saying so, it makes PHP programming look very attractive.
You can do PHP development using simple script code inline
with HTMLthe language is quite intuitive and easy to follow.
Plus, the kit shows you how to use PHP with SQL Server.
Its easy: you use individual function calls to connect to a
database, submit queries, manage parameters and fetch rows
into simple arrays.
At first I couldnt put my finger on why this model was so
appealing. Then I realized: It was the continuing pull of nostalgia.
PHP code looks an awful lot like classic Active Server Pages. And
the SQL Server driver for PHP, the code for which is similar to that
for MySQL, turns out to be the thinnest of wrappers around the
ODBC API. This was the coding equivalent of comfort food; Id gone

48

VISUAL STUDIO MAGAZINE May 2009 VisualStudioMagazine.com

Andrew J. Brust (andrew.brust@26ny.com) is chief, new technology,


for consultancy twentysix NewYork, as well as a Microsoft regional
director and MVP. Hes also the co-author of Programming Microsoft
SQL Server 2008 (Microsoft Press, 2008).

Project1

2/24/09

10:18 AM

Page 1

Project2

4/16/09

10:36 AM

Page 1

EVOLVE YOUR CODE.


Parallelism breakthrough.
7KLVDOOLQRQHSDUDOOHOLVPWRROVHWVLPSOLHVSDUDOOHOLVPIRUPXOWLFRUHIURP
DQDO\VLVDQGFRPSLOLQJWKURXJKGHEXJJLQJDQGWXQLQJ'HVLJQHGIRUWRGD\V
VHULDODSSVDQGWRPRUURZVSDUDOOHOLQQRYDWRUV

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.

S-ar putea să vă placă și