You are on page 1of 44

0209vsm.C1.

v2

1/22/09

1:31 PM

Page 1

Where Have All the Coders Gone?


VisualStudioMagazine.com

E N T E R P R I S E

S O L U T I O N S

F O R

.N E T

D E V E L O P M E N T

RETIRE YOUR

DATA CENTER
Use Azure Services to Maximize Availability,
Reliability, and Scalability.

PLUS

Use Lambda Expressions


for Abstract Delegates

FEBRUARY 2009 Vol. 19, No. 2

Use Iterators in VB

Project5

12/11/08

4:42 PM

Page 1

BeTheDataGuru

Visual Studio

WPF/Silverlight

SharePoint

SQL Server

Java

COM

PowerShell

Project5

12/11/08

4:43 PM

Page 2

Achieve AHigher State Of DataVisualization


To master the art of data visualization, you must seek out the leader. For almost two decades,
Software FX has risen above all others by bringing 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 a data presentation tool that
provides a best-of-breed solution for Windows developers seeking enterprise quality and
performance, as well as a professional IT monitoring solution offering incredible features for
reporting and monitoring data. For a world of data visualization products that can raise your
work to a higher level, depend on the source thats clearly on top.
Our most popular product, Chart FX provides
charts, gauges and maps with additional vertical
visualization functionality for business intelligence
(OLAP), geographic data, financial technical
analysis, and statistical studies and
formulas. Recognized as the innovator
and leader of the charting component
category for the past 15 years, Chart FX
delivers incomparable gallery options,
aesthetics and data analysis features.
Grid FX was specifically designed for visual studio
developers to take advantage of a powerful
design-time experience, integrated Chart FX
functionality right in the box, and AJAX to
provide robust, run-time functionality in ASP.net
applications. The dynamic aesthetic features
for data presentation and analysis allow simple
adaptation to an existing application or to specific
corporate branding 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.

Visit softwarefx.com for interactive demos and more information about our latest products.

Data visualization for every need, every platform

Project4

6/2/08

12:13 PM

Page 1

0209vsm_TOC_3-4.v10

1/22/09

1:33 PM

Page 3

Contents
February 2009 VOLUME 19 NO. 2

C O LU M N S
C# CORNER

26 Use Lambda Expressions


for Abstract Delegates
Lambda expressions are nothing more than
convenient syntax for delegates. So why cant you
use them where the Framework expects a delegate?
And more importantly, what can you do about it?
BY BILL WAGNER
ON VB

32 Use Iterators in VB Now


Iterators are a crucial part of modern programming,
not least because they provide the basis for
collection traversal using For Each loops. Learn
how to take advantage of them in your code with
several different techniques for creating your own
iterators in VB. BY BILL MCCARTHY

14

D E PA RT M E N T S

6 Editors Note BY PATRICK MEADER


F E AT U R E S

10 Letters to the Editor

14 Retire Your Data Center


Visual Studio 2008, ASP.NET, and the Azure Services Platform combine
to simplify local development of data-intensive Web apps and automate
their deployment in Microsoft data centers. The result: You get maximized
availability and reliability with almost limitless on-demand scalability,
while you pay only for resources consumed. BY ROGER JENNINGS

11 First Looks
Product Listings ..........................................................11
Review ............................................................................13

39 Index of Advertisers

ILLUSTRATION BY RANDY LYHUS

40 The Human Factor


The primary economic justification
for moving data center activity into
the cloud is avoidance of capital
expenditure for servers and associated
networking hardware to handle peak
instead of average loads.

Where Did All the Developers Go?


BY DANIEL APPLEMAN

32

Roger Jennings, Retire Your Data Center, p. 14

www.visualstudiomagazine.com February 2009 VISUAL STUDIO MAGAZINE

0209vsm_TOC_3-4.v10

1/22/09

1:33 PM

Page 4

Online

Check out these and other exclusive online articles and tutorials on the Visual Studio Magazine Web site at

VisualStudioMagazine.com

Content
LEARN FROM THE PROS
As a developer you are constantly
facing the problem of how to keep up
with all the new technologies being
released while still getting your job
done. You keep hearing about solutions
to your programming problems but
the question is: are they the right
solutions for your particular needs?
You could spend hours or even days
trying to find the answers yourself, or
you could let the experts do it for you.
Redmond Media Group Events offers a
variety of conferences and shows
where you can learn about new
technologies and what they might offer you, attend in-depth workshops that
focus on topics specific to your needs, ask questions of the experts, and
interact with your peers to discuss problems they face and what solutions
theyve come up with. Whether its Web design, .NET development, or SQL
Server programming, weve got an event that matches your needs. Visit
RedmondEvents.com to learn more about upcoming conferences and shows.
ONLINE ARTICLES

Practical ASP.NET: Decoding Routes


In his ongoing series on ASP.NET, Peter Vogel talks about the routing
feature included in Service Pack 1 for .NET 3.5 and shows how to set up
a site to use routes. In this installment, Vogel talks about the class file
that you must create to handle the conversion between the meaningful
URL provided by the user and the real path to your WebForm.
LOCATOR+ CODE: VS0902PV1

Practical ASP.NET: Supporting Routing


In this edition of Peter Vogels Practical ASP.NET column he goes beyond
the basics of routing to look at some additional features. The goals here
are to simplify your code and make life easier for your users.
LOCATOR+ CODE: VS0902PV2
ONLINE BLOGS

VSMs Big Issue


Visual Studio Magazines Editor in Chief Patrick Meader and Managing
Editor Guy Wright have started a collaborative blog where they take a
look at some of the bigger issues facing .NET developers these days.

The blog will feature opinions and interviews with industry


insiders, and pose questions designed to stimulate discussion.
Check out their blog at VisualStudioMagazine.com.
LOCATOR+ CODE: VS0901BI
ONLINE TUTORIALS

Classic VB Corner:
Executing Debuggables
Have you ever had one of those problems that only
manifests itself in a compiled EXE, that you simply cant
reproduce in the Classic Visual Basic IDE? Or even worse,
that only occurs on the clients machines, and not on
yours at all? Karl E. Peterson shares his debugging
technique that works in both the IDE and EXE.
LOCATOR+ CODE: VS0902KP1

Classic VB Corner: Got One Right!


Conventional wisdom has it that version 1 of any Microsoft
product or idea is really an alpha, that version 2 is the beta,
and that the safe money rides on version 3. Then, following
version 3, Microsoft generally proceeds to do its best to
upset the success it found in that golden release. Karl E.
Peterson takes a trip down memory lane to one of the most
durable version 3 products ever to come out of Redmond.
LOCATOR+ CODE: VS0902KP2

VirtualizationReview.com
1105 Media recently launched
a new Web site devoted
exclusively to covering all
aspects of IT virtualization.
Virtualization Review.com
helps you harness the power
of virtualization by delivering
news and in-depth coverage of the products, vendors,
issues, and technologies transforming IT through
virtualization. The site also features articles, tips, and
timely information about all aspects of virtualization
including servers, storage, desktops, applications, and
more. Visit VirtualizationReview.com now to start your
move to a more efficient, powerful virtual environment.

.NET NEWSLETTER SIGN-UP


Every week, the .NET Insight e-mail newsletter brings you up-to-date news, technical information, opinions,
interviews, and analysis on topics and technologies such as Visual Basic .NET, C#, SQL Server and data access,
ASP.NET, wireless, Web services, and XML. Sign up for free at VisualStudioMagazine.com.

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

Project17

1/19/09

5:25 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
New
G3/G4, JBIG2, MRC, ABC) and more.
Version
Multi-threaded OCR/ICR/OMR/
16!
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.

Paradise #
D77 09101L01

1,444.99

1,033.

99

949.

View Premier
Paradise #
V55 66101A01

CALLI

VDI Included

programmers.com/vmware

TX Text Control 14

by /n software

The c-treeACE database engine is a high performance


database alternative proven by developers in mission
critical enterprise systems, desktop deployments, and
embedded devices for over 25 years.
Complete set of APIs including ADO.NET, LINQ,
C#, C/C++, ODBC, JDBC, VCL, and dbExpress
Graphical productivity tools
Simple deployment
No DBA or ongoing administration
Low deployment licensing costs
Cross-platform support for all major platforms
including Windows, UNIX, Linux, and Mac OS X

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

/n software Red Carpet Subscriptions give


you everything in one package: communications components for every major Internet
protocol, SSL and SSH security, S/MIME
encryption, Digital Certificates, Credit Card
Processing, ZIP compression, Instant
Messaging, and even e-business (EDI)
transactions. .NET, Java, COM, C++, Delphi,
everything is included, together with per
developer licensing, free quarterly update CDs
and free upgrades during the subscription term.
programmers.com/nsoftware

Paradise #
I21 02201A01

Paradise #
I0M 02501F01

Bottom line: dtSearch manages a terabyte of


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

New
Release!

by FairCom

InstallShield Professional Edition is a powerful


yet easy-to-use solution, ideal for both novice
and seasoned installation developers. While
most homegrown installation tools are not
optimized for current industry standards,
InstallShield Professional makes your life
easy by letting you take advantage of latest
technologiesincluding full support for
Windows Vista.

1,689.

Single Server
Paradise #
D29 02101A07

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.

c-treeACE Professional

by Acresso

99

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

/n software Red Carpet


Subscriptions

Acresso InstallShield 2009


Professional Windows

VMware View Premier


Starter Kit

dtSearch Engine for Win & .NET

programmers.com/acresso

Paradise #
F01 0131

711.99

Make your applications faster, easier to deploy,


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

.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 export without additional 3rd party
Paradise #
tools or printer drivers
T79 02101A01
Nested tables, headers & footers, text
$
99
frames, bullets, numbered lists, multiple
undo/redo, sections, merge fields
Download a demo today.
Ready-to-use toolbars and dialog boxes

919.

programmers.com/theimagingsource

Mindjet MindManager 8

Enterprise Architect 7.1

by Mindjet
Do you harness the wealth of data,
Web pages, and other input that comes
your way every day? Is there a way to
use it more effectively to formulate new
ideas, sharpen your focus, and ultimately
drive your success? New MindManager 8
for Windows is the answer.

Visualize, Document and


New
Control Your Software Project
Release!
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 #
also available for Zachman Framework,
SP6 0001
MODAF, DoDAF and TOGAF, and to
integrate with Eclipse and Visual Studio
$
99
2005/2008.
programmers.com/sparxsystems

Unlike the usual linear-based approach of


most productivity tools, MindManager 8
uses mind-mapping technology to let you
capture, organize, and communicate
information using an intuitive visual
canvas. Youll be able to work smarter
and transform your ideas into action
more quickly.

New
Release!

for Windows
1 User
Paradise #
F15 17301A02
$

299.99

programmers.com/mindjet

196.

Infragistics NetAdvantage
for .NET 2008 Volume 3

Telerik RadControls

Multi-Edit 2008

by Telerik

by Multi Edit Software

by Infragistics
NetAdvantage for .NET is our comprehensive
suite of ASP.NET, Windows Forms, WPF
and Silverlight line of business controls,
components, and tools for the .NET platform.
NetAdvantage for .NET has what you need
to add no-touch AJAX to your Web site,
awesome power and performance to your
Windows Forms application, compelling user
experiences leveraging Windows Presentation
Foundation, and professionally polished user
interfaces (UI).

Add grid, combo, editing, navigation and charting


functionality to your AJAX and ASP.NET projects.
RadControls for ASP.NET enhances your Web
applications by adding AJAX functionality to your
ASP.NET projects. The suite takes full advantage
of the features included in Visual Studio 2005.
RadControls for ASP.NET helps developers deliver
feature-rich, standards-compliant (WAI-A, WCAG
1.0, XHTML 1.1) and cross-browser compatible
Single Developer
Web applications, while significantly cutting
Paradise #
their development time. RadControls for ASP.NET
TB3 01101A01
includes: RadEditor, RadTabstrip, RadInput,
RadCalendar, RadUpload, RadWindow, RadAjax,
$
99
RadGrid, RadCombobox, RadMenu, RadSpell,
RadChart, RadTreeview and more.
programmers.com/telerik

Multi-Edit 2008 delivers, a powerful IDE,


with its speed, depth, and support for
over 50 languages. Enhanced search
functions include Perl 5 Regular
Expressions and definable filters.
Supports large DOS/Windows, UNIX,
binary and Mac files. File Sync
Integration for: Delphi 6, 7, 2005,
C++Builder 6, BDS 2006 and RadStudio
2007, VB 6, VC 6, VS 2003 & VS
2005. Includes file compare, code
beautifying, command maps, and
much more.

Includes Annual Subscription and Source Code

programmers.com/infragistics

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

648.

New
Release!
1-49 User
Paradise #
A30 01201A02

161.99

programmers.com/multiedit

programmersparadise.com

0209vsm_EdNote_6-8.v5

1/22/09

Editors

1:42 PM

Page 6

Note

CALCULATING
THE COST OF CHANGE

BY PATRICK MEADER
editor in chief

redo an edit Ive already done.It doesnt happen often,but it happens,and I tend to react to such events in a consistent manner.
I curse fiercely. I berate myself for not taking better precautions. Then I curse some more as I try to rescue the file.
Will it open in notepad, perhaps? Will a different USB port be
able to see the portable storage device? Experience tells me Im
better off knuckling down and just getting to work, but Im usually too worked up to sit down and start anew immediately. I
should take up yoga or meditation, learn a calming mantra. A
better man might seek solace from his spouse, but I dont want
sympathy or empathy at such times. No, I want to break stuff,
to throw the offending computer out the window. I want to
smash things.
Given how much I hate to redo stuff, I know one thing
definitively: Id hate to be a developer. Having to revisit and
rewrite a half-dozen applications every time the company that
makes my software tools changes something would leave me
feeling queasy; having to retool everything Ive ever done
because of far-reaching changes would mean a weeks-, if not
months-long stream of invectives to make David Mamet
blush. Id be in a semi-permanent rage state, tucked away in a
back office or closet so no one else would have to listen to me.
Its one thing to redo something because I made an error; its
quite another to be forced to redo something because someone else makes a change thats in my best interests,especially
if that change alters how I must approach my job.
But such changes happen all too often in software development. In her column last issue (Ask Kathleen, Windows
Workflow Changes Direction, January 2009), Kathleen Dollard tackled the extensive changes Microsoft is making in the
next version of Windows Workflow Foundation (WF). She
noted how many of the changes planned for version 4 will
break existing WF 3.5 applications, and urged that you put off
developing new WF-based applications if you havent begun
creating them already. She also provided several tips for mini-

mizing the transition to the next version of WF. In her opinion, developers will win over the long run, but she also
acknowledges that the price to achieve these gains is steep.
This months Letters to the Editor include a response to
Dollards article from Matt Fritz. Fritz laments the changes to
WF, as well as other, similar types of changes that hes experienced as a Microsoft developer (see Running the Development
Treadmill, p. 8). Fritz notes that hes a strong believer in the
Microsoft development platform, but goes on to say that using
[developers] as beta and field testers aint right. It costs us and
our companies time and money.
Hes right. These changes do carry a significant cost. The
flip side of his argument is this: Does Microsoft save Fritz
money in the long run by making these changes? The answer
is: It depends. For some developers, the changes will pay for
themselves handily over time; for others, the changes wont
provide the same return, whether because the developer doesnt
need the changes, or because the changes mean abandoning a
platform or technology theyve invested considerable time
and energy learning and deploying.
One positive aspect of the changes to WF is that theyre
occurring before the product matured. Another positive
aspect: WF is not a technology thats in widespread use, and
the current implementation is lacking in significant ways that
the next version will address. Theres a reason more people
dont use it now.
But what if youre one of those who made an investment
in the current version of WF? Microsoft is consciously throwing away the efforts of the developers and companies it convinced to adopt this technology. Its penalizing its own best,
most enthusiastic customersthe people, in fact, who had
paid money for WF. When discussing Microsofts approach to
WF with a couple advisors to VSM, the conversation would
usually start with Big Bad Microsoftfor doing this to its customers but eventually would swing back to discussing why

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

PHOTO BY PAT JOHNSON STUDIOS

I hate doing something twice, especially if I perceive that redoing something


isor should beunnecessary.Sometimes a portable USB storage device gives
out or a file gets corrupted,and I find myself needing to reproduce content or

Project17

1/19/09

5:24 PM

Page 1

Integrate Mapping and GIS into Your Applications


Give your users an effective way to visualize and analyze their data so they can make more informed
decisions and solve business problems.
By subscribing to the ESRI Developer Network (EDNSM), you have access to the complete ESRI
geographic information system (GIS) software suite for developing and testing applications on
every platform. Whether 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.

0209vsm_EdNote_6-8.v5

1/22/09

1:42 PM

Page 8

EDITORS NOTE >> COST OF CHANGE

The product hadnt achieved maturity, nor had it achieved


widespread acceptance, but it seems
unlikely you could see this coming if you were
a company that relied on WF.
someone would put an immature or little-used technology to
work in a mission-critical scenario.
On the surface, this argument strikes me as bizarre. Are
the companies Microsoft convinces to use its technologies culpable when Microsoft changes things up? You expect some risk
when you use a beta or community technology preview technology. Maybe the same holds true for a version 1 product. We
all know the adage that you shouldnt adopt a pre-version 3
product from Microsoft, but we dont actually mean it, do we?
Regardless, that argument shouldnt be in play here: Microsoft
is scrapping a version 3.5 product. The product hadnt
achieved maturity, nor had it achieved widespread acceptance,
but it seems unlikely you could see this coming if you were a
company that relied on WF.
The changes that are occurring in WF wouldnt seem so
significant if there werent other examples of developers having to rework their applications because Microsoft made
changes of a similar scope in other technologies. For example,
the introduction of a .NET version of VB roiled the VB community for years, and were still feeling the aftershocks of some
of those design decisions. Microsoft was careful to note when
it introduced a .NET version of VB that the existing code
developers had written would still work. Similarly, WF 3.5
apps will continue to function. But the blunt truth is: Discontinuing a language or technology is a death sentence to future
development for that language or technology, and even existing applications face hardware and other limits on their
longevity. Sooner or later, developers will have to move on,
whether they want to or because they have to. Even if existing
apps continue to function or are maintained indefinitely, your
ability to earn a living with that tool or technology is severely
limited, and you incur an opportunity cost when you need to
abandon what youre doing now for something else.
Im ambivalent about what constitutes the proper balance
between maintaining backward compatibility and introducing
new features. I want the software I use to provide features that
help me do my job better and save me time over the long run. It
should also be noted that theres a cost to backward compatibility, especially in terms of application performance.As much
as I hate to redo things or have to rework things to achieve
functional equivalence, Im willing to accept changes that break
how things work now in exchange for a significant improvement in how things will work going forwardespecially when
the reason for the change is compelling.

But the central issue is this: My notion of compelling


doesnt always match that of the softwares designers. What
strikes a software developer as essential can strike me as capricious (Microsoft Offices ribbon, anyone?). It might be that a
company could change its product so it serves 95 percent of its
users better, but alienates me in the process. I just dont care
how much the first group wins if the software becomes unusable for me. Thats part of the equation that a company that
creates software must consider. When a company bets Ill like a
feature enough to not mind that it no longer works as it used
to, that company places bets with my money, as well as its own.
And Id like a company that places bets with my money to do
so at least as conservatively as I would. In the case of WF,
Microsoft isnt just betting with other peoples money; its saying the chips those early adopters bought from Microsoft can
never be redeemed. A company ought to be extremely careful
about making such bets, because they represent a major withdrawal from the goodwill bank of their customers. Doing this
even once can be enough to turn a customer against you, so a
change that affects only one person in 20 can still have significant consequences. If a company does this routinely, its only a
matter of time until it affects all its customers.
What concerns me most about what occurred with WF
are the implications these changes portend for the future for
those who use Microsoft technologies. Today WF is a peripheral technology. There are people to whom its important, but
there are other technologies such as Office, Windows, or even
VB that are not so peripheral. For example, Windows Communication Foundation is undergoing its own changes that I
understand will have anadmittedly less dramaticeffect
on backward compatibility. And Microsoft has announced
that LINQ to SQL is basically shifting to something akin to
maintenance mode, which is worrisome for many developers
who see it as their only workable data solution at the
moment. Sure, I expect something else, as yet unannounced,
to take its place (Entity Framework?). But how many times
will you as a developer have to go through this process? More
to the point, how long will you suffer Microsoft to put you
through this? VSM
Talk Back: How do you go about striking the proper balance
between backward compatibility and introducing new features
in your own software? Tell me at vsmedit@1105media.com or
ednote@1105media.com.

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

Project13

9/18/07

3:34 PM

Page 1

Get tips.
Get code.
Get the best how-to
articles on the net.

ONLINE

www.visualstudiomagazine.com

0209vsm_Letters_10.v7

1/22/09

1:37 PM

Page 10

Letters
Letters to Visual Studio Magazine are
welcome. Letters must include your
name, address, and daytime phone
number to be considered for publication. Letters might be edited for form,
fit, and style. Letters express the views
of the individual authors, and do not
necessarily reflect the views of the
editors, VSM, or 1105 Media. Please
send them to Letters to the Editor, c/o
Visual Studio Magazine, 230 California
St., San Francisco, CA 94111; fax
them to 415-814-0961; or e-mail
them to vsmedit@1105media.com.

Running the Development Treadmill

VisualStudioMagazine.com
February 2009 Volume 19 No. 2
Editorial Staff
Vice President, Doug Barney
Editorial Director
Editor in Chief
Managing Editor

Examples Would Be Nice


Bill Wagners article covering what VB developers should know about C# would have been
more useful if he had anchored the gee-whiz discussion of iterators, lambdas, and closures
with at least a mention of the closest approximation in VB.NET functionality, so that we could
have gotten a clue as to what the differences are and why we should care [C# Corner, What
VB Devs Should Know About C#, December 2008]. As it is, this read more like a things I like
to do in C# article than an aid for folks trying to bridge the gap between VB.NET and C#.
Bill Clardy, Orange, Calif., originally posted online

Guy Wright

Managing Editor, RMG

Wendy Gonchar

Associate Managing
Editor, RMG

Katrina Carrasco

Contributing Editors
Andrew J. Brust, Ken Cox, John Cronan, Dan Fergus, John Gavilan,
Roger Jennings, Don Kiely, Martin Kulov, Jeff Levinson, Bill McCarthy,
John Charles Olamendy Turruellas, Keith Pleas, Peter Varhol, 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

athleen Dollards article on the changes in the upcoming version of Workflow [Ask
Kathleen,Windows Workflow Changes Direction, January 2009] reminded me that the
same thing happened with SQL Server DTS 2000/2005, as well as with the MapPoint
object model and ADO. Now SQL Notification Services was dropped in 2008? Are you kidding? It
makes you wonder: How many times do you have to relearn things you used to know how to do?
Im a strong believer in the Microsoft developer platform, and I believe the tools do get
better over time. But using us as beta and field testers aint right. It costs us and our companies
time and money. Now I have Biztalk, Windows Communication Foundation, Windows
Workflow, and LINQ on the wait-and-see list, with more to come, no doubt. If Microsoft
still believes that developers are the foundation of its business, it needs to reconsider this
strategy. Gates himself talks about the great companies of yesteryear that couldnt see when
they started doing things wrong, like DEC, Wang, and Novell (and now General Motors?). Its
a mistake to alienate the developer community. Every company hasor will havea Toyota
in the rearview mirror.
Hey Bill! Come back for awhile; we need you to clean house!
Matt Fritz, originally posted online

Patrick Meader

Associate Editor, Web


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
Marketing Programs Manager

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

Matt N. Morollo
Michele Imgrund
Tracy S. Cook
Videssa Djucich

Neal Vitale
Richard Vitale
Michael J. Valenti

President, 1105 Events

Dick Blouin

Vice President, Finance


& Administration

Christopher M. Coates

Vice President, Audience


Marketing & Web Operations
Vice President, Information
Technology & Web Operations
Vice President,
Circulation
Chairman of the Board

Abraham M. Langer
Erik A. Lindgren
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.

Correction:
The recent First Looks review of Compuwares DevPartner Studio contained an error when
discussing the capabilities of that tools Performance Analyzer [Understand What Your App
Does, January 2009]. Performance Analyzer can be configured to analyze ASP.NET applications
running on both local and remote computers. You can read an updated version of the review
online at VisualStudioMagazine.com that explains the general steps you need to take to use
Performance Analyzer with ASP.NET. Locator+ code: VS0901FL
VSM regrets the error.
10

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

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.

0209vsm_FirstLooks_11-13.v7

1/22/09

1:39 PM

Page 11

First
PRODUCT LISTINGS

Looks

REVIEWS

DataDirect Connect for ADO.NET,


List & Label 14, and MobileForms Toolkit 2009
DataDirect Connect for ADO.NET

DataDirect Technologies has released DataDirect Connect for ADO.NET data providers. With
DataDirect Connect for ADO.NET, developers
can write and deploy .NET enterprise applications that connect to multiple databases
including Oracle, DB2, Microsoft SQL Server, and
Sybase. The latest product release includes
new provider features for each major database,
new performance-tuning options, and introduces DataDirect Bulk Load, a standards-based
implementation of bulk-load functionality that
provides a method for moving volume-intense
data across Oracle, DB2, Microsoft SQL Server,
and Sybase databases, without having to
deploy and load client libraries.
The suite of ADO.NET data providers uses
a 100 percent managed code architecture,
therefore DataDirect Connect for ADO.NET
eliminates the need for database client
libraries. Because managed code runs in the
Common Language Runtime (CLR) environment it reduces risks and closes holes that
unmanaged code leaves exposed, providing
developers with versatile deployment
options available in both application and
client-server environments. With DataDirect
Connect for ADO.NET developers get full support for .NET Framework.
The latest release of DataDirect Connect
for ADO.NET additionally offers performance
enhancements including additional tuning
options that support a variety of application
performance scenarios and statement caching,
a connection option that requires no changes
to the application and can increase the efficiency of applications connecting to Oracle,
DB2, and Sybase.

DataDirect Connect for ADO.NET now supports Oracle 11g R2, SQL Server 2008, and
DB2 iSeries V6R1. A complete list of database
provider features is available online.
DataDirect Connect for ADO.NET
DataDirect Technologies
Price: Contact vendor for pricing
Web: www.datadirect.com
Phone: U.S.: 800-876-3101;
World: 44 (0) 1753 218 930

List & Label 14


Combit has released version 14 of its reportgenerating software List & Label. Among the
new features is the inclusion of
a real-data-preview, so changes
can now be seen with real data,
without having to leave the
Designer. Within the preview
theres also an integrated index
to ease navigation through the
report. Additionally, its now
possible to mix different formats within the same document. Now multiple formats are
possible as well as the choice of
printer type. Using a single
record from the database, the
user can define real rows that
can be represented in a line diagram with
respect to time.
Also new for Professional and Enterprise Edition 14 is the generation of DOM code. DOM
code is now automatically provided by the List
& Label object model directly from the project
file. The DOM viewer has been completely
reworked, and now includes a search utility for

objects and properties. Besides functions and


objects, the user can now create their own
designer actions with DOM and Designer. New
with version 14 is support for Delphi 2009.
Additionally, the project parameter interface
has been extended with a method and allows
the storage of SQL queries or even complete
data sets within a project.
Other additions in version 14 include an
extended formula assistant, better overview of
property values, magnetized help lines in the
Designer, and your own Designer actions.
With List & Label software, developers can
equip their own applications with functions to
assist in the generation of reports, statistics,

forms, lists, and labels. Only a few lines of code


are required to integrate the report generator
into existing applications. The Designer, which
can be passed on to end users without having
to pay additional license fees, is available in 15
languages. The development tool for reporting
functions as well as Web reporting is available
in German or English and can process almost all

VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE

11

0209vsm_FirstLooks_11-13.v7

1/22/09

1:39 PM

Page 12

Instantly Search
Terabytes of Text

PRODUCT LISTINGS

REVIEWS

N dozens of indexed,

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

character sets. All three editions of List & Label can be integrated into a
large variety of programming languages.
List & Label 14
Combit GmbH
Price: Standard Edition is available for 370 euro; Subscription Editions Professional starts at 1,380 euro; and Enterprise at 2,094 euro.
Web: www.combit.net/en

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

Phone: +49 (0) 7531 90 60 10

MobileForms Toolkit 2009

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

Resco has released an updated suite of controls and libraries for .NET
Compact Framework (CF) developers targeting Pocket PCs, smartphones, and Windows CE .NET devices. The new suite, MobileForms
Toolkit 2009, is optimized for Microsoft Visual Studio 2008 and
Microsoft .NET CF 3.5. Major enhancements to the suite include adding
Touch functionality to all controls and a new graphical user interface.
Adding Touch functionality to mobile applications is a simple matter of
setting up a single property in Microsoft Visual Studio.
MobileForms Toolkit 2009 includes many controls and libraries that
tackle most of the common problems that developers encounter developing for the mobile environment. Tools include SmartGrida grid control with built-in auto edit capabilities, Touch scroll support, and the
ability to save different SmartGrid layouts to XML files; AdvancedList
a professional list control suitable for small displays of mobile devices
and includes DelayLoad functionality that loads only visible data for
fast previews while additional data is loaded on demand; CompactCharta charting control with five chart types including Pie, Bar,
Line, Doughnut, and Area charts; OutlookWeekCalendar and OutlookMonthCalendarday/week and month/year appointment scheduling
controls; OutlookDateTimePickera modern version of a common control providing advanced styles; DetailViewfor creating mobile user
input forms where input controls are collected in a compact environment giving the form standard Windows Mobile look and feel; InkBox
an ink control suitable for quick notes or signatures; ImageBoxan
image control supporting various graphic formats; CustomKeyboarda
flexible control supporting custom keyboard layouts; OutlookShortcutBara popular shortcut control common for all modern applications; a
library for playing and recording audio; and more.
For more information about the Resco MobileForms Toolkit 2009 and
a complete list of controls and libraries, visit http://tinyurl.com/9wukrz.
MobileForms Toolkit 2009
Resco
Price: Standard Edition $499.95, Professional Edition $999.95,
Enterprise Edition $1,999.95
Web: www.resco.net
Fax: +421 2 090 2010

Contact dtSearch for


fully-functional evaluations

Editors Note: Please send product information to New Products Editor, c/o
Visual Studio Magazine, 230 California St., San Francisco, CA 94111; Phone:
415-814-0950, fax: 415-814-0961; e-mail vsmedit@1105media.com.

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

0209vsm_FirstLooks_11-13.v7

1/22/09

PRODUCT LISTINGS

1:39 PM

Page 13

REVIEWS

Develop Help Content Like


a Professional
MadCap Flare 4.1 is a professional development environment for creating documentation for a wide range of
formats based on a single-source (XML). As a programming writer, I was struck by how Flare offers so many
must-have features of Visual Studio to technical writers.
Information developers have much in common with
software developers. They want to work in a familiar,
integrated environment that organizes files, flags
errors, assists with testing and reporting, controls the
build process, and generally makes them more efficient.
Flare does all this and more. For example, it takes a cue
from software development by allowing projects to link
to common content. As with pre-built software components, you can store and update shared pagesfor
example, legal disclaimersin one place. All of the
projects and documentation suites can incorporate the
latest version into the build automatically.
IntelliSense, an essential feature for writing code, is
REDUCE KEYSTROKES AND WRITERS CRAMP You can store
now available in documentation projects. As you write
frequently used resources as snippets in MadCap Flare 4.1. Just
instructions, the IDE suggests phrases that appear in drag-and-drop the content into the editor. For larger files, you can
the projects topics. Likewise, you can drag snippets link to complete boilerplate topics from a central location.
and drop them directly into a topic.
To accommodate Windows Presentation Foundation (WPF)
Help 2). Another valuable output would be XAML markup for
and Silverlight software projects, Flare now supports an array of
Silverlight apps.
vector graphic types, including the XAML format. A nice touch is
Source control is essential for programmers and writers alike.
the ability to convert those images automatically to Web-safe
When you create a Flare project, theres a checkbox to bind to a
formats such as .GIF or .JPG for browser-hosted output. Speaking
source control provider, including Visual SourceSafe, Team
of formats, Madcap creates .PDF and .XPS files directly, without
Foundation Server, and a generic plug-in. The Bind Project
requiring Microsoft Word, Adobe FrameMaker, or Adobe Acrobat
option recognized and connected to my SourceGear Vault
as intermediaries. Unfortunately, MadCap still doesnt generate
providera real bonus. That said, the IDE crashed when I tried to
files that integrate with Visual Studios help collections (MS
cancel out of a Vault connection using the Advanced option.
Youll appreciate the small conditional-text touches like
automatically adjusting cross-references for the medium. For
AT A GLANCE
example, in a PDF you might generate as shown on p. 32
where the HTML version, which doesnt use page numbers,
MadCap Flare 4.1
would substitute a hyperlink.
MadCap Software
Web: www.madcapsoftware.com
MadCaps user assistance is polished and plentiful. The GetPhone: 858-320-0387
ting Started Wizard, sample projects, videos, dynamic help, and
Price: $899
help topics get you up to speed and over the hurdles.
Quick Facts: Integrated development environment
On the downside, Flare sets off your firewall alarm as it
for authoring user manuals, online help, and Web
accesses the network to validate your license key usage, and
pages. Generates multiple output formats from a
single XML source.
the software stops working until youor the IT department
Pros: File linking and conditional text; XML editor;
unblock its stealth access. With product announcements that
IntelliSense support; drag-and-drop snippets; sourcestart with Dear Propeller Heads! the folks at MadCap seem
control friendly; command-line mode; built-in .PDF
friendly, fun, and upfront. Thats why a high-handed licensing
and .XPS generators; valuable user assistance.
Cons: Doesnt generate integrated help for Visual
approach is disappointing and out of character. VSM
Studio help collections; sets off firewall alarm to
validate license key.

Ken Cox is a Canadian .NET programming writer and the author of


ASP.NET 3.5 for Dummies (For Dummies, 2008).

VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE

13

0209vsm_F1Retire_14-25.v13

F E AT U R E

1/22/09

1:41 PM

Page 14

R E T I R E Y O U R D ATA C E N T E R

Retire
Your Data
Center
Visual Studio 2008, ASP.NET, and the Azure Services Platform
combine to simplify local development of data-intensive Web
apps and automate their deployment in Microsoft data centers.
The result: You get maximized availability and reliability with
almost limitless on-demand scalability, while you pay only for
resources consumed. BY ROGER JENNINGS

T
VB.NET
C#
SQL Server
ASP.NET
XML
Other:
Azure Services
Platform
Elastic Compute
Cloud (EC2)

14

cloud computing. Microsofts cloud candidate


Windows Azureoccupied the bulk of Ozzies
Day One PDC keynote and was the subject of 39
sessions, more than twice as many as the nextmost-discussed topicVisual Studio. Windows
Azure is an Internet-facing operating system that
promises to enable .NET developers to leverage
their current ASP.NET,Windows Communication
Foundation (WCF), and Windows Workflow programming skills to deploy .NET Web applications
to Microsofts newly built data centers quickly and
easily. Microsofts message to VS developers is to
use your existing tools, knowledge, and skill set
for projects you deploy to Windows Azure.

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

The Azure Services Platform, for which the


Windows Azure OS serves as the foundation,
provides massively scalabletable and blob storage
services, a persistent message-queue service, several .NET utility services (formerly code-named
Zurich), a Live operating environment, and the
successor to SQL Server Data Services thats now
called SQL Data Services (see Figure 1, opposite
page). Ill give you a brief introduction to the
platforms objectives and its architectural details
to achieve them, and describe how Azure differs
from its cloud-based competitors. Then Ill drill
down into programming data-intensive Web
applications that take advantage of Azures

ILLUSTRATION BY RANDY LYHUS

TECHNOLOGY TOOLBOX

he three-year hiatus between the Microsoft Professional


Developers Conference (PDC) 2008 and its 2005 predecessor
gave Ray Ozzie and his newly expanded development team
the opportunity to play catch-up with Amazon.com Inc., Google Inc.,
and other major players in the race to capture developer mindshare for

0209vsm_F1Retire_14-25.v13

1/22/09

1:41 PM

Page 15

R E T I R E Y O U R D ATA C E N T E R

The primary economic justification for moving data


center activity into the cloud is avoidance of
capital expenditure for servers and associated networking
hardware to handle peak instead of average loads.

ILLUSTRATION BY RANDY LYHUS

unique development and deployment tools. Finally, Ill discuss an


instrumented ASP.NET test harness for Azure Table Services that you
can download, run locally with the community technology preview
(CTP) of the Windows Azure SDK, and then deploy to the Windows
Azure CTP running in a Microsoft data center (see the Go Online
information on p. 25 for details). Future VSM issues will cover Blob
Services, Queue Services, SQL Data Services, and .NET Services.
Cloud computing is a catch-all term for Webbased utility computing operations provisioned as
pay-by-usage software services and accessed over the
Internet. Amazon Web Services and Google App
Engine are probably the best-known cloud-computing
services, but Web-hosting firms, such as Rackspace
Hosting Inc., and specialty vertical-market providers
like SalesForce.com Inc., also fit into the cloud-computing picture. The primary economic justification for
moving data center activity to the cloud is avoidance of
capital expenditure for servers and associated networking hardware to handle peak instead of average
loads. Other benefits include reduction of IT management and operating costs, improved application reliability and availability, and the ability to scale Web
applications up-and-out quickly to match rapid
increases in traffic. When the traffic subsides, such as
after holiday sales, resources can return to the pool
automatically or by manual intervention. Cloud
deployment also offers a rapid method for proving
Web application or service concepts without making
infrastructure investments.
Azure Echoes AWS
Azures architecture most closely resembles a combination of Amazon Web Services (AWS) Elastic Compute Cloud (EC2) running Windows Server 2003 R2
with SimpleDB for semi-structured tables, Simple
Storage Service (S3) for blob storage, Simple Queue
Service (SQS) for messaging between applications,
and Elastic Block Store to persist other instance data
(see Table 1, p. 23, and Additional Resources, p. 25).
Amazon EC2 running Windows Server and SimpleDB
are in the beta-testing stage, as is the Google App
Engine (GAE). Microsoft wont reveal pricing for
Azure services until later in 2009 when version 1 is

closer to release. However, the current word is that Azure will be


competitive, presumably with the AWS, GAE, or both price
lists, and the Service Level Agreement will be factored into
monthly charges. Its not known whether Microsoft will adopt
Googles approach of billing only for App Engine usage in excess
of fixed quotas for free CPU time, network ingress and egress,
and storage.

FIGURE 1 Move ASP.NET Web Apps to the Cloud The foundation for the Azure
Services Platform is the Windows Azure operating system, which provides the fabric
for virtualized Windows 2008 Server instances; schemaless persistent table, blob,
and queue storage; .NET Services for managing authentication/ authorization, interservice communication, and workflows; and SQL Services for data management with
relational database features and consumer-oriented Live services. Like the Google
App Engine, Azure provides a development environment that emulates its cloud
operating system and storage services.

VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE

15

0209vsm_F1Retire_14-25.v13

1/22/09

1:41 PM

Page 16

R E T I R E Y O U R D ATA C E N T E R

Windows Azure runs on Windows Server 2008 with virtualization provided by Microsofts Hyper-V hypervisor technology
to deliver a runtime fabric that handles load balancing, data
replication, and resource management. According to Microsofts
Erick Smith, the Azure Fabric Controller maintains a graph of
the inventory of physical and virtual machines, load balancers,
routers, and switches it manages in a Microsoft data center. Edges
of the graph are interconnections of various types, for example,
network, serial, and power cables. You specify the topology of
your servicethe number and connectivity of roles, the attributes and locations of the various hardware components, as well
as the numbers of fault/update domains and maximum
instances of each role you need with a declarative Service Model.
In this respect, Windows Azure management features are similar
to those offered by RightScale for AWS and employed by the
GAE. Roles are runnable components of an application; role
instances run on the fabrics nodes and channels connect roles.

The CTP limits applications to managed code authored in VS


2008 that runs under a custom version of medium trust Code
Access Security. Microsoft promises future support for Python,
Ruby, native code, and Eclipse. Fault domains for role instances
represent a single point of failure, such as a rack; update domains
for performing rolling software upgrades or patches run across multiple fault domains (see Figure 2). Ultimately, youll be able to specify
your Service Model with Oslos domain-specific language tools and
store the model in the Oslo repository.
The current CTP released at PDC 2008 doesnt expose the
Service Model; instead the Windows Azure Tools for Microsoft
Visual Studio add-in defines common Azure application-role
templates for Web Role, Worker Role, and Workflow. The Web
Role enables creating a new Web Cloud Service or Web and
Worker Cloud Service as an ASP.NET Web application running
on IIS 7 instance(s) under Windows Server 2008 (see Figure 3,
opposite page). Windows Azure doesnt support file-system Web
site projects. Worker Roles are asynchronous operations that perform background processing when
added to Web projects; roles also can create standalone Worker Cloud Services. The most common
use for Worker Roles is processing messages added
to an Azure Queue. Workflows enable writing
standalone CloudSequentialWorkflow projects or
can be incorporated in Web or Worker Cloud Services. Azures October 2008 CTP limits testers to a
maximum of 2,000 runtime hours with up to eight
instances of a single production application having one Web and, optionally, one Worker Role.

FIGURE 2 Distribute Instances Across Azure Domains The Azure Fabric


Controller automates deploying computing and network resources to support
application instances on multiple fault domains (server racks) to prevent a single
point of failure. Instances run on nodes, which usually are virtualized Windows
2008 Servers but can be physical machines; Azure currently maintains a master
and two replicas of application roles. XCopy application deployment simplifies
adding new or upgrading applications. Rolling upgrades or service releases only
affect a single update domain at a time to prevent application downtime. Unlike
Amazon and Google services, Azure offers an intermediate Staging deployment
for new apps that developers can test with a private URL, then deploy to the
accounts public Production URL (see Figure 6, p. 22).

16

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

Emulate the Cloud Locally


Azure was in a limited (private) beta stage at press
time. You can apply for admission to the Azure Services Platform beta program at the Microsoft Connect site; the OakLeaf blog offers a walkthrough of
the somewhat convoluted sign-up process (see
Additional Resources, p. 25). However, you dont
need to wait for a beta invitation because downloading and installing the Windows Azure SDK
(October 2008 CTP) and Windows Azure Tools for
Microsoft Visual Studio (October 2008 CTP) lets
you emulate the Azure Services Platform on your
local development machine. Installing the SDK
adds a start menu folder with Development Fabric
and Development Storage nodes, as well as Release
Notes, Windows Azure SDK Command Prompt,
and Windows Azure SDK Documentation nodes.
Choosing the Development Fabric and Development Storage nodes or clicking their icons in the
Taskbars Notification Area opens management
dialogs for the two service emulators (see Figure 4,
p. 18).
When you specify one of the Cloud Services
templates (typically a Web Cloud Service) for a

0209vsm_F1Retire_14-25.v13

1/22/09

1:41 PM

Page 17

R E T I R E Y O U R D ATA C E N T E R

Downloading and installing the Windows Azure SDK


(October 2008 CTP) and Windows Azure Tools for
Microsoft Visual Studio (October 2008 CTP) lets you
emulate the Azure Services Platform on
your local development machine.
new VS 2008 project, the add-in generates a solution with a
Cloud Service project, which contains ServiceConfiguration.cscfg and ServiceDefinition.csdef files, as well as an
ASP.NET Web Role application. You also must expand the Windows Azure SDKs \Program Files\Windows Azure SDK\v1.0\samples.zip file to a temporary folder. Then add the \Temp\StorageClient\ Lib\StorageClient.csproj and \Temp\HelloFabric\Common\Common.csproj projects to your solution by right-clicking
on the solution in Solution Explorer and selecting Add an Existing
Project. Add the two project files as references to
your ProjectName_WebRole application. The
StorageClient library delivers wrapper classes for
REST API operations on Azure Blob, Queue, and
Table Services; the Common library provides
ApplicationEnvironment classes for logging and
other local fabric-related activities. The Azure
Tools add a reference to Microsoft.ServiceHosting.ServiceRuntime.dll for the local fabric automatically. Right-click on the Cloud Service project node and choose Create Test Storage Tables to
add ProjectName tables to your local instance of
SQL Server 2005+ Express. At this point, you can
import page and class files for existing ASP.NET
projects or create a new Web application from
scratch.
Settings in the ServiceConfiguration.cscfg file
determine whether your application uses local or
cloud storage when emulating the hosted service.
Heres a ServiceConfiguration.csfg file with entries
for both local and cloud storage with AccountSharedKey values abbreviated:
<?xml version="1.0"?>
<ServiceConfiguration
serviceName="SampleWebCloudService"
xmlns="http://schemas.microsoft.com/
ServiceHosting/2008/10/
ServiceConfiguration">
<Role name="WebRole">
<Instances count="3"/>
<ConfigurationSettings>
<Setting name="AccountName"
value="devstoreaccount1"/>

value="Eby8vd MGw=="/>
<Setting name="BlobStorageEndpoint"
value="http://127.0.0.1:10000/"/>
<Setting name="QueueStorageEndpoint"
value="http://127.0.0.1:100001/"/>
<Setting name="TableStorageEndpoint"
value="http://127.0.0.1:10002/"/>
<!-- <Setting name="AccountName"
value="<youraccountname>"/>

FIGURE 3 Choose a Pre-configured Cloud Service, Role or Workflow The


October 2008 community technology previews Windows Azure Tools for
Visual Studio 2008 add-in provides pre-configured Web Cloud Service, Worker
Cloud Service, Web and Worker Cloud Service, Web Role, Worker Role, and
CloudWorkflow templates for Windows Azure Web applications and services.
Creating a new Web Cloud Service adds a ProjectName service node with
ServiceConfiguration.cscfg and ServiceDefinition.csdef files, and a pointer to a
ProjectName_WebRole project, as shown for this articles SampleWebCloudService
project in Solution Explorer. Common and StorageClient class libraries provide local
logging features and wrapper classes for Azure Storage Services REST API. The
Limog class contains code to regenerate the CustomerTable.

<Setting name="AccountSharedKey"

VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE

17

0209vsm_F1Retire_14-25.v13

1/22/09

1:41 PM

Page 18

R E T I R E Y O U R D ATA C E N T E R

Azure tables have a distributed architecture thats related to


Googles Bigtable, and Microsoft says Azure tables are
designed to scale to billions of entities and terabytes of data.
<Setting name="AccountSharedKey"
value="<YourPrimaryAccessKey>" />
<Setting name="BlobStorageEndpoint"
value="http://blob.core.windows.net" />
<Setting name="QueueStorageEndpoint"
value="http://queue.core.windows.net" />
<Setting name="TableStorageEndpoint"

ing 127.0.0.1 (localhost) port numbers appear in Figure 4s


Development Storage dialog. YourPrimaryAccessKey is the
base64Encoded Primary Access Key value on the Azure Portals
Project Summary page.
Each <Setting name="*Endpoint" /> element in the ServiceConfiguration.csfg file must have a corresponding entry in the
ServiceDefinition.csdef file (indicated here in red):

value="http://table.core.windows.net" /> -->


</ConfigurationSettings>
</Role>
</ServiceConfiguration>

<?xml version="1.0" encoding="utf-8"?>


<ServiceDefinition name="SampleWebCloudService"
xmlns="http://schemas.microsoft.com/
ServiceHosting/2008/10/ServiceDefinition">

Settings for cloud storage services are commented out in the


preceding example; local setting values are the same for all users.
The <Instances count="3"> element causes three instances
to run in the Development or Azure Fabric. Note that the preced-

<WebRole name="WebRole">
<InputEndpoints>
<!-- Must use port 80 for http and port 443 for
https when running in the cloud -->
<InputEndpoint name="HttpIn"
protocol="http"
port="80" />
</InputEndpoints>
<ConfigurationSettings>
<Setting name="AccountName"/>
<Setting name="AccountSharedKey"/>
<Setting name="BlobStorageEndpoint"/>
<Setting name="QueueStorageEndpoint"/>
<Setting name="TableStorageEndpoint"/>
</ConfigurationSettings>
</WebRole>
</ServiceDefinition>

FIGURE 4 Manage Local Developer Fabric and Storage Instances This multiple
exposure screen capture shows log data for three instances of this articles
SampleWebCloudService project running in the Development Fabric and emulated
Azure Storage Services for blobs, queues, and Azures schemaless Entry-AttributeValue tables. A local SQL Server 2005+ Express instance holds a DevelopmentStorageDb database to store blobs, queues, and account information as
well as a ProjectName database containing Azure Table Services data. Starting
up the Development Fabric and Development Services slows VSs compile and
run operations significantly.

18

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

If the <Setting> element name attribute values dont


match in the two files, you receive an Invalid configuration file message when running in the Developer
Fabric; the Azure Fabric adds the names of missing or
misspelled <ConfigurationSettings> elements. The
matching <Setting> name attributes requirement is
hidden in an Issues and Constraints in the Windows
Azure Tools and SDK white paper (see Additional
Resources, p. 25). The <InputEndpoint> elements
port attribute determines whether Azure expects
clear-text HTTP or encrypted HTTPSSecure Sockets Layer (SSL)protocol. Setting up HTTPS requires
completing the entries on the SSL page of the ProjectName nodes properties sheet.
Connect to Schemaless EAV Tables with REST
Windows Azure tables are similar to the schemaless
Entity-Attribute-Value (EAV) tables of the initial SQL

0209vsm_F1Retire_14-25.v13

1/22/09

1:41 PM

Page 19

R E T I R E Y O U R D ATA C E N T E R

Server Data Services (SSDS) CTPs Authority-ContainerEntity (ACE) model, which has been incorporated
into Windows Azure as SQL Data Services (SDS).
The EAV data model is much more scalable than
conventional file system-based relational tables. Azure
tables have a distributed architecture thats related
to Googles Bigtable, and Microsoft says Azure tables
are designed to scale to billions of entities and
terabytes of data. Azure and SDS table versions offer
free-form open properties (formerly flex properties) or property bags and permit adding or removing table attribute/value pairs at will. However, the
two versions have different required properties and
sets of data types.
Azure tables require PartitionKey and RowKey
string property values to form a concatenated primary
key and automatically add a DateTime Timestamp
property value to each entity. SDS entities require a
unique Id property value, permit an optional Kind
property, and supply an autoincrementing Version
FIGURE 5 Stage Azure Apps for Testing before Production Deployment
value for concurrency management.
Azure tables support Binary, Bool, DateTime, Windows Azures Click-Twice deployment approach lets you test your project in
Double, GUID, Int, Long, and String data types; SDS a Staging instance with a private guid.cloudapp.net URL before placing it in prooffers Base64Binary, Blob, Boolean, DateTime, Deci- duction with your AccountName.cloudapp.net URL. Right-clicking on the Projectmal, and String data types. SimpleDB property values Name service node and choosing Publish opens a page that lets you browse for
are limited to strings and require padding numbers your project ProjectName.cspkg package and ServiceConfiguration.cscfg files in
with leading zeros and adding offsets for negative val- the projects \ProjectName\bin\Debug\Publish folder. Clicking OK exposes the
ues, which complicates client programming. My Hosted Service page with the Staging instance in Allocated mode. Click Run to
Comparing Google App Engine, Amazon SimpleDB, start the staged service, test it with the private URL, click Suspend, and then
and Microsoft SQL Server Data Services blog post click the exchange icon to place it in production.
provides a detailed comparison of those three services
(see Additional Resources, p. 25).
Azure tables and SDS containers are units of consistency
Progress Toward Standards
and have a size limit of 2GB; SimpleDB domains, which correMicrosofts data-access teams are moving to standards-based
spond approximately to Azure tables, hold a maximum of 10GB.
RESTful data access protocols at an increasingly rapid pace.
Azure tables and SDS containers have strong consistency; all
Azure tables, blobs, and queues have a REST API, while SDS and
observers see the same value immediately after an update; special
SimpleDB provide REST and SOAP protocols.
algorithms guarantee consistency over multiple replicas. SimAzure tables and SDS use a new version of the ADO.NET
pleDB domains promise eventual consistency after a period with
Data Services (Astoria) runtime, which supports open propno new updates, but Amazon doesnt specify the inconsistent
erties with the Atom syndication wire protocol and operates
windows maximum duration.
with the existing ADO.NET Data Services client libraries and
Transactions are crucial for online order processing and
tools. Pablo Castros ADO.NET Data Services in Windows
other business applications, but neither Azure nor SimpleDB
Azure: pushing scalability to the next level blog post describes
tables currently support transactions. However, the Azure team
how the Astoria team modified the runtime to accommodate a
promises that their tables will at some point in the future perdynamic open properties provider for Azure and SDS, in addiform atomic transactions across multiple entities within the
tion to the static CLR types defined by the more common Entity
same partition. Partitions are similar to Bigtables tablets with
Framework and LINQ to SQL data providers (see Additional
some characteristics of the App Engines entity groups thrown
Resources, p. 25).
in; a single VM or server stores all entities in the table with the
The REST API for Azure defines HTTP GET (query), POST
same PartitionKey value. (App Engine offers transactions for
(create), PUT (update with properties replaced), MERGE (update
entities in the same Entity Group.) The CTP provides equality
without properties replaced), and DELETE operations on entities.
filters only and sorts in PartitionKey/RowKey order; inequality
Heres the GET request header for the second page of the sample
filters and developer-specified secondary indexes for alternative
projects Customers GridView, which starts with CENTC as the
sorting orders are slated for the release version.
CustomerID and RowKey value:

VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE

19

Project1

1/21/09

11:14 AM

Page 1

Project1

1/21/09

11:15 AM

Page 2

0209vsm_F1Retire_14-25.v13

1/22/09

1:41 PM

Page 22

R E T I R E Y O U R D ATA C E N T E R

GET /CustomerTable()?$top=12&NextPartitionKey=
Customer&NextRowKey=CENTC HTTP/1.1
User-Agent: Microsoft ADO.NET Data Services
x-ms-date: Fri, 19 Dec 2008 23:37:31 GMT
Authorization: SharedKeyLite oakleaf:Z/KA 5Yc=
Accept: application/atom+xml,application/xml
Accept-Charset: UTF-8

$top operator. The Atom-formatted response body includes xms-continuation-NextPartitionKey and x-ms-continuationNextRowKey continuation tokens to identify the first entity of
the next page. Optimistic concurrency management uses eTags
and Timestamp values to detect conflicts with If-Match HTTP
headers. Heres the GET response header and abbreviated body
of the second GridView page:

DataServiceVersion: 1.0;NetFx
MaxDataServiceVersion: 1.0;NetFx

HTTP/1.1 200 OK

Host: oakleaf.table.core.windows.net

Cache-Control: no-cache
Content-Type: application/atom+xml;charset=utf-8

Azure Table and Queue Services require authentication, as do


private Blob Services; blobs are the only storage type that can be
specified for public access. The Authorization headers SharedKeyLite value, shown abbreviated in the preceding request header, is specific to the Astoria client and is the HMAC-SHA256
encoding of this string:

Server: Table Service Version 1.0 MicrosoftHTTPAPI/2.0


x-ms-request-id: 2a109a5d- f6e
x-ms-continuation-NextPartitionKey: Customer
x-ms-continuation-NextRowKey: FRANK
Date: Fri, 19 Dec 2008 23:37:00 GMT
Content-Length: 15691

Fri, 19 Dec 2008 23:37:31 GMT\n/oakleaf/Tables


<?xml version="1.0" encoding="utf-8"

Queries return a maximum of 1,000 entities and support the

standalone="yes"?>
<feed xml:base=
"http://oakleaf.table.core.windows.net/"
xmlns:d="http://schemas.microsoft.com/
ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/
ado/2007/08/dataservices/metadata"
xmlns="http://www.w3.org/2005/Atom">
<title type="text">CustomerTable</title>
<id>
http://oakleaf.table.core.windows.net/
CustomerTable
</id>
<updated>2008-12-19T23:37:01Z</updated>
<link rel="self" title="CustomerTable"
href="CustomerTable" />
<entry m:etag="W/&quot;datetime'2008-129T22%3A10%3A30.2752Z'&quot;">
<id>
http://oakleaf.table.core.windows.net/
CustomerTable(PartitionKey='Customer',
RowKey='CENTC')

FIGURE 6 Try the Live Table Services Sample Project You can run this articles
SampleCloudWebService.sln project in the Azure Services Platform CTP at
oakleaf.cloudapp.net. The Default.aspx page contains a paged GridView that
displays 12 Northwind Customers records per page and a FormView for
inserting new entities; both controls are bound to an ObjectDataSource that
connects to an Azure table. (The projects FormView is disabled in the public
version.) The Count button iterates the entity set; clicking on Delete All
Customers deletes the table and Create Customers recreates the table and
adds Customer entities. Update Customers toggle the addition or deletion of
a plus sign (+) after the CompanyName. The Time textbox displays the
elapsed time of the server components of these operations.

</id>
<title type="text"></title>
<updated>2008-12-19T23:37:01Z</updated>
<author>
<name />
</author>
<link rel="edit" title="CustomerTable"
href="CustomerTable(PartitionKey=
'Customer',RowKey='CENTC')" />
<category term="oakleaf.CustomerTable"
scheme="http://schemas.microsoft.com/
ado/2007/08/dataservices/scheme" />

22

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

0209vsm_F1Retire_14-25.v13

1/22/09

1:41 PM

Page 23

R E T I R E Y O U R D ATA C E N T E R

Windows Azure management features are similar


to those offered by RightScale for AWS and employed
by the Google App Engine.
<content type="application/xml">

</entry>
</feed>

<m:properties>
<d:PartitionKey>Customer</d:PartitionKey>
<d:RowKey>CENTC</d:RowKey>
<d:Timestamp m:type="Edm.DateTime">
2008-12-19T22:10:30.2752Z
</d:Timestamp>
<d:Address>
Sierras de Granada 9993
</d:Address>
<d:City>Mxico D.F.</d:City>
<d:CompanyName>
Centro comercial Moctezuma
</d:CompanyName>
<d:ContactName>
Francisco Chang
</d:ContactName>

</m:properties>
</content>

Use LINQ to REST to Query Tables


ADO.NET Data Services enables a subset of the LINQ Standard
Query Operators to compose LINQ queries, which an expression
tree translates to an HTTP URI. The StorageClient librarys
TableStorage, TableStorageDataServiceContext, and TableStorageDataServiceQuery classes and TableStorageEntity abstract
class handle interaction with the ADO.NET Data Services client
library (System.Data.Services.Client) and implement Azure Table
Services helper functions for CRUD operation on tables, authentication, and error handling.
You define a TableName DataModel type that implements
TableStorageEntity and a TableName DataServiceContext that
inherits from TableName DataServiceContext. Next, you instantiate the latter in the Page.Preload event handler with a StorageAccountInfo type as its parameter, and create and execute a LINQ to
REST query with optional paging as shown here for the sample
project:

Feature

Windows Azure (October CTP Instance)

Amazon EC2 Beta (Default Instance)

Host OS

Windows Server 2008 Core, 64-bit

Linux Xen kernel (AKI)

Guest OS

Windows Server 2008 Enterprise, 64-bit

Windows Server 2003 R2, 32-bit

Hypervisor

Hyper-V

Xen

CPU

1.5 - 1.7 GHz x64 equivalent

1.7GHz

Memory

1.7GB

1.75GB

Network

100Mbps

250Mbps

Transient storage

250GB

160GB

Persistent storage

50GB Azure storage (maximum for CTP)

Elastic Block Store (up to 1TB)

Authentication/
Authorization

NET Access Control: LiveID, username/ password, X.509 certs, Information Card

Windows with Authentication Services (surcharge)

TABLE 1 Compare Windows Azure October 2008 CTP and Amazon EC2 with Windows Server Beta On Sept. 30, 2008, Amazon.com Inc.
announced the availability of a public beta version of its Elastic Compute Cloud (EC2) with Windows Server 2003. The default Amazon
Machine Image (AMI) creates a 32-bit small instance with IIS, .NET 2.0 SP1, 3.0 SP1, and 3.5 (not SP1), and SQL Server Express 2005. The
Azure Services Platform October 2008 community technology preview provides services similar to Amazon EC2 with Windows Server (beta)
plus SimpleDB (beta), Simple Storage Services (S3), Simple Queue Services (SQS), and Elastic Block Store. This table compares the Azure CTP
instance and Amazon EC2 beta default instances.

VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE

23

0209vsm_F1Retire_14-25.v13

1/22/09

1:41 PM

Page 24

R E T I R E Y O U R D ATA C E N T E R

Theres considerable overlap of Azure Table Services


and SDS features, which portends a future

conflict at least as serious as that between LINQ to


SQL and the Entity Framework.
// Add the continuation tokens to the GET query
nextLink.NavigateUrl =

protected void Page_Prerender(object sender,

string.Format("?ct={0}/{1}", nextPartition,

EventArgs e)

nextRow);

{
// This LINQ to REST query gets a page of 12

// Customer entities at a time

// Set the customersView DataView's DataSource

// From paging code by Microsofts Steve Marx

// to the query result


customersView.DataSourceID = null;
customersView.DataSource = result;

var query =

customersView.DataBind();

(DataServiceQuery<CustomerDataModel>)
(new CustomerDataServiceContext(account).

CustomerTable.Take(12));
// Get the continuation tokens from the request
var cTokens = Request["ct"];

Youll also need code like this that runs once for each session in the
Global.asax.cs file to create the initial table from your TableName
DataModel class:

if (cTokens != null)
{

StorageAccountInfo account =
// ct parameter format is "<partition>/<row>"

StorageAccountInfo.

string[] tokens = cTokens.Split('/');

GetDefaultTableStorageAccountFromConfiguration();

var partitionToken = tokens[0];

TableStorage.CreateTablesFromModel

var rowToken = tokens[1];


// These QueryOptions become continuation
// token query parameters in the request
query = query.AddQueryOption(
"NextPartitionKey", partitionToken)
.AddQueryOption("NextRowKey", rowToken);
}
// Execute the LINQ to REST query
var result = query.Execute();
// Cast result to a QueryOperationResponse
var qor = (QueryOperationResponse)result;
// Get the continuation token values
string nextPartition = null;
string nextRow = null;
qor.Headers.TryGetValue(
"x-ms-continuation-NextPartitionKey",
out nextPartition);

(typeof(CustomerDataServiceContext), account);

After debugging your project in the SDKs local Developer fabric,


copy the ApplicationID from the Live Services and Active Directory Federation section of the Azure Services Development Portal
to the Portal page of the CloudService nodes Properties sheet,
right-click on the node, and choose Publish to open a window
containing your projects \bin\Debug\Publish folder. Click on
Deploy in the Manage pages Staging area to open the Staging
Deployment page, browse to the ProjectName.cspkg and ServiceConfiguration.cscfg files to fill the App Package and Configuration Settings text boxes, add a unique name (label) for the project
to the Properties text box, and click on Deploy to copy the package and configuration data to a Staging instance (see Figure 5,
p. 19). After you test the role with the private Web site URL, click
on the central icon to move the project to Production status and
test it with your public accountname.cloudapp.net URL (see Figure 6, p. 22).ClickTwice (once for Staging, once for Production)
deployment of roles to the Azure Fabric is a snapand much easier than migrating apps to AWS or the GAE.

qor.Headers.TryGetValue(
"x-ms-continuation-NextRowKey", out nextRow);
if (nextPartition != null && nextRow != null)
{

24

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

SDS vs. Azure


Theres considerable overlap of Azure Table Services and SDS features, which portends a future conflict at least as serious as that
between LINQ to SQL and the Entity Framework. A SQL

0209vsm_F1Retire_14-25.v13

1/22/09

1:41 PM

Page 25

R E T I R E Y O U R D ATA C E N T E R

The SQL Data Services team has promised

for months to support schemas and


full-text search in later CTPs.
Services Labs incubation project is in the works to align SDS with
the ADO.NET Data Services and enable Atom and JavaScript
Object Notation (JSON) as wire protocols. The SDS team intends
to add more relational-style features to the SDS data model in
the future.
According to Microsoft partner architect Gopal Kakivaya,
Among the things SQL Data Services will include in the future
are improvements in backup and restore, differential b-trees, distributed transactions, geo-replication (synchronous and asynchronous), distributed materialized views, job framework, and
distributed queries.
The SDS team has promised for months to support schemas
and full-text search in later CTPs. SDS probably will become a
premium offering, with a substantial surcharge over basic Azure
Table Storage. For example, Amazon extracts a $0.60 to $1.20 per
instance-hour surcharge for SQL Server 2005 Standard. (SQL
Server 2005 Express comes free with the $0.125 to $1.20 hourly
charge for Windows Server 2003 R2 instances.) Amazons surcharge for Windows Authentication Services is $0.25 to $0.60 per
instance-hour, depending on instance type. That totals $7,344 to
$15,552 extra per instance-year. Windows Azure with Azure Table
Storage probably will be the price leader that entices enterprises
to give Azure Platform Services a serious shot at playing a significant role in their data center expansion plans. VSM
Roger Jennings is an independent data-oriented .NET developer and
computer book author with more than 1.25 million English copies in
print. His books on Microsoft operating systems and data technologies
have been translated into more than 20 languages. Jenningss latest
book is Professional ADO.NET 3.5 with LINQ and the Entity
Framework (WROX/Wiley 2009). Hes also a Visual Studio Magazine
contributing editor and writer for Redmond Developer News, and
manages the OakLeaf Systems blog (oakleafblog.blogspot.com). You
can reach him at Roger_Jennings@compuserve.com.
ADDITIONAL RESOURCES:
Azure Services Platform homepage: tinyurl.com/6lr5nr
MSDN homepage for Azure developers: tinyurl.com/65ogcw

Setting Up the Windows Azure Services Platform: An Illustrated Walkthrough OakLeaf blog post: tinyurl.com/65wywn
Ray Ozzie and Amitabh Srivastava PDC 2008 Day One Keynote video
(Channel9): tinyurl.com/5tsgvm; transcript: tinyurl.com/5vhprm
Video clips of 39 Azure-related sessions at PDC 2008 (Channel9):
tinyurl.com/5vd7cr
Video clips of eight SQL Data Services-related sessions at PDC 2008
(Channel9): tinyurl.com/638uoo
Azure SDK online documentation: tinyurl.com/6yy75b
SQL Services Labs home page with planned incubation projects for SDS
tinyurl.com/5asfdm
Windows Azure TablesProgramming Table Storage white paper:
tinyurl.com/59tlo7
Windows Azure TablesProgramming Blog Storage white paper:
tinyurl.com/6785ra
Issues and Constraints in the Windows Azure Tools and SDK white
paper tinyurl.com/4m92h9
The Atom Syndication Format (1.0) specification (IETF RFC 4287):
tinyurl.com/ysewpe
Amazon Elastic Compute Cloud (EC2) Running Microsoft Windows Server
and SQL Server (Beta) data sheet: tinyurl.com/4xw9cw
Amazon Elastic Compute Cloud (Amazon EC2) data sheet:
http://tinyurl.com/4bw86s
ADO.NET Data Services in Windows Azure: pushing scalability to the next
level blog post by Pablo Castro tinyurl.com/4ky4x2
Comparing Google App Engine, Amazon SimpleDB and Microsoft SQL
Server Data Services OakLeaf Systems blog post: tinyurl.com/626td8
Test Harnesses Compare Amazon EC2 with SQL Server and SimpleDB
Performance OakLeaf Systems blog post: http://tinyurl.com/5ea99x
SQL Data Services (SDS) Test Harness Updated to the Windows Azure
Services Platform OakLeaf Systems blog post: tinyurl.com/58tw7c
Test-Drive SQL Server Data Services by Roger Jennings: Locator+ Code
VS0807RJ_T
Manipulate Data in the Cloud by Roger Jennings: Locator+ Code
VS0805RJ_T

Windows Azure SDK (October 2008 CTP) download: tinyurl.com/5pha33


GO ONLINE
Windows Azure Tools for Microsoft Visual Studio (October 2008 CTP)
download: tinyurl.com/58oega
Azure Services Training Kit - PDC Preview download: tinyurl.com/5z87ru
Register with Microsoft Connect to access Azure services online:
tinyurl.com/5urpnv

Use this Locator+ code at VisualStudioMagazine.com to go directly to these


related resources.
READ & DOWNLOAD
VS0902RJ Read this article online and download the SampleWebCloudService
project for this article.

VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE

25

0209vsm_C#Corner_26-29.v8

1/22/09

C# CORNER

1:43 PM

Page 26

USING EXPRESSIONS

Use Lambda Expressions


for Abstract Delegates
Lambda expressions are
nothing more than
convenient syntax for
delegates. So why cant you
use them where the
Framework expects a
delegate? And more
importantly, what can you
do about it?
BY BILL WAGNER

ve written before about how much I like lambda expressions and the way type inferences work
in C#. I think lambda expressions have more clarity than the combination of delegate definitions and out-of-band method definitions and the related extra work you have to do only to satisfy
the language definitions. But, there are some weaknesses. If a methods parameters contain the
System.Delegate abstract type, using lambda expressions introduces special problems: The C#
compiler cant convert a lambda to some not-yet-defined concrete, derived delegate type.
Without some extra thought on your part, youll end up with code that looks like it came from
.NET 1.0. Ill walk you through the exercise of understanding why lambda expressions arent immediately
convertible to abstract delegate types, and how you can convince the compiler to convert the specific
delegate type you defined for your use. The solution Ill describe relies on Windows Presentation
Foundation (WPF) and the System.Windows.Threading.Dispatcher component, but this is not strictly
a WPF issue. The issue described crops up in several locations in the .NET Framework, including the
Windows Forms, Office APIs, and Reflection APIs.Youll be able to follow the approach described in this
article when you see it crop up in those other technologies as well.
Whenever I use an API in the .NET Framework that has a parameter thats some form of delegate, I
prefer to use a lambda expression instead of a more verbose representation. For example, this line of code
creates a System.Windows.Threading.Timer that calls the method TickHandler when the timer fires:

TECHNOLOGY TOOLBOX
VB.NET
C#
SQL Server
ASP.NET
XML

tick = new System.Threading.Timer((unused) =>


TickHandler());

26

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

ILLUSTRATION BY ISTOCKPHOTO.COM

0209vsm_C#Corner_26-29.v8

1/22/09

1:43 PM

Page 27

C# CORNER USING EXPRESSIONS

Whenever youre not sure what thread youre on, you can call

Dispatcher.CheckAccess() to determine whether


you can access any UI controls.
If the body of the method were small enough, I would replace the
TickHandler() method call with the body of the method. That
approach works fine most of the time,but the same technique doesnt
work when the API uses System.Delegate as a parameter.For example,
you use the System.Windows.Controls.Dispatcher.Invoke() method
to marshal calls across threads in WPF:
public object Invoke(

I built a WPF timer application to show you how this works,


illustrating how a little C# 3.0 can make it easy to work with these
older APIs (see Figure 1). The timer is quite simple: You give it a
length of time and press start. The background changes from light
green, to yellow, to red as time runs out.
Updating the display based on time requires responding to
events from a timer. Timers run on background threads, so youll
run headlong into the problem I described at the outset.

delegate method,
params object[] args)

Now consider what happens when you try to use a lambda expression for this call:

Updating the Application


The UI handling code is straightforward. The work happens when
the timer fires, and the code updates the timer display. The update
must change the text, and possibly the background for the control.
Thats a couple quick lines of code:

MyTime.Dispatcher.Invoke(() => DoSomething());


MyTime.Background = newBrush;

You get the cryptic error:

MyTime.Content = label;

error CS1660: Cannot convert lambda expression to

The timer runs on a background thread, so you need to marshal the


call across the thread boundary using the Dispatcher.Invoke()
method. These two lines of code are what youd want to put in a
lambda expression, not the heavy-duty business logic that justifies a
method definition. But I said earlier that a lambda doesnt work with
Dispatcher.Invoke. It can, but you need to use a concrete delegate
definition. Several are defined in .NET Framework 3.5. The fact that
you can use the built-in delegate definitions and assign them makes
this solution less work than might initially appear to be the case.
These two lines also require a pair of parameters: a string for the content and a brush for the background color. That means you need to
use a delegate definition that takes two parameters and returns void:

type 'System.Delegate' because it is not a delegate type

Youll probably wonder whats going on the first time you see this
error. Of course, its a delegate type, right? Well, the compiler isnt
quite as smart as you are.The System.Delegate type is an abstract type,
and the type inference engine cant infer the number and types of the
arguments or the return value for some unknown delegate type
derived from System.Delegate. To fix this problem, you must create a
concrete delegate type and assign your lambda expression to that
type. Before you delve too far into the distant past and begin writing
C# 1.0 code, remember delegate types let you treat methods as data.

Action<string, Brush> updateTimer;

After declaring the variable,you can assign the delegate variable to the
body of the code you want to execute. You can use a lambda expression here because Action<T1, T2> is a concrete delegate definition:
updateTimer = (label, newBrush) =>
{
MyTime.Background = newBrush;
MyTime.Content = label;

FIGURE 1 WPF Timer Application Running This sample application


runs a timer while you practice a presentation. The color changes from
green to yellow to red as you run out of time. Its a great way to demo
cross-thread calls, because the timer runs in a background thread.

};

Now youve got a member variable that points to the block of code
that you want to execute when the timer raises its event. All thats
left is to use the delegate definition with Dispatcher.Invoke():

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

27

0209vsm_C#Corner_26-29.v8

1/22/09

1:43 PM

Page 28

C# CORNER USING EXPRESSIONS

else

if (!MyTime.Dispatcher.CheckAccess())

updateTimer(newLabel, next);

{
MyTime.Dispatcher.Invoke(updateTimer,

This process is straightforward, but its something that youll do


repeatedly, so lets go a few steps further and make this easier to reuse.
Theres a simple pattern at work here.
Event handlers can be called from a background thread. Youll see this behavior when
you use timers, when you call Web services
LEADTOOLS v.16 .NET, WPF, WCF,
asynchronously, and in other common tasks.
WF, C API, C++ Class Lib, COM & more!
Whenever youre not sure what thread youre
Barcode
Document
Form Recognition & Processing
on, you can call Dispatcher.CheckAccess() to
determine whether you can access any UI controls. If you need to marshal a call across
thread boundaries, you must use
Dispatcher.Invoke().The Dispatcher.Invoke()
method avoids several different overloads by
Mark-up
Multimedia
DICOM Medical
using a params array for any parameters to the
method; it uses an abstract delegate type for
the code that you want to execute.
You want a single method that checks
whether marshaling is needed. If marshaling is needed, the method marshals the
call; otherwise, it calls the method pointed
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
to by the delegate. You want that method to
Hospitals.
appear as if it were a member of the SysLEADTOOLS provides developers easy access to decades of expertise in color, grayscale,
document, medical, vector and multimedia imaging development. Install LEADTOOLS to
tem.Windows.Controls.Control class. This
eliminate months of research and programming time while maintaining high levels of
quality, performance and functionality.
enables you to use the code as if it were part
of any control. C# 3.0 gives you a way to do
Image Formats: All industry standards
Medical Web Viewer Framework: Plug-in
this: extension methods. You need to write a
including TIFF, EXIF, PDF, JPEG/JPEG2000,
enabled framework to quickly build high
DICOM, PCL, DWG and hundreds more.
quality,full-featured, web-based medical image
few different overloads of the methods,which
Image Compression: From standard
delivery and viewer applications.
JBIG, JBIG2, ABIC, JPEG and CCITT G3/G4 to
Medical Image Viewer: High level display
enables you to use them with different numLEADs specialized ABC, CMP and CMW
control with built-in tools for image mark-up,
bers of parameters:
compression.
window level, measurement, zoom/pan, cine,
newLabel, next);

Display Controls: Scroll, zoom, pan,


magnify glass, brightness/contrast/gamma,
window level.
Image Processing: 200+ lters, 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
lled 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 les.
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.

and LUT manipulation.


DICOM: Full support for all IOD classes and
modalities dened 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 and WIA(32 and 64-bit),
autodetect 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
800 637-1840

public static class WPFExtensions:


{
public static voidInvokeIfNeeded(
this Control widget,
Action whatToDo)
{
if (!widget.Dispatcher.
CheckAccess())
widget.Dispatcher.Invoke(whatToDo);
else
whatToDo();
}
public static void
InvokeIfNeeded<T>(
this Controlwidget, Action<T>
whatToDo, T parm)

28

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

0209vsm_C#Corner_26-29.v8

1/22/09

1:43 PM

Page 29

C# CORNER USING EXPRESSIONS

Use this Locator+ code at VisualStudioMagazine.com to go directly to


these related resources.

{
if (!widget.Dispatcher.CheckAccess())

READ & DOWNLOAD

widget.Dispatcher.Invoke(whatToDo, parm);

VS0902CC Read this article and download the sample code online.

else
whatToDo(parm);
}
public static void
InvokeIfNeeded<T1, T2>(this
Controlwidget, Action<T1, T2>
whatToDo,
T1 parm1, T2 parm2)
{
if (!widget.Dispatcher.
CheckAccess())
widget.Dispatcher.
Invoke(whatToDo,
parm1, parm2);
else
whatToDo(parm1, parm2);
}
}

Of course, you can extend this class by


adding more overloads with more parameters. Its a simple extension.
There was a method to the WPF designers madness: They wanted to make it as easy
as possible to use the Dispatcher object by
minimizing the surface area of the API. By
using abstract delegates, and params on the
parameter list, this object is usable in the
widest possible number of scenarios. Any
method with any number of parameters can
be used. However, that comes with a downside. This more abstract API removes all type
safety, and this hurts the compilers ability to
use type inference to make you more productive. The work around is to add your own
layer of type-safe extension methods that
provide a layer between your type safe calls
and the more abstract .NET library API. VSM
Bill Wagner, author of Effective C# (2004)
and More Effective C# (2008), both from
Addison-Wesley Professional, 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. E-mail
Wagner at wwagner@srtsolutions.com.

The LEADTOOLS Competitive Upgrade


Call Our Sales Dept. (800) 637-4699
for details. Valid through March 31, 2009.
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.

One Company For Any Imaging Need


Flexible Licensing, Royalty Free Options
Time Tested, Easy to Use
Free Technical Support
Document

Form Recognition & Processing

Barcode

Mark-up

DICOM Medical

Multimedia

Chosen by thousands of companies for use in their high


volume applications and internal systems.

Free 60 Day Evaluation!

www.leadtools.com/vsm

LEADTOOLS SDKs feature LEADs iCompress Technologies.

GO ONLINE

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

29

San Francisco
Hyatt Regency Embarcadero
February 23-27, 2009

Buy One VSLive! Conference


Registration Get One FREE*
Calling All Developers
VSLive! Is Expecting You!
Take advantage of this recession busting breakregister for
VSLive! and bring a colleague absolutely FREE OF CHARGE!
Thats up to an $1,800 savings to you and your company
Join us at VSLive! San Francisco and you can expect these great activities:
Attend the Microsoft MSDN Developer Conference FREE
(pre-con event, Monday Feb 23. Space is limited;
first come, first served.)

Listen to amazing speakers in over 80 sessions


spanning existing technologies, Microsofts newest
releases, and yet-to-be-shipped tools

Participate in the NEW VSLive! After Darkan informal


open ended chat with VSLive! speakers, attendees
and industry experts

Visit the Exhibitor Expo and VIP Lounge & Game Center
(sponsored by ComponentOne)
Book signings with some of your favorite technical authors

To view the complete agenda and register for VSLive! go to vslive.com/sf2009

Be sure to use priority code NQ9F14 to get the 2 for 1 savings!


Brought to you by:

VSL_VSM_Feb09.indd 1

1/20/09 12:43:30 PM

vslive.com/sf2009
Be sure to use priority code
NQ9F14 to get the 2 for 1 savings!
Meet these Experts in Person at VSLive! San Francisco:

2 FOR 1
SAVINGS!

UP TO

1800*

Rockford Lhotka on Silverlight, and


Building Distributed Apps in .NET 3.5 SP1
Lhotka is principal technology evangelist for Magenic Technologies and the
conference co-chair, and a well-known author and magazine contributing
editor who speaks regularly at major conferences worldwide.

Richard Hale Shaw on LINQ


Shaw has created and chaired numerous technology conferences and is
a popular and articulate speaker and writer who is well known for
his criticisms of non-functioning developer tools

Aaron Skonnard on Dublin, Windows Azure,


and Whats New in WCF/WF 4.0
Skonnard is co-founder of the Microsoft .NET training provider Pluralsight
and author of numerous books, articles, whitepapers, and courses.

Brian Randell on TFS 2010, Database Design,


and Team System 2008
Radell is a well-known software developer, consultant, speaker, course
developer and educator. A senior consultant with MCW Technologies, he
writes the Team system column for MSDN Magazine.

Bill Vaughn on ADO.NET 3.5 SP1 for Visual Studio


and SQL Server and Visual Studio ReportingLeveraging the
New SQL Server 2008 RDL Technology
Vaughn is a 35-year veteran of the computer industry, author of the
critically acclaimed book Hitchhikers Guide to SQL Server 2000 Reporting
Services and top expert on Microsoft Visual Studio, SQL Server, Reporting
Services and data access interfaces.

Deborah Kurata on
Visual Studio and .NET Framework Secrets
Deborah Kurata, president of InStep Technologies, .NET expert with over 15
years experience in application architecture, design and development, and
author of several books, including Best Kept Secrets in .NET.

Dave Bost on Prism, and a deep dive into ASP .NET 3.5 SP1
Bost, who has been a developer and solution architect for over 15 years,
is a Developer Evangelist with Microsoft and co-hosts the
Thirsty Developer Podcast.
* Choose either the VSLive! Plus Package (Five day all access pass Feb. 23-27), or the VSLive! Conference Package (Three day pass Feb 24-26). The Buy One Get
One FREE offer cannot be combined with other discounts or coupons. The second conference pass must be of equal or lesser value than the first conference pass.

VSL_VSM_Feb09.indd 2

1/20/09 12:43:35 PM

0209vsm_OnVB_32-38.v9

ON VB

1/22/09

1:36 PM

Page 32

I T E R AT O R S I N V B

Use Iterators in VB Now


Iterators are a crucial part of
modern programming, not
least because they provide
the basis for collection
traversal using For Each loops.
Language Integrated Query
(LINQ) adds to the importance
of iterators, as iterators are
the source of IEnumerable(Of
T) that forms the backbone
of LINQ. Learn how to take
advantage of them in your
code with several different
techniques for creating your
own iterators in VB.
BY BILL MCCARTHY

n Visual Studio 10, Visual Basic and C# will officially attempt to converge rather than diverge.
The two languages are touted by Microsoft to have the same major language features as each
other; Microsoft also promises language parityand an end to the sibling rivalry.For C#, this
means the inclusion of long-standard VB features such as late binding and optional parameters.
For VB, it means the inclusion of multi-expression lambdas and auto properties. This parity is
not absolute: For example, C# wont have XML literals, making VB still the best language for working
with XML. One thing VB is not likely to get in the next release is iterators.
Iterators in C# are a language feature that enables you to write a complete implementation for an
enumerable object in a single method. An enumerable object is one that you can perform For Each
loops or LINQ queries on. Arrays, Lists, and Collections are all common examples of enumerable
objects. In fact, enumerable objects are so common in the .NET Framework that you rarely need to
define your own. Still, its important you understand the basics of what enumerable objects are and how
to create them should the need ever arise.
Lets kick things off with some common examples for iterators youll see in C#. The first is from the
C# documentation:

I
TECHNOLOGY TOOLBOX

C#

public int[] items;

SQL Server 2005

public IEnumerable BuildCollection()

ASP.NET

{
for (int i = 0; i < items.Length; i++)
{

32

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

PHOTO BY ISTOCKPHOTO.COM

VB.NET

0209vsm_OnVB_32-38.v9

1/22/09

1:36 PM

Page 33

O N V B I T E R AT O R S I N V B
O B J E C T / R E L AT I O N A L M A P P I N G W I T H L I N Q R O S Q L

I have seen many cases where iterator blocks are superfluous.


Superfluous code is an evil because it adds to the
testing and maintenance burdens.
} while (currentCharacter++ < 'z');

yield return items[i];


}

}
}

I hope youre laughing at that sample. If you arent, some explanation might help you see the humor. The code shows a method that
returns an IEnumerable: This is what an iterator is in C#. The yield
return statement indicates what is returned when the code is enumerated with a For Each loop or similar. So, this code iterates over
an array and returns each item in the array. In other words, it is
superfluous and just adds overhead, as an array is already enumerable. That method could have just returned the array cast to
an IEnumerable.
You might think thats just a one-off, bad-code example. Sadly,
I have seen many cases where iterator blocks are superfluous.
Superfluous code is an evil because it adds to the testing and maintenance burdens. But not all cases are superfluous. Bill Wagner in
his December 2008 C# column (What VB Devs Should Know
About C#) showed a good example of creating an iterator that will
give you the letters a to z as you enumerate it:
public static IEnumerable<char> Letters()
{

This code shows an important aspect of iterators: Theyre state


machines. The variable currentCharacter is modified each time
you enumerate the IEnumerable returned from Letters. To achieve
the same result in VB could require some substantial work on your
part, but there are, as they say, many ways to skin a cat (note: no
felines were harmed in the production of this code). For example,
you could create an array of Char, populate it, and return that:
Dim letters(0 To 25) As Char
For i As Int32 = 0 To 25
letters(i) = ChrW(&H61 + i)
Next

This will work, but its a bit messy. An alternative approach is to


refactor this method. The code inside the For i As Int32 = 0 to 25 loop
is an expression in a range, so you can use the Enumerable.Range
method as part of a LINQ expression:
Dim letters = From i In Enumerable.Range(0, 26) _
Select ChrW(&H61 + i)

char currentCharacter = 'a';


do
{
yield return currentCharacter;

This is a little better, but there are other ways to approach this
problem, as well. A String is in fact enumerable and implements
IEnumerable(Of Char), so you can simplify everything to a single
string declaration:
Dim letters = "abcdefghijklmnopqrstuvwxyz"

FIGURE 1 Create the Interfaces of an Iterator VB doesnt come


with iterators out-of-the-box, as the next version of C# will, but its
possible to create your own, and what you can create is more versatile than the plain-vanilla iterators youll be able to create with the next
version of C#. These are the interfaces and the members you must
implement to create your own iterator.

This alternative certainly seems far more maintainable and a lot


more obvious too.
Of course, this example is a simple one. If it were more complex,
such as fetching values from somewhere or calculating the values, the
differences between the solutions become much more meaningful.
Both the first and last solution are based on having the complete set of
characters in memory to begin with, whereas the solution that uses
the Enumerable.Range method loads the characters only when you
iterate over the letters.This is often referred to as delayed evaluation.
Delayed evaluation, or on-demand evaluation as I prefer to
call it, is an important aspect of iterators and especially of LINQ.
Its also something you need to be wary of when translating C# code
to VB or when you look for alternatives to iterators. Typically, LINQ
expressions and utility methods such as Range provide solutions
that have the desired, on-demand evaluation behavior.
However, there are times when you will find it necessary to
write an iterator. One such case occurred for me recently. I wanted

VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE

33

0209vsm_OnVB_32-38.v9

1/22/09

1:36 PM

Page 34

O N V B I T E R AT O R S I N V B

to read from a stream line-by-line, search for a substring, and


return the first couple of matches. Unfortunately, StreamReader
doesnt have an iterator that returns each line. Without something
that is enumerable, you cant form the basis of a LINQ query, so
youre forced to write your query imperatively. Thats not as bad as
it might first sound; VB developers were doing this successfully for
years before LINQ came along:
strLine = myStreamReader.ReadLine
Do While strLine IsNot Nothing

VB

If strLine.Contains(value) Then
count += 1
resultList.Add(strLine)
If count >= 3 Then Exit Do
End If
strLine = myStreamReader.ReadLine
Loop

Building the query into the imperative procedural block does


work, although its kind of on the ugly side. I look at that code,

EXTEND THE STREAMREADER CLASS

Module StreamExtensions
<Extension()> _
Function Lines(ByVal rdr As TextReader) _
As IEnumerable(Of String)
Return New StreamReaderLineEnumerator(rdr)
End Function
End Module

Public Class StreamReaderLineEnumerator


Implements IEnumerable(Of String)
Implements IEnumerator(Of String)
Private _rdr As TextReader
Private _current As String
Sub New(ByVal rdr As TextReader)
_rdr = rdr
End Sub

''' <summary>
''' Get's an enumerator to read lines from a stream
''' </summary>
''' <returns>IEnumerator(Of String)</returns>
''' <remarks>Can only be called once due to the
''' underlying stream.
''' Not thread safe.</remarks>
''' <exception cref="InvalidOperationException">
''' thrown if GetEnumerator is called more
''' than once</exception>
Public Function GetEnumerator() _
As IEnumerator(Of String) _
Implements IEnumerable(Of String).GetEnumerator
Static iFirstTime As Int32
If iFirstTime = 0 AndAlso _
Threading.Interlocked.Increment( _
iFirstTime) = 1 Then
Return Me
Else
Throw New InvalidOperationException( _
"GetEnumerator can only be called " & _

"once on a stream")
End If
End Function

Private Function IEnumerator_GetEnumerator() _


As IEnumerator _
Implements IEnumerable.GetEnumerator
Return GetEnumerator()
End Function

Public ReadOnly Property Current() As String _


Implements IEnumerator(Of String).Current
Get
Return _current
End Get
End Property
Private ReadOnly Property IEnumerator_Current() _
As Object Implements IEnumerator.Current
Get
Return Current
End Get
End Property

Public Function MoveNext() As Boolean _


Implements IEnumerator.MoveNext
_current = _rdr.ReadLine()
Return _current IsNot Nothing
End Function
Private Sub Reset() Implements IEnumerator.Reset
Throw New NotImplementedException()
End Sub
Public Sub Dispose() Implements _
IDisposable.Dispose
'not implemented
End Sub
End Class

LISTING 1 Most of what you see in the class is boilerplate code, with the two methods of interest being GetEnumerator and the MoveNext
method. This sample also illustrates how to add an extension method to make getting the enumerator a lot simpler. The extension method will
show up on an instance of the StreamReader class as a Lines function.

34

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

0209vsm_OnVB_32-38.v9

1/22/09

1:36 PM

Page 35

O N V B I T E R AT O R S I N V B
O B J E C T / R E L AT I O N A L M A P P I N G W I T H L I N Q R O S Q L

and it screams to me that it needs to be beautified. Im not the


type of person who tends to talk about beautifying codethe
May 2007 On VB column headline,Beautify Your Code, was created by an editorbut an extension method is the kind of thing
that can help you add some beauty to this code.
If you have an extension method named Lines that returns
an IEnumerable with each item a line, then you can create a query
like this:

static class StreamExtensions


{
static public IEnumerable<String> Lines(
this TextReader rdr)
{
String line;
while ((line = rdr.ReadLine()) != null)
{
yield return line;
}

Dim result = From line In myStreamReader.Lines _


}

Where line.Contains(value) _
}

Take 3

I think that approach is a clear winner for the most beautiful solution. The difficulty is in creating the Lines extension method. If you
dont mind having a C# assembly as a reference, its a simple task to
create an Extension method thats an iterator:

VB

This can take substantially more work in VB.You have to implement


IEnumerable(Of T) and IEnumerator(Of T), which also includes the
non-generic IEnumerable, IEnumerator, and IDisposable interfaces.
Thats a class (or classes) with at least seven members, eight if you

CREATE A GENERICITERATOR CLASS

Public Class GenericIterator(Of T)


Implements IEnumerable(Of T)
Implements IEnumerator(Of T)
Public Delegate Function MoveNextFunc( _
ByRef nextItem As T) As Boolean
Private _Current As T
Private _func As MoveNextFunc
Public Sub New(ByVal func As MoveNextFunc)
_func = func
End Sub

Public Function MoveNext() As Boolean _


Implements IEnumerator.MoveNext
Return _func(_Current)
End Function

Public Function GetEnumerator() _


As IEnumerator(Of T) _
Implements IEnumerable(Of T).GetEnumerator
Static iBeenCalled As Int32
If (iBeenCalled = 0) AndAlso _
(Threading.Interlocked.Increment( _
iBeenCalled) = 1) Then
Return Me
Else
Return New GenericIterator(Of T)(_func)
End If
End Function

Public ReadOnly Property Current() As T _


Implements IEnumerator(Of T).Current
Get
Return _Current
End Get
End Property
Public Overridable Sub Reset() _
Implements IEnumerator.Reset
Throw New NotImplementedException( _
"Iterator cannot be reset")
End Sub

Private Function _
IEnumerator_GetEnumerator() As IEnumerator _
Implements IEnumerable.GetEnumerator
Return Me.GetEnumerator
End Function
Private ReadOnly Property IEnumerator_Current() _
As Object Implements IEnumerator.Current
Get
Return Me.Current
End Get
End Property
Public Sub Dispose() _
Implements IDisposable.Dispose
' not implemented
End Sub
End Class

LISTING 2 This class is most useful in VB10, where you can pass in a multi-statement lamba expression for the MoveNextFunc. You can use this
generic template in VB8 and VB9, but without support for multi-statement lambdas youll find that youll need to use AddressOf, and capture
variables used by making them fields of a wrapper class. As a consequence, youre better off using the direct implementation (Listing 1,
opposite page) rather than the generic template for versions of VB prior to VB10.

VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE

35

0209vsm_OnVB_32-38.v9

1/22/09

1:36 PM

Page 36

O N V B I T E R AT O R S I N V B

include the constructor (see Figure 1, p. 33). The good news is that
most of these methods are typically implemented with the same
boilerplate code. This means that you can streamline creating iterators in VB by using techniques such as snippets, templates, or
generic classes.
You must implement three methods for the IEnumerator

New 7.0
e
mag
DotI ease
Rel

interface: MoveNext, Reset, and Current, a ReadOnly property.


Reset is seldom used. It cant be used inside a For Each loop, so
for most of your implementations you can Throw a NotImplementedException as the body of the Reset method. The important method is MoveNext. In the MoveNext method, you determine whether there are more items to return. If there are, you
store the next item to return in the Current property. This means the Current
property needs to return only a field.
Next, add the generic interface IEnumerator(Of T). Then add Current As T, a
strongly typed ReadOnly Property, as well
as an IDisposable.Dispose implementation. At this point, you have two ReadOnly properties named Current that wont
compile, or you have one named Current
and the other named Current1. A good
way to deal with this is to make the least
strongly typed method Private. This
allows you to give the method a name for
internal use. You can still access the private method externally through a cast to
the interface:
Private m_Current As T
Public ReadOnly Property _
Current() As T _
Implements IEnumerator( _

The .NExT Step In Document


and Photo Imaging

Of T).Current
Get
Return m_Current
End Get

DotImage 7.0More Powerful,


with Zero-Footprint Imaging, and
3 Months of Free Gold Support.

End Property
Private ReadOnly Property _
IEnumerator_Current() _
As Object _

New features to our already powerful imaging toolkit include PDF/A


support, AJAX Vector Annotations including FreeHand, WPF annotations, and more. Use templates in our AJAX Wizard to create zerofootprint web applications in C# and VB.NETTake document and
photographic imaging to the .NExT step.
Visit Atalasoft.com for web demos, video tutorials, and a free trial.

Atalasoft, Your .NET Imaging Partner


Call us toll free at 866-568-0129

www.atalasoft.com

36

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

Implements IEnumerator.Current
Get
Return Current
End Get
End Property

You must also implement IEnumerable(Of T). This includes a single function
(GetEnumerator), in which you return
your IEnumerator(Of T) implementation.
As part of the IEnumerable(Of T) interface, you must also implement the nongeneric IEnumerable interface. IEnumerable also has a GetEnumerator function,

0209vsm_OnVB_32-38.v9

1/22/09

1:36 PM

Page 37

O N V B I T E R AT O R S I N V B
O B J E C T / R E L AT I O N A L M A P P I N G W I T H L I N Q R O S Q L

The VB version is obviously lengthier than the C# version,


but the VB version has some
significant benefits.
but its return type is the non-generic IEnumerator. As you did with the Current property and IEnumerator, make the IEnumerable GetEnumerator method Private and
have it call the more strongly typed generic
method:
Public Function GetEnumerator() _
As IEnumerator(Of T) _
Implements IEnumerable( _
Of T).GetEnumerator
'TODO: add implementation here
End Function
Private Function _
IEnumerable_GetEnumerator() _
As IEnumerator Implements _
IEnumerable.GetEnumerator
Return GetEnumerator()
End Function

The code you put inside the GetEnumerator method deserves careful consideration.
You need to think through how you expect
these implementations to be used, as well
as how they will behave in cases such as
multi-threaded environments or when
changes occur. Enumerators are normally
considered to be a snapshot. For example,
List(Of T)s enumerator will throw a runtime exception if the list is changed during
a For Each iteration. Other iterators might
just ignore changes. In the case of a stream,
your decision is a bit tougher.
You change a streams position as you
read from it. For example, if there are two
iterators reading from the one stream, the
results could be unpredictable, changing
depending on threading behaviors. There
are two ways around this problem: Use a
null stream and have the iterators return
no data, or throw an exception in GetEnumerator if it has been called previously.
Throwing an exception makes it easier to
debug what went wrong. Whichever
choice you make, take the time to document it by completing the XML comments
on the method:

VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE

37

0209vsm_OnVB_32-38.v9

1/22/09

1:36 PM

Page 38

O N V B I T E R AT O R S I N V B

''' <summary> Get's an enumerator to read lines


''' from a stream </summary>
''' <returns> IEnumerator(Of String) </returns>
''' <remarks> Can only be called once due to the

and combine this with a generic template to give you the same
functionality from VB.
To do this, you need to define a delegate in your generic template that has the current item as a ByRef parameter:

''' underlying stream.


''' Not thread safe. </remarks>
''' <exception cref="InvalidOperationException">
''' thrown if GetEnumerator is called more than once
''' </exception>
Public Function GetEnumerator() As IEnumerator(Of String) _
Implements IEnumerable(Of String).GetEnumerator
Static iFirstTime As Int32
If iFirstTime = 0 AndAlso _

Public Delegate Function MoveNextFunc( _


ByRef nextItem As T) As Boolean

Your generic iterator takes a delegate in its constructor, stores a reference to it, and calls that in the MoveNext method. Once you
define the GenericIterator class (see Listing 2, p. 35), you can use
this much as you use inline iterators in C#. For example, you can
create a line-by-line iterator with a StreamReader:

Threading.Interlocked.Increment(iFirstTime) = 1 Then
Return Me
Else
Throw New InvalidOperationException( _
"GetEnumerator can only be called once on a stream" )
End If

Dim lines = New GenericIterator(Of String) _


(Function(ByRef nextItem As String) As Boolean
nextItem = rdr.ReadLine
Return nextItem IsNot Nothing
End Function)

End Function

There are a couple of points worth discussing in this code. The code
relies on a static variable inside the code to check whether the
method has been called previously, and uses Threading.Interlocked.Increment to change the value. This ensures that it can be
called only once, even in a thread-race condition. If it has been
called more than once, an InvalidOperationException is thrown.
Note that the method returns a Me reference when called for the
first time. This is because the class implements both the IEnumerable(Of T) interface and the IEnumerator(Of T) interface. You can
separate them into different classes, but often its useful to have
them in a single class because you generally need to store some
shared state in them (see Listing 1, p. 34, for a complete example of
a StreamReaderLineEnumerator).
The VB version is obviously lengthier than the C# version,
but the VB version has some significant benefits. First, your
implementation is likely to be more robust because youve been
forced to look at the implementation details. Second, the C# version doesnt prevent GetEnumerator being called more than
once on the same stream. This could result in some obscure
threading problems. It could also produce seemingly null result
sets for files if the iterator is called twice. Or, it could potentially
result in some object-disposed exceptions occurring that arent
explicit in describing the real problem. The C# version does provide a quick-and-dirty way to write the iterators: The quick part
is inviting, but its often the dirty part that we spend a lot more
time cleaning up after.
Its important to note that iterators in C# arent always dirty.
Sometimes they do provide an elegant and clean way to express an
IEnumerable. And its likely VB will get a similar syntax in the
not-too-distant future. In VB10, you will be able to use multistatement lambdas that capture surrounding variables. If youre
willing to accept the same limitations that iterators have in C#,
then you can use a lambda as the basis for the MoveNext method

38

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

The lack of a formal syntax for iterators in VB doesnt mean you cant
create iterators in VB. In fact, the download for this article includes a
snippet,templates,and examples of how you can write iterators easily
in the current version of VB. The download also includes an example
that illustrates how to use a generic template and lambdas in VB10.
Using the downloadable snippet or templates in the current version of
VB, you can quickly create iterators that are more flexible and more
robust than what the C# iterator syntax allows for.
As LINQ and PLINQ become more a part of your programming, your reliance on iterators will increase, so nows a good time
to learn how to write them properly. Being exposed to the implementation details will give you a better understanding of iterators
and their pitfalls, which means youll be less likely to yield to the
temptation of using them poorly when the day comes that VB too
adds some syntactic sugar for creating iterators.
So grab these downloads and start writing your own iterators today. VSM
Bill McCarthy is an independent consultant based in Australia and
is one of the foremost .NET language experts specializing in Visual
Basic. Hes been a Microsoft MVP for VB for the last 10 years and sat
in on internal development reviews with the Visual Basic team for
the last five years where he helped to steer the languages future
direction. These days he writes his thoughts about language direction
on his blog at http://billmccarthy.com.

GO ONLINE
Use this Locator+ code at VisualStudioMagazine.com to go directly to these
related resources.
READ & DOWNLOAD
VS0902OV Read this article and download the sample code online.

0209vsm_AdIndex_39.v3

1/22/09

1:44 PM

Page 39

Advertising Sales

Ad Index

East

Atalasoft, Inc.
www.atalasoft.com

36

dtSearch
www.dtsearch.com

12

ESRI
www.esri.com

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

Intel Corporation
www.intel.com

C4

West

LEAD Technologies, Inc.


www.leadtools.com

28, 29

Chris Kourtoglou
Regional Sales Manager
Phone: 415-814-0955
ckourtoglou@1105media.com

Microsoft Corporation
www.microsoft.com

20, 21

National Accounts Director


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

Microsoft Account Manager


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

Director, Print Production


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

Production Coordinator
Catharine Wood
Phone: 818-734-1520 ext 233
vsmadproduction@1105media.com
cwood@1105media.com

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

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

Software FX Inc.
www.softwarefx.com

37

C2, 1

TallApplications BV
www.deepseaobfuscator.com
TallComponents BV
www.tallcomponents.com

C3

Visual Studio Magazine


www.visualstudiomagazine.com

ID Statement
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,
email VSM@1105service.com or call toll free 888-768-8759,
fax number 847-763-9564. International calls 847-7639135. 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.

Pegasus Imaging Corporation


www.pegasusimaging.com

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

Corporate Address
Corporate Headquarters:
1105 Media
9121 Oakdale Ave. Ste 101
Chatsworth, CA 91311
www.1105media.com

Media Kits
Direct your Media Kit requests to:
Matt Morollo, VP Publishing
Phone: 508-532-1418
Fax: 508-875-6622
E-mail: mmorollo@1105media.com

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

List Rental
This publications subscriber list, as well as other lists from
1105 Media, Inc., is available for rental. For more information, please contact our list manager, Merit Direct.
Phone: 914-368-1000
E-mail: 1105media@meritdirect.com
Web: www.meritdirect.com

VSLive! San Francisco


www.vslive.com/2009/sf

30, 31

Wayside Technology Group Inc.


www.waysidetechnology.com

Edit Ad Index
Combit GmbH
www.combit.net/en

11

DataDirect Technologies
www.datadirect.com

11

MadCap Software
www.madcapsoftware.com

13

Resco
www.resco.net

12

Go to
VisualStudioMagazine.com
to access the stories in this
issue, plus read exclusive
online-only content.

VisualStudioMagazine.com February 2009 VISUAL STUDIO MAGAZINE

39

0209vsm_GuestOp_40.v8

1/22/09

The Human

1:38 PM

Page 40

Factor

WHERE DID ALL THE


DEVELOPERS GO?

BY DANIEL APPLEMAN

Google Trends (trends.google.com) is a curious tool. It displays the relative


popularity of search terms over time. Recently, a group of developers on a
software-developers forum noted that over the past five years, searches for
VB.NET have been declining to the point where they are now
below those for C#.
This, of course, means nothing. For one thing, Visual
Basic programmers use more than one search term (VB,
VB.NET,Visual Basic), while C# programmers use only C#, so
total VB searches, while trending downward, are probably still
well above C#. Besides, the whole VB versus C# discussion is
tiresomethe framework is where the real excitement is. If
C# use is growing at the expense of VB.NET, who cares?
Except that it isnt growing. The real surprise in the trend
line was that C# searches have been flat for years. This prompts
the question: If programmers are leaving VB and arent going
to C#, where are they going? Could it be that theyre abandoning Microsoft technologies?
I checked the trend lines for other programming languages and platforms, including PHP, Perl, Java, JavaScript,
and Flash programming. I discovered that C#, by holding flat,
is doing well because every other traditional language is
trending downward.
Why would this be? Perhaps developers are using
Live.com instead of Google? Id accept that if it were just the
Microsoft languages, but LAMP programmers leaving Google
for Live.com? I dont think so. Something real is happening.
Does use of language names as search terms correspond
to the popularity of a language? After all,experienced developers
dont often search for language nameswere much better at
refining our searches. People use language names as search
terms when theyre curious about them or when theyre just
starting out. They use them to find introductory articles and
tutorials. So were most likely looking at a specific population;
new developers and those who are switching languages. Could
the declining trend lines be indicating an overall drop in interest
in computer programming? Could it indicate a movement
away from traditional programming to newer platforms?
Its probably both. Statistics from the U.S. Department of
Education and National Science Board concur: Enrollment

40

VISUAL STUDIO MAGAZINE February 2009 VisualStudioMagazine.com

and degrees granted in computer science programs have been


dropping recently. This year many colleges (including top-tier
programs such as MIT, Rutgers, and Berkeley) report lower
enrollment. Carnegie Mellon, one of the top computer science
schools in the country, had only 2,000 applicants for its computer science department, down from 3,200 in 2001.
Google Trends is little more than a curiosity, a signpost to
reality. The surge of people who entered programming in the
80s is drifting away. Fewer people are entering the field. The
software development world has fragmented, with programmers being drawn from mainstream-development platforms
to new technologies such as iPhone and Facebook application
development (both of which are trending upward).
Theres another reality to be found on Google Trends. It
also lists the regions, cities, and languages where a search term is
most popular. Keeping in mind that language terms are most
popular with beginners and those learning a new language, its
interesting to note that the top three regions for C# are India,
South Africa, and Israel (the United States is No. 10), that the
seven top cities are in India and China, and that the No. 1search
language is Chinese. Indeed, similar region and language trends
apply across every language and dev platform I checked.
Where have all the coders gone? Now we know. But perhaps the better question is: Where are the new coders going to
come from? Thats something you can help answer, by teaching
your kids to code and by volunteering to help introduce or
teach programming in your local schools and community
colleges. And if you arent part of creating the answer, dont
complain if you dont like the answer you get. VSM
Dan Appleman is a Microsoft Visual Basic MVP, webmaster of
SearchDotNet.com, CEO of Desaware Inc, co-founder of Apress,
and sometime author, speaker, and blogger who has throughout
his career insisted that you cant talk technology without also
discussing its human and financial impact. You can reach him
at dan@desaware.com.

Project3

1/21/09

11:34 AM

Page 1

Project3

1/16/09

8:56 AM

Page 1

EVOLVE YOUR CODE.


Parallelism breakthrough.
Analyze, compile, debug, check, and tune your code for multicore
with Intel Parallel Studio. Designed for todays serial apps and
tomorrows parallel innovators.
Learn more and sign up for Beta: www.intel.com/go/parallel

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.

You might also like